http://stackoverflow.com/a/50633297
accepted answer of: http://stackoverflow.com/q/50633220
downvote count: 0
answers question: http://stackoverflow.com/q/50633220
upvote count: 2
type: AcceptedAnswer
type: Answer
has body: The problem here, as far as I can see on that screenshot is UltraColor file doesn't have the .py extension, for import to work properly you'll need to rename it from UltraColor to UltraColor.py, otherwise will raise an ImportError exception. For more information, take a look to this one. Import a python module without the .py extension
score: 2

http://stackoverflow.com/a/50690615
downvote count: 0
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50690333
has body: Try the below: merged_df = pd.merge(df1_master, df2_newValues, left_on='col_A', right_on='A1col', how='outer') merged_df.A2col.fillna(merged_df.col_C, inplace=True) merged_df.col_A.fillna(merged_df.A1col, inplace=True) merged_df = merged_df.drop(['col_C','A1col'], axis=1) merged_df.columns=['col_A','col_B','col_C'] merged_df

http://stackoverflow.com/a/76262704
downvote count: 0
score: 1
has body: This is what worked 4 me: MonthLabels = ['Feb', 'Mar', 'May', 'June', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] palette = ['#ff9100', '#ad0000'] # Use pd.Categorical to order the columns df1 = df.copy() df1['Month'] = pd.Categorical(df1['Month'], categories=MonthLabels) sns.histplot(data=df1, x='Month', palette=sns.color_palette(palette, 2), hue='Revenue', edgecolor='#FFF', kde=True, legend=True) plt.suptitle('Distribution of Revenue by Month') plt.show()
has comment: http://stackoverflow.com/comment/134486263
type: Answer
answers question: http://stackoverflow.com/q/50543055
upvote count: 1

http://stackoverflow.com/comment/88117205
comment on: http://stackoverflow.com/a/50553063
type: Comment
has text: let me try that and get back to you
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88364723
comment on: http://stackoverflow.com/q/50676008
type: Comment
score: 0
has text: Yes thank you for the help
type: QuestionComment

http://stackoverflow.com/q/50555630
has answer: http://stackoverflow.com/a/50555654
score: 0
has body: Given the following html document, how can I extract the string "CLN8"? OIL ---
accepted answer: http://stackoverflow.com/a/50555654
answer count: 1
tagged with: beautifulsoup
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: AnsweredQuestion
type: Question
has title: How can I extract the name of a tag by using Beautiful Soup?
has comment: http://stackoverflow.com/comment/88122054

http://stackoverflow.com/a/50689004
has body: On the one hand this answer should be an addition to the answer of @DavidW but on the other hand it also investigates possible improvements. It also proposes to use a wrapper for serialization, which would keep the beloved CPoint-objects but achieves the same dense serialization as structured numpy-arrays. As already pointed out, it doesn't make much sense to compare sizes of the single serialized object - the is just too much overhead. Among other things, Python has to save the identifier of the class, which is the full name of the module+class name. In my case, I'm using ipython with %%cython-magic, it is pretty long: &gt;&gt;&gt; print(pickle.dumps(CPoint(1,2))) b'\x80\x03c_cython_magic_46e1a18d1df9b5ea5ee974991f9aba67\n__pyx_unpickle_CPoint\nq\x00c_cython_magic_46e1a18d1df9b5ea5ee974991f9aba67\nCPoint\nq\x01J\xe9\x1a\x8d\x0cK\x01K\x02\x86q\x02\x87q\x03Rq\x04.' The length of the automatically created name of the module is c_cython_magic_46e1a18d1df9b5ea5ee974991f9aba67 and that hurts! So basically, without knowing how your objects are stored (list, map, set or something else), there is no way to give a proper answer. However, similar to @DavidW, a will assume that the points are stored in a list. When there are multiple CPoint objects in a list, pickle is clever enough to save the Class-header only once. I choose a slightly different test-setup - the coordinates are chosen randomly from the range [-2e9,2e9], which basically covers the whole int32-range (it is nice to know, that pickle is clever enough to reduce the number of needed bytes for small values, but how large is the gain depends on the distribution of the points): N=10000 x_lst=[random.randint(-2*10**9, 2*10**9) for _ in range(N)] y_lst=[random.randint(-2*10**9, 2*10**9) for _ in range(N)] and compare lists ofPoints, CPoints and int32-structured numpy arrays: lst_p = [ Point(x,y) for x,y in zip(x_lst, y_lst)] lst_cp = [ CPoint(x,y) for x,y in zip(x_lst, y_lst)] lst_np = np.array(list(zip(x_lst, y_lst)),…
downvote count: 0
answers question: http://stackoverflow.com/q/50660112
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/88238983
has text: To follow up on what @PixelEinstein said: using `BeautifulSoup`, this whole thing (including parsing the answer out of that mess, of tags which includes part of the head and all of the body, which I assume you were planning to get to once you finished this part?) is `return soup.title.text, soup.div.text`.
type: Comment
comment on: http://stackoverflow.com/q/50614223
score: 2
type: QuestionComment

http://stackoverflow.com/comment/88324388
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50657166
has text: I am confused by your test cases. Why doesn't 5 2 2 2 2 2 give 5?
type: Comment

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

http://stackoverflow.com/a/50663823
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50663804
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50663804
has body: meas_len_ipt is just a single string when you input it. You need to split it to individual elements: meas_len_ipt = input("type 5 values separated by comma:") meas_len = meas_len_ipt.split(",")
type: AcceptedAnswer

http://stackoverflow.com/q/50549920
has answer: http://stackoverflow.com/a/50550502
upvote count: 1
answer count: 1
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/50550502
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python
has title: Error: Can not convert a int into a Tensor or Operation. While making a CNN in tensorflow
has body: I am trying to make an autoencoder in tensorflow using CNN. Here is my code. hm_epochs = 10 learning_rate = 0.001 dropout = 0.2 batch_size = 128 x = tf.placeholder(tf.float32, shape=(None, 28, 28, 1)) def conv_layer(x, filters): return tf.layers.conv2d(inputs=x, filters=filters, kernel_size=[3, 3], padding="same", activation=tf.nn.relu) def downsample_layer(x): return tf.layers.max_pooling2d(inputs=x, pool_size=[2, 2], strides=2, padding='same') def dropout_layer(x, dropout): return tf.layers.dropout(inputs=x, rate=dropout) def deconv_layer(x, filters): return tf.layers.conv2d_transpose(inputs=x, filters=filters, kernel_size=[3, 3], strides=2, padding="same", activation=tf.nn.relu) def model(x): with tf.name_scope('encoder'): print('input shape:', x.shape) conv1 = conv_layer(x, 32) conv1 = downsample_layer(conv1) conv1 = dropout_layer(conv1, dropout) print('conv1 shape:', conv1.shape) conv2 = conv_layer(conv1, 16) conv2 = downsample_layer(conv2) conv2 = dropout_layer(conv2, dropout) print('conv2 shape:', conv2.shape) conv3 = conv_layer(conv2, 8) encoded = downsample_layer(conv3) print('encoded shape:', encoded.shape) with tf.name_scope('decoder'): conv4 = conv_layer(encoded, 8) conv4 = deconv_layer(conv4, 16) conv4 = dropout_layer(conv4, dropout) conv4 = tf.image.resize_images(conv4, size=(7,7), method=tf.image.ResizeMethod.NEAREST_NEIGHBOR) print('conv4 shape:', conv4.shape) conv5 = deconv_layer(conv4, 32) conv5 = dropout_layer(conv5, dropout) print('conv5 shape:', conv5.shape) conv6 = conv_layer(conv5, 32) decoded = deconv_layer(conv6, 1) print('decoded shape:', decoded.shape) return decoded def train_model(x): output = model(x) loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=x, logits=output)) opt = tf.train.AdamOptimizer(learning_rate).minimize(loss) mnist = input_data.read_data_sets("MNIST_data/") hm_batches = mnist.train.num_examples // batch_size with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for epochs in range…

http://stackoverflow.com/comment/88283778
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50636709
type: AnswerComment
has text: you can do the same thing in a loop over len(fileList), but `enumerate` is preferred, it keeps code compact and readable.

http://stackoverflow.com/comment/88201653
type: QuestionComment
has text: [Antti's answer](https://stackoverflow.com/a/40560564/4014959) is quite good. The key point being: "The desirability of this is in that it doesn't need any _exceptions_".
comment on: http://stackoverflow.com/q/50596148
score: 0
type: Comment

http://stackoverflow.com/q/50656805
tagged with: python-3.x
has title: Cloning file attributes in windows
has body: I am trying to clone folders with their contents using a small python script, but I am facing a little problem - when I copy, for example, a hidden or a system file, the copied file loses those attributes. I know that I can get the file attributes by using either the os.stat(original_file).st_file_attributes or the win32api.GetFileAttributes(original_file) and also that I can use win32api.SetFileAttributes() to set the attributes for the target file if, for example, I test for the stat.FILE_ATTRIBUTE_HIDDEN. The problem is that I don't know of a direct way of using the full result of the win32api.GetFileAttributes() in the win32api.SetFileAttributes(). By full result I mean all the file attributes at once. To be clearer, what I want to achieve is: Get the file attributes from the original_file. Set the file attributes to the target_file. Is this possible in one go or to I have to test individually for each file attribute?
tagged with: python
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/50657331
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50657331
downvote count: 0
accepted answer: http://stackoverflow.com/a/50660035
upvote count: 1
tagged with: windows
favorite count: 0
has answer: http://stackoverflow.com/a/50660035

http://stackoverflow.com/q/50623709
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88257378
has body: So I've got some data which I scraped from a website and it looks like this: table = '[['January 2010',1368,719],['February 2010',1366,729] ... ['April 2018',1429,480],['Today',1440,448]]' It's already formatted pretty well but how would I go about converting this string into a list of lists that looks the exact same but simply has a list datatype instead of string? I tried just converting the datatype but that didn't give me the right answer: &gt; print(list(table)) &gt; ['[', '[', "'", 'J', 'a' ... '4', '4', '8', ']', ']'] Thanks in advance
answer count: 2
possible better answer: http://stackoverflow.com/a/79379025
has title: Convert string into list Python
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/50623754
accepted answer: http://stackoverflow.com/a/50623754
has comment: http://stackoverflow.com/comment/88257410
linked to: http://stackoverflow.com/q/1832940
linked to: http://stackoverflow.com/q/1894269
has comment: http://stackoverflow.com/comment/88257228
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/79379025
upvote count: 3

http://stackoverflow.com/comment/88349629
comment on: http://stackoverflow.com/a/50667954
score: 0
type: AnswerComment
has text: Called regular expression matching.
type: Comment

tensorflow
tags question: http://stackoverflow.com/q/50605186
tags question: http://stackoverflow.com/q/50635729
tags question: http://stackoverflow.com/q/50548050
tags question: http://stackoverflow.com/q/50671630
tags question: http://stackoverflow.com/q/50664699
tags question: http://stackoverflow.com/q/50641374
tags question: http://stackoverflow.com/q/50598716
tags question: http://stackoverflow.com/q/50612923
tags question: http://stackoverflow.com/q/50656285
tags question: http://stackoverflow.com/q/50629620
tags question: http://stackoverflow.com/q/50623313
tags question: http://stackoverflow.com/q/50630123
tags question: http://stackoverflow.com/q/50683039
tags question: http://stackoverflow.com/q/50588274
tags question: http://stackoverflow.com/q/50563215
tags question: http://stackoverflow.com/q/50661250
tags question: http://stackoverflow.com/q/50673852
tags question: http://stackoverflow.com/q/50596163
tags question: http://stackoverflow.com/q/50668389
tags question: http://stackoverflow.com/q/50668416
tags question: http://stackoverflow.com/q/50559586
tags question: http://stackoverflow.com/q/50657425
tags question: http://stackoverflow.com/q/50694968
tags question: http://stackoverflow.com/q/50632275
tags question: http://stackoverflow.com/q/50690865
tags question: http://stackoverflow.com/q/50608080
tags question: http://stackoverflow.com/q/50653999
tags question: http://stackoverflow.com/q/50625298
tags question: http://stackoverflow.com/q/50697550
tags question: http://stackoverflow.com/q/50672019
tags question: http://stackoverflow.com/q/50669702
tags question: http://stackoverflow.com/q/50603972
tags question: http://stackoverflow.com/q/50644567
tags question: http://stackoverflow.com/q/50626224
tags question: http://stackoverflow.com/q/50552806
tags question: http://stackoverflow.com/q/50560463
tags question: http://stackoverflow.com/q/50561325
tags question: http://stackoverflow.com/q/50581043
tags question: http://stackoverflow.com/q/50659698
tags question: http://stackoverflow.com/q/50634776
tags question: http://stackoverflow.com/q/50630103
tags question: http://stackoverflow.com/q/50560013
tags question: http://stackoverflow.com/q/50682487
tags question: http://stackoverflow.com/q/50685576
tags question: http://stackoverflow.com/q/50610557
tags question: http://stackoverflow.com/q/50543862
tags question: http://stackoverflow.com/q/50631867
tags question: http://stackoverflow.com/q/50560394
tags question: http://stackoverflow.com/q/50669990
tags question: http://stackoverflow.com/q/50632258
tags question: http://stackoverflow.com/q/50641219
tags question: http://stackoverflow.com/q/50660190
tags question: http://stackoverflow.com/q/50612686
tags question: http://stackoverflow.com/q/50640254
tags question: http://stackoverflow.com/q/50651996
tags question: http://stackoverflow.com/q/50595638
tags question: http://stackoverflow.com/q/50575794
tags question: http://stackoverflow.com/q/50696558
tags question: http://stackoverflow.com/q/50685155
tags question: http://stackoverflow.com/q/50578642
tags question: http://stackoverflow.com/q/50641588
tags question: http://stackoverflow.com/q/50551096
tags question: http://stackoverflow.com/q/50562287
tags question: http://stackoverflow.com/q/50615156
tags question: http://stackoverflow.com/q/50620483
tags question: http://stackoverflow.com/q/50697171
tags question: http://stackoverflow.com/q/50673363
tags question: http://stackoverflow.com/q/50682119
tags question: http://stackoverflow.com/q/50609002
tags question: http://stackoverflow.com/q/50545411
tags question: http://stackoverflow.com/q/50577055
tags question: http://stackoverflow.com/q/50673604
tags question: http://stackoverflow.com/q/50605059
tags question: http://stackoverflow.com/q/50689367
tags question: http://stackoverflow.com/q/50604182
tags question: http://stackoverflow.com/q/50641866
tags question: http://stackoverflow.com/q/50552774
tags question: http://stackoverflow.com/q/50588693
tags question: http://stackoverflow.com/q/50655884
tags question: http://stackoverflow.com/q/50572962

http://stackoverflow.com/comment/88168072
has text: @PaulaThomas alright...I'm gonna wait maybe someone else come up with an idea how to crack this one...Thank you for your time !
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50578871

http://stackoverflow.com/q/50647914
tagged with: forms
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/88306945
has body: I want to print user-entered values to a file but every time I run it again, even with the same data (or no data at all), they are in a different order. This is the part of my .py file that does this: for key, value in request.form.items(): data = "%s=%s\n" % (key, shlex.quote(value)) configfile.write(bytes(data, 'UTF-8')) Here is an example of one output: (the first 3 lines of 40) IP='' cloud_radio=NO TO='' Here is another example where I entered the exact same data: (again the first 3 lines out of 41) key='' port2='' IP='' Is it possible to set the order that they output in? OR make sure that the order is the same each time?
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/50648055
tagged with: python
tagged with: request.form
accepted answer: http://stackoverflow.com/a/50648055
has title: How is the order of request.form.items() determinded?
type: Question
type: AnsweredQuestion

http://stackoverflow.com/a/50594469
type: Answer
has body: This may not be correct, as I don't have much experience with the texting side of smtplib, but it looks like you need to start the TLS connection. I would change your script to the following: import smtplib sender = 'xxxx@company.com' smtpObj = smtplib.SMTP('smtp.company.com') smtpObj.starttls() def text_func ( subject,text_message ): text_receivers = ['##########@vtext.com', 'xxxxxxxx@company.com', 'xxxxxxxx@gmail.com' ] text_message = """Subject: %s\n\n%s""" % (subject, text_message) smtpObj.sendmail(sender, text_receivers, text_message)
downvote count: 0
answers question: http://stackoverflow.com/q/50594442
has comment: http://stackoverflow.com/comment/88227087
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88235581

http://stackoverflow.com/comment/88104533
comment on: http://stackoverflow.com/q/50546899
type: Comment
type: QuestionComment
has text: In the above text, what exact text do you want to match before "HELLO WORLD"?
score: 1

http://stackoverflow.com/a/50692747
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50692161
has body: The average case complexity of a quicksort is O(N log N), however the actual complexity can vary between O(N) and O(N²) depending on your pivot choice and data. For instance, if your array is already sorted (or almost) choosing the first element as a pivot or the last element can either be a very bad pivot choice or a great choice. A random pivot choice has the advantage to reduce the chances to fall into such a case. However, since your dataset is random, your choice of pivot has little influence. To convince yourself, you can simply count the number of calls to each function. I've done it on your code for 1000000 elements and the difference is lower than 0.1%. The difference of computation time is probably caused by the only real difference in the code: the computation of random.randint(0,len(arr)-1)

http://stackoverflow.com/a/50732532
type: Answer
accepted answer of: http://stackoverflow.com/q/50618261
upvote count: 2
score: 2
has body: This is a well know limitation of extra(); it won't properly alias references. I suggest you stay way from it as it should only be used as a last resort. Instead you should use annotate(Length) annotate( length=Length('name'), ).order_by('length', 'name') https://docs.djangoproject.com/en/2.0/ref/models/database-functions/#length Or simply pass the Length to order_by if it's only annotated for ordering purpose .order_by(Length('name'), name) https://docs.djangoproject.com/en/2.0/ref/models/querysets/#order-by
has comment: http://stackoverflow.com/comment/88494057
answers question: http://stackoverflow.com/q/50618261
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88301322
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50645206
has text: How big is your data? maybe after you clear out all the strings you can open it in excel and let it handle all different formats, then change the format to something unique and go from there

http://stackoverflow.com/q/50558458
score: 85
duplicate of: http://stackoverflow.com/q/14281871
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/60107971
tagged with: percentage
has body: I want to get a percentage of a particular value in a df column. Say I have a df with (col1, col2 , col3, gender) gender column has values of M, F, or Other. I want to get the percentage of M, F, Other values in the df. I have tried this, which gives me the number M, F, Other instances, but I want these as a percentage of the total number of values in the df. df.groupby('gender').size() Can someone help?
has title: Get frequency of item occurrences in a column as percentage
type: Question
tagged with: group-by
possible better answer: http://stackoverflow.com/a/50558506
accepted answer: http://stackoverflow.com/a/50558594
tagged with: dataframe
has answer: http://stackoverflow.com/a/50558506
tagged with: pandas
has answer: http://stackoverflow.com/a/56019520
downvote count: 0
has answer: http://stackoverflow.com/a/58039547
favorite count: 0
upvote count: 85
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/50558594
duplicate of: http://stackoverflow.com/q/23377108

http://stackoverflow.com/comment/88133134
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50561307
has text: Your question seems unrelated to pandas
type: Comment

http://stackoverflow.com/a/61775146
type: Answer
has body: Script 1: YYYY = people_raw.find({"Birthday" : {"$type" : "string"}})
score: 0
has comment: http://stackoverflow.com/comment/109269817
answers question: http://stackoverflow.com/q/50689725

http://stackoverflow.com/comment/88149504
score: 0
type: Comment
type: QuestionComment
has text: How are you displaying the table? Note: version `0.23` already pads to a consistent length (`.2f` var1 and `.3f` var3).
comment on: http://stackoverflow.com/q/50569610

http://stackoverflow.com/comment/88258655
has text: @user1093967 your point is also right. thanks for the help.
type: QuestionComment
comment on: http://stackoverflow.com/q/50617525
type: Comment
score: 1

http://stackoverflow.com/comment/88388876
type: AnswerComment
comment on: http://stackoverflow.com/a/50689272
type: Comment
has text: Does it show `<QuerySet [...]>` around it? Because then you have an iterable that has the `Character` instances. Then it is only a matter of representation. When I perform the above queries, I get the objects (when I iterate over them), for both queries.
score: 0

http://stackoverflow.com/comment/88336501
comment on: http://stackoverflow.com/a/50663216
has text: Thank you so much! So, for future reference, anytime a .json file is imported the values are integers? Also I attempted to change my code by changing the user input into integers, but it still wouldn't return an output?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/50590760
type: Answer
has comment: http://stackoverflow.com/comment/88190904
has comment: http://stackoverflow.com/comment/88191110
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/88190955
has body: You can use zip + list/dict comprehensions: names = ['abc' , 'xyz' , 'foo'] ids = ['1234' , '5678' , '9101'] res = [{"name": n, "id": i} for n, i in zip(names, ids)]
answers question: http://stackoverflow.com/q/50590714
has comment: http://stackoverflow.com/comment/88191004
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50590714

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

http://stackoverflow.com/comment/88223431
comment on: http://stackoverflow.com/q/50604954
score: 0
has text: And you've searched yourself and most likely gotten to this page? https://stackoverflow.com/questions/6996603/how-to-delete-a-file-or-folder
type: QuestionComment
type: Comment

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/50659173
tags question: http://stackoverflow.com/q/50555817
tags question: http://stackoverflow.com/q/50546084
tags question: http://stackoverflow.com/q/50604451
tags question: http://stackoverflow.com/q/50656576
tags question: http://stackoverflow.com/q/50672941
tags question: http://stackoverflow.com/q/50679857
tags question: http://stackoverflow.com/q/50626959
tags question: http://stackoverflow.com/q/50625057
tags question: http://stackoverflow.com/q/50665548
tags question: http://stackoverflow.com/q/50595330
tags question: http://stackoverflow.com/q/50591662
tags question: http://stackoverflow.com/q/50574024
tags question: http://stackoverflow.com/q/50581684
tags question: http://stackoverflow.com/q/50663584
tags question: http://stackoverflow.com/q/50688071
tags question: http://stackoverflow.com/q/50652057
tags question: http://stackoverflow.com/q/50659964
tags question: http://stackoverflow.com/q/50573171
tags question: http://stackoverflow.com/q/50614266
tags question: http://stackoverflow.com/q/50567369
tags question: http://stackoverflow.com/q/50599454
type: Tag
tags question: http://stackoverflow.com/q/50621262
tags question: http://stackoverflow.com/q/50597101
tags question: http://stackoverflow.com/q/50573565
tags question: http://stackoverflow.com/q/50645204
tags question: http://stackoverflow.com/q/50645301
tags question: http://stackoverflow.com/q/50638902
tags question: http://stackoverflow.com/q/50678954
tags question: http://stackoverflow.com/q/50678549
tags question: http://stackoverflow.com/q/50689217
tags question: http://stackoverflow.com/q/50581508
tags question: http://stackoverflow.com/q/50575064
tags question: http://stackoverflow.com/q/50606068
tags question: http://stackoverflow.com/q/50555501
tags question: http://stackoverflow.com/q/50577697
tags question: http://stackoverflow.com/q/50687879
tags question: http://stackoverflow.com/q/50623889
tags question: http://stackoverflow.com/q/50682107
tags question: http://stackoverflow.com/q/50570687
tags question: http://stackoverflow.com/q/50689599
tags question: http://stackoverflow.com/q/50618896

http://stackoverflow.com/comment/88266513
score: 1
comment on: http://stackoverflow.com/q/50557129
has text: But, there is the [pd.get_dummies](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html) function which: > Convert categorical variable into dummy/indicator variables .. making this without apply `LabelEncoder` and `OneHotEncoder`. Is more efficient.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50666088
tagged with: matrix
answer count: 1
has comment: http://stackoverflow.com/comment/88344372
tagged with: python
has answer: http://stackoverflow.com/a/50727530
accepted answer: http://stackoverflow.com/a/50727530
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88347125
has comment: http://stackoverflow.com/comment/88347974
type: Question
has title: Trouble setting up matrix with sympy
score: 0
has comment: http://stackoverflow.com/comment/88348321
has comment: http://stackoverflow.com/comment/88348799
has body: I would like to do some symbolic mathe withe some matrices. But my code does not work. Setting up my first matrices is no problem but calculating the wanted one from the start matrices does not work and I do not know why. Any suggestions? from sympy import * from sympy import Matrix , pprint, symbols niso=4 MM = Matrix(niso-1,1, lambda i,j:var('MM_%s' % (i+1) )) MA = Matrix (niso-1,1, lambda i,j:var('m_%s%s' % ('A', chr(66+i)) ) ) MX = Matrix (niso-1,1, lambda i,j:var('m_%s%s'% (chr(66+i), 'A'))) Rb = Matrix(niso-1,1, lambda i,j:var('Rb_%s%d' % ( chr(65)+chr(66+i)+',', i+2))) R = Matrix (niso, niso-1, lambda i,j: var('R_%s%d' % (chr(65+i)+',' , j+1 ))) A = Matrix(niso-1,niso-1, lambda i,j:var('A_%d' % i)) for i in range(0,niso-1): for j in range(0,niso-1): A[i,j]=Rb[i,0]*MM[i,0] + MM[i,0] My code only leads to this error message. TypeError: Can't multiply sequence by non-integer of type '' The problem is that I thought that my matrices already contain only symbols so that multiplying should work.
tagged with: sympy

http://stackoverflow.com/q/50573209
downvote count: 0
has answer: http://stackoverflow.com/a/50576024
has comment: http://stackoverflow.com/comment/88158533
favorite count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has body: I have a csv file that has different lenghts per row, similar to: left, 10, xdfe, 8992, 0.231 left, 10, xdfk, 8993, 2.231 right, 20, adfk, 8993, 2.231, DDT, 10, 10 right, 30, dfk, 923, 2.231, ADD, 10, 20 center, 923, 2.231, 10, 20 right, 34, efk, 326, 6.21, DDD, 20, 40 where rows that start with a keyword, left, right and center have the same length (the left rows always have the same length as other left rows, for example). I want to read these files using spark.readStream.csv, do some transformations that can depend on the kind of row, and write the results to parquet. Is there a way to use different schemas based on the value of the first column of each row?
tagged with: python
score: 2
upvote count: 2
type: Question
has title: Read CSV file in PySpark Streaming with different schema on the same file
tagged with: pyspark
has comment: http://stackoverflow.com/comment/88160368
has comment: http://stackoverflow.com/comment/88157103
tagged with: apache-spark
answer count: 1

http://stackoverflow.com/a/50638392
score: 0
has comment: http://stackoverflow.com/comment/88287146
upvote count: 1
downvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50638264
answers question: http://stackoverflow.com/q/50638264
has body: The first time your code calls file.read() it is reading the whole file. The second time your code calls it, without first closing the file and reopening it, it is at EOF. If you want to extract stuff from individual lines of the file then iterate through the file: codes = [] functions = [] with open(fname,'r') as file: for line in file: codes.extend(re.findall('LIR: (.+)',line)) functions.extend(re.findall(';(.+);LIR', line))
type: AcceptedAnswer

http://stackoverflow.com/q/50635104
tagged with: merge
has answer: http://stackoverflow.com/a/50664910
answer count: 4
accepted answer: http://stackoverflow.com/a/50664910
has answer: http://stackoverflow.com/a/50664952
downvote count: 0
tagged with: del
has comment: http://stackoverflow.com/comment/88339925
type: AnsweredQuestion
score: 7
has answer: http://stackoverflow.com/a/50674069
type: Question
has answer: http://stackoverflow.com/a/50672223
has title: How to delete and shift values in a pandas df column
tagged with: pandas
favorite count: 0
has body: I have a pandas df that I want to manipulate so it's ordered. So for the df below, I'd like ['I'] to be ordered. So values would read 10-50. I have 2 options to do this; 1) Try to delete values in Column ['G'] or ['H']. So if values are == X then delete. 2) Try to merge values in the same Columns when they are == X import pandas as pd d = pd.DataFrame({ 'J' : [10,'B','C','C',50], 'I' : ['B',20,30,40,'C'], 'H' : ['X','A','C','B','X'], 'G' : ['X', 'B', 'A','B','X'], }) Output: G H I J 0 X X B 10 1 B A 20 B 2 A C 30 C 3 B B 40 C 4 X X C 50 Option 1 is we delete X from Column H and the intended output would be: G H I J 0 X B 10 1 B A 20 B 2 A C 30 C 3 B B 40 C 4 X C 50 Option 2 is we merge on X in Column G-H and the intended output would be: G H I J 0 XX B 10 1 B A 20 B 2 A C 30 C 3 B B 40 C 4 XX C 50 I have played around with df = df.drop(df.H == 'X') but this deletes the whole row.
upvote count: 7
tagged with: python
possible better answer: http://stackoverflow.com/a/50664952

http://stackoverflow.com/a/50640396
has body: First of all python function passes the value by object and the reference name here param is just a reference to a value hold by n. Now coming to the solution, yes it could be possible provided you pass the variable name def init_param(var_name): globals()[var_name] = 10 n = 1 init_param('n') print n Hope it will answer!
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50640122
type: Answer
downvote count: 0

http://stackoverflow.com/a/50673172
type: Answer
answers question: http://stackoverflow.com/q/50672792
score: 0
has body: It's simpler than you imagine. Just observe your manual attempt and try to infer from it. We can simply do x = len(num_list)//2 + len(num_list)%2 for i in range(x): sumBoth = num_list[i] + num_list[-i-1] num_list2.append(sumBoth) or with a simpler one-liner num_list2 = [ num_list[i] + num_list[-i-1] for i in range(len(num_list)//2+len(num_list)%2)] This works for even as well as odd lengths because of the len(num_list)%2 at the end in the range.

http://stackoverflow.com/q/50559529
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/50560982
type: Question
has answer: http://stackoverflow.com/a/50560067
score: 0
has body: I was trying to parse a dictionary queried from the Spotify Album API in Python3 but got the error message: ValueError: malformed node or string when using ast.literal_eval. When using JSON.loads, I got the error message: SyntaxError: EOL while scanning string literal. When looking at the dictionary, I saw that the text stops being recognized as a string in VIM at charater 3072, for a reason that I can't figure out. Is this a bug, or a hidden character that I am unfamiliar with? The text is copied below and a Screenshot is attached to show the text suddenly changing from string to regular text. How can I fix this issue to parse this text as a dictionary? { 'album_type': 'single', 'artists': [ { 'external_urls': { 'spotify': 'https://open.spotify.com/artist/4D75GcNG95ebPtNvoNVXhz' }, 'href': 'https://api.spotify.com/v1/artists/4D75GcNG95ebPtNvoNVXhz', 'id': '4D75GcNG95ebPtNvoNVXhz', 'name': 'Afrojack', 'type': 'artist', 'uri': 'spotify:artist:4D75GcNG95ebPtNvoNVXhz' }, { 'external_urls': { 'spotify': 'https://open.spotify.com/artist/50kceDjknh0CjwOko7kx7V' }, 'href': 'https://api.spotify.com/v1/artists/50kceDjknh0CjwOko7kx7V', 'id': '50kceDjknh0CjwOko7kx7V', 'name': 'Jewelz &amp; Sparks', 'type': 'artist', 'uri': 'spotify:artist:50kceDjknh0CjwOko7kx7V' } ], 'available_markets': [ 'AD', 'AR', 'AT', 'AU', 'BE', 'BG', 'BO', 'BR', 'CA', 'CH', 'CL', 'CO', 'CR', 'CY', 'CZ', 'DE', 'DK', 'DO', 'EC', 'EE', 'ES', 'FI', 'FR', 'GB', 'GR', 'GT', 'HK', 'HN', 'HU', 'ID', 'IE', 'IL', 'IS', 'IT', 'JP', 'LI', 'LT', 'LU', 'LV', 'MC', 'MT', 'MX', 'MY', 'NI', 'NL', 'NO', 'NZ', 'PA', 'PE', 'PH', 'PL', 'PT', 'PY', 'RO', 'SE', 'SG', 'SK', 'SV', 'TH', 'TR', 'TW', 'US', 'UY', 'VN', 'ZA' ], 'copyrights': [ { 'text': '2018 Wall Recordings under exclusive license to Armada Music B.V.', 'type': 'C' }, { 'text': '2018 Wall Recordings under exclusive license to Armada Music B.V.', 'type': 'P' } ], 'external_ids': { 'upc': '8718522203121' }, 'external_urls': { 'spotify': 'https://open.spotify.com/al…
answer count: 3
tagged with: spotify
tagged with: string
has title: Error when parsing dictionary with ast.literal_eval or JSON. Possible bug in writing String? Python
has answer: http://stackoverflow.com/a/50559631
has comment: http://stackoverflow.com/comment/88129671
type: UnansweredQuestion
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/88341773
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50665866
score: 3
has text: So to sum it up, you have a dictionary where the values are ascending numbers, and you want to remove some elements from that dict without introducing any gaps in those numbers? Are you sure you aren't storing your data backwards? Why not use `words = ['apple', 'orange', 'banana', 'pear']`?

http://stackoverflow.com/q/50659698
tagged with: opencv
has comment: http://stackoverflow.com/comment/88329857
score: 0
answer count: 1
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/88329566
has answer: http://stackoverflow.com/a/51038072
has body: i try to develop object detection API,during implementation occur a error, import cv2 cap = cv2.VideoCapture(0) with detection_graph.as_default(): with tf.Session(graph=detection_graph) as sess: while(True): ret,image_np =cap.read() image_np_expanded = np.expand_dims(image_np,axis=0) image_tensor =detection_graph.get_tensor_by_name('image_tensor:0') boxes = detection_graph.get_tensor_by_name('detection_boxes:0') scores = detection_graph.get_tensor_by_name('detection_scores:0') classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0') (boxes,scores,classes,num_detections) = sess.run( [boxes,scores,classes,num_detections], feed_dict={ image_tensor:image_np_expanded}) vis_util.visualize_boxes_and_labels_on_image_array( image_np, np.squeeze(boxes), np.squeeze(classes).astype(np.int32), np.squeeze(scores), category_index, use_normalized_coordinates=True, line_thickness=8) cv2.imshow('image',cv2.resize(image_np,(1280,960))) if cv2.waitkey(25) &amp; 0xFF == ord('q'): break cv2.destroyAllWindows() cap.release()
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88336152
has title: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
has comment: http://stackoverflow.com/comment/88330793
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/88329409

http://stackoverflow.com/q/50554317
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: anaconda
answer count: 0
downvote count: 0
has body: I downloaded the anaconda 3.6 and in jupyter i try to import numpy. Even after reinstallation I still get this error: import numpy ImportError Traceback (most recent call last) ~\AppData\Roaming\Python\Python36\site-packages\numpy\core\__init__.py in &lt;module&gt;() 15 try: ---&gt; 16 from . import multiarray 17 except ImportError as exc: ImportError: cannot import name 'multiarray' During handling of the above exception, another exception occurred: ImportError Traceback (most recent call last) &lt;ipython-input-1-d4cdadb62aa7&gt; in &lt;module&gt;() ----&gt; 1 import numpy ~\AppData\Roaming\Python\Python36\site-packages\numpy\__init__.py in &lt;module&gt;() 140 return loader(*packages, **options) 141 --&gt; 142 from . import add_newdocs 143 __all__ = ['add_newdocs', 144 'ModuleDeprecationWarning', ~\AppData\Roaming\Python\Python36\site-packages\numpy\add_newdocs.py in &lt;module&gt;() 11 from __future__ import division, absolute_import, print_function 12 ---&gt; 13 from numpy.lib import add_newdoc 14 15 ############################################################################### ~\AppData\Roaming\Python\Python36\site-packages\numpy\lib\__init__.py in &lt;module&gt;() 6 from numpy.version import version as __version__ 7 ----&gt; 8 from .type_check import * 9 from .index_tricks import * 10 from .function_base import * ~\AppData\Roaming\Python\Python36\site-packages\numpy\lib\type_check.py in &lt;module&gt;() 9 'common_type'] 10 ---&gt; 11 import numpy.core.numeric as _nx 12 from numpy.core.numeric import asarray, asanyarray, array, isnan, zeros 13 from .ufunclike import isneginf, isposinf ~\AppData\Roaming\Python\Python36\site-packages\numpy\core\__init__.py in &lt;module&gt;() 24 Original error was: %s 25 """ % (exc,) ---&gt; 26 raise ImportError(msg) 27 finally: 28 for envkey in env_added: ImportError: Importing the multiarray numpy extension module failed. Most likely you are trying to import a failed build of numpy. If you're working with a numpy git repo, tr…
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88141298
upvote count: 2
has title: numpy ImportError cannot import name 'multiarray'
has comment: http://stackoverflow.com/comment/88125707
tagged with: jupyter-notebook
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/50666546
answers question: http://stackoverflow.com/q/50662638
has comment: http://stackoverflow.com/comment/88360101
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50662638
has body: I am working with python3 and have changed the imports to work with your original example, but this works beautifully for me, let me know how it works for you. I tried to comment all the places I changed, but may have missed one: import Tkinter as tk import ttk from matplotlib.backends.backend_tkagg import ( FigureCanvasTkAgg, NavigationToolbar2TkAgg) import matplotlib.pyplot as plt import numpy as np class Frame_examples_program(object): def __init__(self): self.window = tk.Tk() self.window.title("Amazing GUI 5000") self.create_widgets() def create_widgets(self): self.window['padx'] = 10 self.window['pady'] = 10 # - - - - - - - - - - - - - - - - - - - - - # Frame frame1 = ttk.Frame(self.window, relief=tk.RIDGE) frame1.grid(row=0, column=0, sticky=tk.E + tk.W + tk.N + tk.S, padx=0, pady=0) frame2 = ttk.Frame(self.window, relief=tk.RIDGE) frame2.grid(row=1, column=0, sticky=tk.E + tk.W + tk.N + tk.S, padx=0, pady=0) self.plotFrame = self.PlotFrame(frame1, frame2) frame3 = ttk.Frame(self.window, relief=tk.RIDGE) frame3.grid(row=2, column=2, sticky=tk.E + tk.W + tk.N + tk.S, padx=0, pady=0) self.workFrame = self.WorkFrame(frame3, self.plotFrame) class PlotFrame(object): # The plot def __init__(self, parent1, parent2): self.parent1 = parent1 self.parent2 = parent2 self.observers = [] self.x = 0 self.y = 0 canvas = self.plot() self.plot_toolbar(canvas) def plot(self): # the actual plot fig, ax = plt.subplots() plt.imshow(np.ones((100, 100)), picker=True) canvas = FigureCanvasTkAgg(fig, self.parent1) canvas.mpl_connect('button_press_event', self.onclick) return canvas def plot_toolbar(self, canvas): # the tool bar to the plot toolbar = NavigationToolbar2TkAgg(canvas, self.parent2) toolbar.update() canvas.get_tk_widget().grid(row=1, column=1) canvas.draw() def onclick(self, event): # Here I am now setting the position self.set_new_position(event.x, event.y) def set_new_position(self, x, y): self.x = x self.y = y for callback in self.observers: # Here I am now calling the m…
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/88348428
type: QuestionComment
score: 0
has text: The question is not similar idk why it was marked that way
comment on: http://stackoverflow.com/q/50669144
type: Comment

http://stackoverflow.com/comment/88330411
type: Comment
comment on: http://stackoverflow.com/a/50659978
has text: I tried to print the shape of the dataframe and is: `<class 'pandas.core.series.Series'>` and `(12436,)` respectively
score: 0
type: AnswerComment

pyqt
type: Tag
tags question: http://stackoverflow.com/q/50660860
tags question: http://stackoverflow.com/q/50671868
tags question: http://stackoverflow.com/q/50571097
tags question: http://stackoverflow.com/q/50575492
tags question: http://stackoverflow.com/q/50596027
tags question: http://stackoverflow.com/q/50681354
tags question: http://stackoverflow.com/q/50657352
tags question: http://stackoverflow.com/q/50547526
tags question: http://stackoverflow.com/q/50596590
tags question: http://stackoverflow.com/q/50611712
tags question: http://stackoverflow.com/q/50582560
tags question: http://stackoverflow.com/q/50549439
tags question: http://stackoverflow.com/q/50541913
tags question: http://stackoverflow.com/q/50578978
tags question: http://stackoverflow.com/q/50566738
tags question: http://stackoverflow.com/q/50556216
tags question: http://stackoverflow.com/q/50661112
tags question: http://stackoverflow.com/q/50666680
tags question: http://stackoverflow.com/q/50607790
tags question: http://stackoverflow.com/q/50600811
tags question: http://stackoverflow.com/q/50640196
tags question: http://stackoverflow.com/q/50554791
tags question: http://stackoverflow.com/q/50623735
tags question: http://stackoverflow.com/q/50590087
tags question: http://stackoverflow.com/q/50572925
tags question: http://stackoverflow.com/q/50605433
tags question: http://stackoverflow.com/q/50556514
tags question: http://stackoverflow.com/q/50666721
tags question: http://stackoverflow.com/q/50591049
tags question: http://stackoverflow.com/q/50604760
tags question: http://stackoverflow.com/q/50566848
tags question: http://stackoverflow.com/q/50633851
tags question: http://stackoverflow.com/q/50547593
tags question: http://stackoverflow.com/q/50575900
tags question: http://stackoverflow.com/q/50593591
tags question: http://stackoverflow.com/q/50611181
tag name: pyqt
tags question: http://stackoverflow.com/q/50593841
tags question: http://stackoverflow.com/q/50606443
tags question: http://stackoverflow.com/q/50556719
tags question: http://stackoverflow.com/q/50608275
tags question: http://stackoverflow.com/q/50548820
tags question: http://stackoverflow.com/q/50545917
tags question: http://stackoverflow.com/q/50564390
tags question: http://stackoverflow.com/q/50567832

http://stackoverflow.com/comment/88187439
has text: @MoH. I think you should add _"`s = str(x) + '.'` appends an extra `.` to the string representation of `x`"_ (or something like that) to your answer for clarity.
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50588945

http://stackoverflow.com/q/50598984
has answer: http://stackoverflow.com/a/50599205
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/50599205
upvote count: 1
type: AnsweredQuestion
score: 1
tagged with: group-by
tagged with: dataframe
type: Question
has title: How do you specify pandas groupby operations that operate on previous records?
answer count: 1
downvote count: 0
has body: I have a Pandas dataframe as following which has to be sorted by Col_2: +----+-------+-------+ | id | Col_1 | Col_2 | +----+-------+-------+ | 1 | 0 | 21 | | 1 | 1 | 24 | | 1 | 1 | 32 | | 1 | 0 | 35 | | 1 | 1 | 37 | | 2 | 0 | 2 | | 2 | 0 | 5 | +----+-------+-------+ How can I create two new columns: Col_1_sum: the sum of values in the previous rows for each id. Col_2_max: the max value of Col_2 in the last rows which Col_1 was one. (for each id) For example for above dataframe the result should be: +----+-------+-------+-----------+-----------+ | id | Col_1 | Col_2 | Col_1_Sum | Col_2_Max | +----+-------+-------+-----------+-----------+ | 1 | 0 | 21 | 0 | 0 | | 1 | 1 | 24 | 0 | 0 | | 1 | 1 | 32 | 1 | 24 | | 1 | 0 | 35 | 2 | 32 | | 1 | 1 | 37 | 2 | 32 | | 2 | 0 | 2 | 0 | 0 | | 2 | 0 | 5 | 0 | 0 | +----+-------+-------+-----------+-----------+
tagged with: pandas-groupby
tagged with: pandas

http://stackoverflow.com/comment/88319651
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50654672
has text: @Peteris you don't need Panda, there's already a csv module in the stdlib.
score: 0

http://stackoverflow.com/a/50615190
upvote count: 4
has comment: http://stackoverflow.com/comment/88242794
has body: First, you can turn each of those four-line blocks into a one-liner if you just edit your convertMillis function to return np.nan instead of raising—or, if you can't do that, wrap the function in another one: def convertMillisOrNan(millis): try: return convertMillis(millis) except: return np.nan newaccsla_comp = convertMillisOrNan(issues.fields.customfield_10705.completedCycles[0].remainingTime.millis) newaccsla_ongoing = convertMillisOrNan(issues.fields.customfield_10705.ongoingCycle.remainingTime.millis) # etc. Or, maybe the exception you're trying to handle comes a bit farther up. You're always calling convertMillis on &lt;something&gt;.remainingTime.millis. What if, say, the field always exists, and always has an ongoingCycle, but that doesn't always have a remainingTime attribute? Then you can push that part into the try:, and also simplify things even further at the same time: def convertCycle(cycle): try: return convertMillis(cycle.remainingTime.millis) except: return np.nan newaccsla_comp = convertCycle(issues.fields.customfield_10705.completedCycles[0]) newaccsla_ongoing = convertCycle(issues.fields.customfield_10705.ongoingCycle) If the exception comes even higher up—e.g., if the field doesn't always have an ongoingCycle—obviously you need to push more of the expression inside the try: block; I'm really just making a guess here at what you're trying to handle with that except:. And, while you're at it, do you really want a bare except:? That will handle any exception, not just an AttributeError or ValueError or whatever kind of exception you were actually expecting. Meanwhile, your existing jira_hours refactor doesn't work because you can't just use .field when field is a variable holding a string. One way to solve that is: def get_jira_hours(field): comp = convertCycle(field.completedCycles[0]) ongoing = convertCycle(field.ongoingCycle) return comp, ongoing newaccsla_comp, newaccsla_ongoing = get_jira_hours(issues.fields.customfield_10705) paymentssla_com…
score: 4
answers question: http://stackoverflow.com/q/50615071
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88247055
accepted answer of: http://stackoverflow.com/q/50615071

http://stackoverflow.com/q/50660763
upvote count: 2
has title: Printing inside jupyter notebook custom loss function with Keras/TF
answer count: 1
tagged with: keras
has answer: http://stackoverflow.com/a/56218606
favorite count: 0
linked to: http://stackoverflow.com/q/33833818
tagged with: python
tagged with: jupyter-notebook
score: 2
has comment: http://stackoverflow.com/comment/88331561
downvote count: 0
type: UnansweredQuestion
has body: In Keras, if you make a custom loss function in a Jupyter notebook, you can not print anything. For instance if you have: def loss_func(true_label, NN_output): true_cat = true_label[:,0] pred_cat = NN_output[:,0] indicator = NN_output[:,1] print("Hi!") custom_term = K.mean(K.abs(indicator)) return binary_crossentropy(true_cat, pred_cat) + custom_term Nothing will print when the function is evaluated. As a workaround, in case I am doing some debugging, I have found that I can write to a file in a cost function, which can be useful if I want to print something standard like an int or a string. However, trying to write out a tensor like indicator to a file gives the unbelievably helpful output: Tensor("loss_103/model_105_loss/Print:0", shape=(512,), dtype=float32) I know TF provides a tf.Print() method to print the value of a tensor, but I don't understand how that plays with Jupyter. Other answers have said that tf.Print() writes to std. err, which means trying sys.stderr = open('test.txt', 'w') should theoretically allow me to get my output from a file, but unfortunately this doesn't work (at least in Jupyter). Is there any general method to get a representation of my tensor as a string? How do people generally get around this barrier to seeing what your code does? If I come up with something more fancy than finding a mean, I want to see exactly what's going on in the steps of my calculation to verify it works as intended. Thanks!
has comment: http://stackoverflow.com/comment/88332557
tagged with: tensorflow
type: Question
linked to: http://stackoverflow.com/q/33633370
tagged with: loss-function

http://stackoverflow.com/a/50565731
type: Answer
has body: I propose to iterate manually in the file with next and use an infinite loop. When there are no more lines, next throws StopIteration exception, that's where we break the loop. Then the classic elegant way of summing a comma-separated list of integers is to split then map to integer conversion and feed to sum import sys with open("test.txt") as infile: while True: try: total = sum(map(int,next(infile).split(","))) name = next(infile).rstrip() # remove linefeed from name print("Sum of favourite numbers for {} : {}".format(name,total)) except StopIteration: break prints: Sum of favourite numbers for John Doe : 11 Sum of favourite numbers for Jane Doe : 19 If the file has an odd number of lines, the last line information is dropped since the StopIteration exception happens when reading the name information.
upvote count: 1
answers question: http://stackoverflow.com/q/50562626
has comment: http://stackoverflow.com/comment/135512286
downvote count: 0
score: 1

http://stackoverflow.com/comment/88368994
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50679741
has text: @JoeIddon, i was just learning about bytearray's so, i was trying to use it. But, from what you mentioned, i cant modify the string to have a utf-8 character right?

http://stackoverflow.com/a/59640371
type: Answer
answers question: http://stackoverflow.com/q/50579783
score: 0
has body: For json format below code will work : graphs.append(html.Div(dcc.Graph( id='chart_id_6', figure={ 'data': [{'x':pv2.index, 'y': pv2[('amount','FY17')], 'marker': {'color': ['#b50000', '#e63535', '#fa8989']}}], 'layout': { 'title': 'Bottom ' + str(x_bottom) + ' Customers' } })))

javascript
tags question: http://stackoverflow.com/q/50683637
tags question: http://stackoverflow.com/q/50685826
tags question: http://stackoverflow.com/q/50563235
tags question: http://stackoverflow.com/q/50649510
tags question: http://stackoverflow.com/q/50644641
tags question: http://stackoverflow.com/q/50598070
tags question: http://stackoverflow.com/q/50578323
tag name: javascript
tags question: http://stackoverflow.com/q/50654450
tags question: http://stackoverflow.com/q/50667409
tags question: http://stackoverflow.com/q/50631873
tags question: http://stackoverflow.com/q/50633415
tags question: http://stackoverflow.com/q/50692249
type: Tag
tags question: http://stackoverflow.com/q/50546689
tags question: http://stackoverflow.com/q/50606468
tags question: http://stackoverflow.com/q/50591323
tags question: http://stackoverflow.com/q/50548962
tags question: http://stackoverflow.com/q/50614257
tags question: http://stackoverflow.com/q/50651652
tags question: http://stackoverflow.com/q/50623788
tags question: http://stackoverflow.com/q/50634430
tags question: http://stackoverflow.com/q/50573455
tags question: http://stackoverflow.com/q/50546268
tags question: http://stackoverflow.com/q/50651518
tags question: http://stackoverflow.com/q/50644215
tags question: http://stackoverflow.com/q/50568534
tags question: http://stackoverflow.com/q/50569848
tags question: http://stackoverflow.com/q/50618271
tags question: http://stackoverflow.com/q/50626626
tags question: http://stackoverflow.com/q/50557796
tags question: http://stackoverflow.com/q/50648727
tags question: http://stackoverflow.com/q/50589034
tags question: http://stackoverflow.com/q/50587076

http://stackoverflow.com/a/50664228
downvote count: 1
score: -1
has body: Here is some pseudo code, but you can essentially achieve this in pandas. I'm not going to write an entire program for you, but a basic example as you noted should suffice. import pandas as pd import numpy as np import matplotlib.pyplot as plt a = np.arange(1, 8) data_frame = pd.DataFrame([[1, 2, 3, 4, 5, 6, 7]], columns=['A', 'B', 'C', 'D', 'E', 'F', 'G']) data_frame.plot(kind='barh') plt.show() This code will create a horizontal bar chart like the one you've shown above. If you want it to be stacked exactly like the one above, you can add the 'stacked=True' argument in the .plot() method. In order to make the bar chart horizontal we pass kind='barh' in the argument. There will automatically be a legend in the chart that highlights what each bar means. You can manipulate the color of the various bars. This is a simple example, and you will have to do more research on pandas, but you can essentially create nice visuals with pandas and matplotlib.pyplot. Here is the output: Again, you can add titles to the values in the DataFrame if you want to get specific names for the columns, and if you have data that supports a stacked bar, simply setting the stacked kwarg to True will create a stacked bar chart for the various categories.
upvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50663482

http://stackoverflow.com/a/50674229
has comment: http://stackoverflow.com/comment/88663297
score: 0
answers question: http://stackoverflow.com/q/50674141
type: Answer
has comment: http://stackoverflow.com/comment/88358160
accepted answer of: http://stackoverflow.com/q/50674141
has comment: http://stackoverflow.com/comment/88358191
has body: You can locate your element using this: //font[contains(text(),'PCA Submit Request completed successfully')] Before this element appears, you can set a pause like in the example: from selenium.webdriver.support import expected_conditions element = WebDriverWait(driver, 10).until( expected_conditions.presence_of_element_located((By.xPath, "xPath_to_element")) ) or browser.implicitly_wait(30)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88661711

http://stackoverflow.com/comment/90543168
comment on: http://stackoverflow.com/q/50634824
score: 0
type: Comment
type: QuestionComment
has text: Did you found anything about this?

http://stackoverflow.com/a/50599039
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50582105
answers question: http://stackoverflow.com/q/50582105
has body: Can you test these locators in the Dev tools and check if they are pointing to the right element on the page? In the console use $x() to test XPaths and $$() to test CSS selectors. If it returns 0, you know there's something wrong with your locator. If it returns 1, you are good to go. If it returns more than 1, you will need to verify that the element you are looking for is the first element returned. If it's not, you will need to craft a new locator. I have a feeling that your current locators is returning 2 nodes, out of which the first one is invisible. Try to access the target element using that elements ancestors. Keep going one level up till you find a node that is uniquely identifiable and then use relative xpath (//) to traverse down to your element. You can also use ordinals/index to locate the element, but i would not recommend it as they will make your test brittle. If possible update the question with a bigger snippet of the HTML or the applications URL
score: 0

http://stackoverflow.com/comment/88233073
has text: Unfortunately integer arrays cannot hold NaNs so pandas is automatically casting that column as float.
comment on: http://stackoverflow.com/q/50611539
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/88269554
comment on: http://stackoverflow.com/a/50629615
type: Comment
score: 1
type: AnswerComment
has text: Thanks RavinderSingh13

http://stackoverflow.com/a/50638028
has comment: http://stackoverflow.com/comment/88289374
has comment: http://stackoverflow.com/comment/88430317
has comment: http://stackoverflow.com/comment/88431655
has comment: http://stackoverflow.com/comment/88286219
has comment: http://stackoverflow.com/comment/88288603
has comment: http://stackoverflow.com/comment/88289328
has comment: http://stackoverflow.com/comment/88288590
answers question: http://stackoverflow.com/q/50637763
score: 0
has comment: http://stackoverflow.com/comment/88288244
has body: try this, string['res'] = string.apply(lambda x: ' '.join(globals()[x['location']].iloc[(x['start']-1):(x['stop'])]['w']),axis=1) print string['res'].values.tolist() output: ['i am', 'in love', 'with you', 'i wish', 'python is', 'my friend', 'the ship', 'has', 'set sail'] For further Result (Adding Boundary): string['res'] = string.apply(lambda x: ' '.join(globals()[x['location']].iloc[(x['start']-1):(x['stop'])]['w']),axis=1) string.loc[~string['part'].duplicated(keep='last'),'flag']='boundry' l=list(string['res'].values) b = list(np.where(string['flag'].values == 'boundry')[0]) [l.insert(ind+i,'boundary') for i,ind in enumerate(b,1)] print l Output: ['i am', 'in love', 'with you', 'i wish', 'python is', 'my friend', 'boundary', 'the ship', 'has', 'set sail', 'boundary']
has comment: http://stackoverflow.com/comment/88288531
type: Answer

http://stackoverflow.com/q/50595288
has answer: http://stackoverflow.com/a/50608554
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
has comment: http://stackoverflow.com/comment/88199698
has comment: http://stackoverflow.com/comment/88200717
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88226294
score: -4
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/88199841
downvote count: 4
upvote count: 0
has comment: http://stackoverflow.com/comment/88199901
has body: I have a .csv file with a lot of dates and times (around 3000 rows). And all the rows are like: #Arrival_Date# #Arrival_Time# #Departure_Date# #Departure_Time# 2017/01/01 23:30 2017/01/01 00:30 2017/02/01 23:30 2017/02/01 23:40 2017/03/01 15:45 2017/03/01 17:30 2017/04/10 23:50 2017/04/10 00:30 But my problem is: I need to correct the date on Departure_Date (2017/01/02 and 2017/04/11). Is there a way to do this automatically? My professor told me to use Python, but I have no idea how. Any suggestions about where should I start?
has comment: http://stackoverflow.com/comment/88199705
type: Question
has comment: http://stackoverflow.com/comment/88199975
has title: Correct Date and Time using Python
has comment: http://stackoverflow.com/comment/88199693
tagged with: linux

http://stackoverflow.com/q/50656643
has comment: http://stackoverflow.com/comment/88348523
type: Question
score: 0
has comment: http://stackoverflow.com/comment/88325320
tagged with: speech-recognition
tagged with: python
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has title: Speech Recognition with opening programs
has body: import speech_recognition as sr import os # obtain audio from the microphone r = sr.Recognizer() def get_audio(): global RealAudio with sr.Microphone() as source: print("Say something!") audio = r.listen(source) try: RealAudio = r.recognize_google(audio) print(RealAudio) commands_audio() except sr.UnknownValueError: print("Impossibole to understand.\n") get_audio() def start_function(): global Discord try: if Discord == 'False': os.system('cd D:\\Program\\Steam\Steam.exe') if 'open Steam' in RealAudio: Discord = False start_function() get_audio() I just started on my voice program. I always get the error message ´Could not find the specific directory´. I want it to open the program Steam.exe.
tagged with: speech

http://stackoverflow.com/q/50660947
has body: I am using python 3.5 with opencv. I want to use 2 threads: Thread 1: Save the video to a file Thread 2: Display the video to the user To view/capture the video from webcam i am using snippets of code from the following website: opencv video docs I can capture and save the video using the following code: # Define the codec and create VideoWriter object fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480)) while(True): ret, frame = cap.read() if ret==True: frame = cv2.flip(frame,0) # write the flipped frame out.write(frame) else: break out.release() cv2.destroyAllWindows() I can view the video using the following code: while(True): # Capture frame-by-frame ret, frame = cap.read() cv2.imshow('frame',frame) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break cv2.destroyAllWindows() Each of these pieces of code are in their own functions called capture and display. I then call them in separate threads with pythons threading library as follows: cap = cv2.VideoCapture(0) Thread(target=capture).start() Thread(target=display).start() cap.release() I get an error I assume is related to both threads wanting to access the video buffer at the same time. I understand this can be done without threads but there are other things I would like to do further than can only be done in separate threads. How can I access the cap video capture from both threads?
has comment: http://stackoverflow.com/comment/88333428
score: 1
accepted answer: http://stackoverflow.com/a/50668843
has comment: http://stackoverflow.com/comment/88332114
has comment: http://stackoverflow.com/comment/88332659
has title: How to access 1 webcam with 2 threads
has comment: http://stackoverflow.com/comment/88332351
tagged with: video-capture
has comment: http://stackoverflow.com/comment/88332727
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88344867
type: AnsweredQuestion
tagged with: multithreading
upvote count: 1
has answer: http://stackoverflow.com/a/50668843
type: Question
tagged with: opencv

http://stackoverflow.com/comment/88193348
score: 0
type: AnswerComment
has text: Okay , And if possible then plz give this question a like .
type: Comment
comment on: http://stackoverflow.com/a/50576575

http://stackoverflow.com/a/50667108
has body: Here's an alternative that will work if the domain name length is variable, rather than always 11 characters long: In [2]: df['tweet text'].str.split('//').str[-1] Out[2]: 1 example.com Name: tweet text, dtype: object
upvote count: 2
has comment: http://stackoverflow.com/comment/88344426
has comment: http://stackoverflow.com/comment/88344391
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50667036
downvote count: 0

http://stackoverflow.com/q/50628915
type: AnsweredQuestion
type: Question
tagged with: pyinstaller
tagged with: python
has answer: http://stackoverflow.com/a/63945272
has answer: http://stackoverflow.com/a/56453165
has answer: http://stackoverflow.com/a/50672927
score: 0
tagged with: tensorflow
has title: Pyinstaller, tensorflow.contrib lazy loader error at runtime
has body: Using the 3.3.1 pyinstaller in python 3.5 32bit, I converted a .py application to .exe The application uses tensorflow and at some point throws Traceback (most recent call last): File "face_classify.py", line 140, in &lt;module&gt; loaded_model = load_c3d.c3d_model_obj(user_case) File "load_c3d.py", line 80, in __init__ 'wc1': _variable_with_weight_decay('wc1', [3, 3, 3, 3, 64], 0.0005), File "load_c3d.py", line 47, in _variable_with_weight_decay var = _variable_on_cpu(name, shape, tf.contrib.layers.xavier_initializer()) File "site-packages\tensorflow\__init__.py", line 35, in __getattr__ File "importlib\__init__.py", line 126, in import_module File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 956, in _find_and_load_unlocked ImportError: No module named 'tensorflow.contrib' This happens when running the .exe. Looks like a file path issue. The __init__.py of tensorflow does this # Lazily import the `tf.contrib` module. This avoids loading all of the # dependencies of `tf.contrib` at `import tensorflow` time. def __getattr__(self, item): global contrib # Replace the lazy loader with the imported module itself. import importlib # pylint: disable=g-import-not-at-top contrib = importlib.import_module('tensorflow.contrib') return getattr(contrib, item) To me it looks like this lazy loading cannot be tracked by pyinstaller. However the contrib folder is correctly placed inside my python installation: C:\Python35\Lib\site-packages\tensorflow\contrib How can I solve this issue?
possible better answer: http://stackoverflow.com/a/57095400
accepted answer: http://stackoverflow.com/a/50672927
answer count: 4
linked to: http://stackoverflow.com/q/45830206
has answer: http://stackoverflow.com/a/57095400

http://stackoverflow.com/comment/88183499
has text: Sure, `pandas` can deal with thousands of dataframes too. Naming columns the same, like this, almost certainly isn't the best way to approach your problem.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50587023
score: 0

http://stackoverflow.com/comment/88158802
score: 0
type: AnswerComment
has text: Actual data is Column1: Source Column2: Subject Column3: Timestamp Column4: Date Column5:Grouped Names( i addressed in previous post) Column6: Name (Person). I think it was mis manipulated over publishing data under Column4:Date will come and Column5: Grouped names called(Actionable/Duplicate--). I thought of that getting error for above one. But Thanks a lot and can you just re-check with my current input. @petersmith
type: Comment
comment on: http://stackoverflow.com/a/50574501

http://stackoverflow.com/a/50617408
answers question: http://stackoverflow.com/q/50601867
type: Answer
score: 0
has body: No worries, I have figured out a solution to my problem using turtle: Thank you for the help. Hopefully this can also help you if you have a similar problem. :) import turtle import time #Define the 'playgif' operator which will be used to run the code later on def playgif(frame): screen = turtle.Screen() screen.setup(700,700) screen.bgpic(frame) screen.exitonclick turtle.bgcolor('#33EDAE') #load the images and assign them each a variable frame1 = "Frame01.jpg" frame2 = "Frame02.jpg" frame3 = "Frame03.jpg" frame4 = "Frame04.jpg" frame5 = "Frame05.jpg" frame6 = "Frame06.jpg" frame7 = "Frame07.jpg" frame8 = "Frame08.jpg" frame9 = "Frame09.jpg" frame10 = "Frame10.jpg" frame11 = "Frame11.jpg" frame12 = "Frame12.jpg" #run the code by calling each frame and delaying each frames exposure again = 1 while again == 1: playgif(frame1) time.sleep(0.08) playgif(frame2) time.sleep(0.08) playgif(frame3) time.sleep(0.08) playgif(frame4) time.sleep(0.08) playgif(frame5) time.sleep(0.08) playgif(frame6) time.sleep(0.08) playgif(frame7) time.sleep(0.08) playgif(frame8) time.sleep(0.08) playgif(frame9) time.sleep(0.08) playgif(frame10) time.sleep(0.08) playgif(frame11) time.sleep(0.08) playgif(frame12) time.sleep(0.08) mainloop()

http://stackoverflow.com/q/50587012
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/88190338
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88190554
has title: Multiple solution with scipy.optimize.nnls
has comment: http://stackoverflow.com/comment/88189584
score: 1
has comment: http://stackoverflow.com/comment/88190102
has comment: http://stackoverflow.com/comment/88190118
downvote count: 1
tagged with: scipy
has comment: http://stackoverflow.com/comment/88185246
type: Question
has body: I am using scipy.optimize.nnls to compute non-negative least square fit with a coefficients sum to 1. I always get the same solution when I run the computation. This is the code I am using : #! /usr/bin/env python3 import numpy as np import scipy.optimize as soptimize if __name__ == '__main__': C = np.array([[112.771820, 174.429720, 312.175750, 97.348620], [112.857010, 174.208300, 312.185270, 93.467580], [114.897210, 175.661850, 314.275100, 99.015480] ]); d = np.array([[112.7718, 174.4297, 312.1758, 97.3486], [112.7718, 174.4297, 312.1758, 97.3486]]); for line in d: ret , _= soptimize.nnls(C.T, line) print(ret) And everytime I get : [9.99992794e-01 7.27824399e-06 0.00000000e+00] [9.99992794e-01 7.27824399e-06 0.00000000e+00] I need to compute multiple solutions with a tolerance range, and select the solution that fits best my needs. Do anyone know how to get different solutions for the same input matrix ?
linked to: http://stackoverflow.com/q/50591532
has comment: http://stackoverflow.com/comment/88195486
has comment: http://stackoverflow.com/comment/88189651
tagged with: least-squares
has comment: http://stackoverflow.com/comment/88191059
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88190033

http://stackoverflow.com/q/50688439
has comment: http://stackoverflow.com/comment/88386773
upvote count: 0
answer count: 1
has body: I did find this function on stackoverflow which extract hostname, aliaslist, and ipaddrlist, but how can I make a function which take a hostname and search all the websites associated with it (hosted by it)? &gt;&gt;&gt; import socket &gt;&gt;&gt; def get_ips_for_host(host): try: ips = socket.gethostbyname_ex(host) except socket.gaierror: ips=[] return ips &gt;&gt;&gt; ips = get_ips_for_host('www.slowtravelmagazine.com') &gt;&gt;&gt; print(repr(ips)) ('ext-cust.squarespace.com', ['www.slowtravelmagazine.com'], ['198.185.159.144', '198.185.159.145', '198.49.23.144', '198.49.23.145'])
has comment: http://stackoverflow.com/comment/88387882
favorite count: 0
accepted answer: http://stackoverflow.com/a/50688476
has comment: http://stackoverflow.com/comment/88387151
tagged with: sockets
has comment: http://stackoverflow.com/comment/88386840
has title: Finding all the websites which are on a particular hostname
has comment: http://stackoverflow.com/comment/88386979
tagged with: python
score: -1
tagged with: python-3.x
tagged with: dns
downvote count: 1
type: Question
type: AnsweredQuestion
tagged with: network-programming
has answer: http://stackoverflow.com/a/50688476

http://stackoverflow.com/a/50661706
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50661676
score: 1
has body: You can use Pillow Python Imaging Library (Fork). But i think simple to do this in graphical editor.
has comment: http://stackoverflow.com/comment/88333575
has comment: http://stackoverflow.com/comment/88333683
has comment: http://stackoverflow.com/comment/88333623
downvote count: 0

http://stackoverflow.com/a/50594389
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50594310
downvote count: 0
type: Answer
has body: In Bash File give the complete path to the file #!/usr/bin/env bash echo $PWD &gt; /tmp/test.txt python3.6 "/absolute/path/to/upload.py"; #path is correct exit 0 check the directory in which the program run. $ cat /tmp/test.txt

http://stackoverflow.com/comment/88354903
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50672428
has text: That was it, in a local folder worked perfectly. Thanks folks
score: 0

http://stackoverflow.com/comment/88335737
type: AnswerComment
score: 0
type: Comment
has text: thanks @Wen, your soln is slightly different from what I want I want only the top 2 regions, but your soln returns all regions
comment on: http://stackoverflow.com/a/50653550

python
tags question: http://stackoverflow.com/q/50653173
tags question: http://stackoverflow.com/q/50600841
tags question: http://stackoverflow.com/q/50561487
tags question: http://stackoverflow.com/q/50634023
tags question: http://stackoverflow.com/q/50578890
tags question: http://stackoverflow.com/q/50542736
tags question: http://stackoverflow.com/q/50669874
tags question: http://stackoverflow.com/q/50688184
tags question: http://stackoverflow.com/q/50630569
tags question: http://stackoverflow.com/q/50673870
tags question: http://stackoverflow.com/q/50553585
tags question: http://stackoverflow.com/q/50601513
tags question: http://stackoverflow.com/q/50653097
tags question: http://stackoverflow.com/q/50688288
tags question: http://stackoverflow.com/q/50693624
tags question: http://stackoverflow.com/q/50594501
tags question: http://stackoverflow.com/q/50671746
tags question: http://stackoverflow.com/q/50555232
tags question: http://stackoverflow.com/q/50597816
tags question: http://stackoverflow.com/q/50675844
tags question: http://stackoverflow.com/q/50548843
tags question: http://stackoverflow.com/q/50624170
tags question: http://stackoverflow.com/q/50671008
tags question: http://stackoverflow.com/q/50575902
tags question: http://stackoverflow.com/q/50612208
tags question: http://stackoverflow.com/q/50670930
tags question: http://stackoverflow.com/q/50662773
tags question: http://stackoverflow.com/q/50696077
tags question: http://stackoverflow.com/q/50623028
tags question: http://stackoverflow.com/q/50669990
tags question: http://stackoverflow.com/q/50630942
tags question: http://stackoverflow.com/q/50628396
tags question: http://stackoverflow.com/q/50547145
tags question: http://stackoverflow.com/q/50604740
tags question: http://stackoverflow.com/q/50630372
tags question: http://stackoverflow.com/q/50564992
tags question: http://stackoverflow.com/q/50605424
tags question: http://stackoverflow.com/q/50634131
tags question: http://stackoverflow.com/q/50573241
tags question: http://stackoverflow.com/q/50627861
tags question: http://stackoverflow.com/q/50657350
tags question: http://stackoverflow.com/q/50559811
tags question: http://stackoverflow.com/q/50621172
tags question: http://stackoverflow.com/q/50658159
tags question: http://stackoverflow.com/q/50685300
tags question: http://stackoverflow.com/q/50690761
tags question: http://stackoverflow.com/q/50567883
tags question: http://stackoverflow.com/q/50655175
tags question: http://stackoverflow.com/q/50660585
tags question: http://stackoverflow.com/q/50576975
tags question: http://stackoverflow.com/q/50632664
tags question: http://stackoverflow.com/q/50558284
tags question: http://stackoverflow.com/q/50647396
tags question: http://stackoverflow.com/q/50550801
tags question: http://stackoverflow.com/q/50571115
tags question: http://stackoverflow.com/q/50683537
tags question: http://stackoverflow.com/q/50548942
tags question: http://stackoverflow.com/q/50613755
tags question: http://stackoverflow.com/q/50611330
tags question: http://stackoverflow.com/q/50660972
tags question: http://stackoverflow.com/q/50563372
tags question: http://stackoverflow.com/q/50554272
tags question: http://stackoverflow.com/q/50559609
tags question: http://stackoverflow.com/q/50548895
tags question: http://stackoverflow.com/q/50634955
tags question: http://stackoverflow.com/q/50566848
tags question: http://stackoverflow.com/q/50580779
tags question: http://stackoverflow.com/q/50647108
tags question: http://stackoverflow.com/q/50689700
tags question: http://stackoverflow.com/q/50577852
tags question: http://stackoverflow.com/q/50628068
tags question: http://stackoverflow.com/q/50687234
tags question: http://stackoverflow.com/q/50616439
tags question: http://stackoverflow.com/q/50595929
tags question: http://stackoverflow.com/q/50642777
tags question: http://stackoverflow.com/q/50634781
tags question: http://stackoverflow.com/q/50689005
tags question: http://stackoverflow.com/q/50587822
tags question: http://stackoverflow.com/q/50668981
tags question: http://stackoverflow.com/q/50618404

http://stackoverflow.com/comment/88317214
type: Comment
type: QuestionComment
has text: This is actually a better solution than what I was trying to do before, thanks.
comment on: http://stackoverflow.com/q/50653253
score: 0

http://stackoverflow.com/comment/88327760
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50658884
has text: @BasileStarynkevitch it is not possible to run on GPU because of memory issue. Shouldn't numba speeds up even on CPU?
type: Comment

http://stackoverflow.com/a/50598146
accepted answer of: http://stackoverflow.com/q/50597462
answers question: http://stackoverflow.com/q/50597462
has body: You can use ElementTree module from xml.etree: from xml.etree import ElementTree struct = """ &lt;data&gt; {} &lt;/data&gt; """ def reformat(tree): root = tree.getroot() seen = [] for neighbor in root.iter('data'): for child in neighbor.getchildren(): tx = child.text if tx == ',': yield "&lt;combined&gt;{}&lt;combined&gt;".format(' '.join(seen)) seen = [] else: seen.append(tx) with open('test.xml') as f: tree = ElementTree.parse(f) print(struct.format(',\n'.join(reformat(tree)))) result: &lt;data&gt; &lt;combined&gt;Head1 Inter1 Inter2 Inter3 Inter4 Inter5&lt;combined&gt;, &lt;combined&gt;Head2 Inter6 Inter7 Inter8 Inter9&lt;combined&gt; &lt;/data&gt; Note that if you're not sure all the blocks are separated wit comma you can simply change the condition if tx == ',': according your file format. You can also check when the tx is started with 'Head' then if seen is not empty yield the seen and clear its content, otherwise append the tx and continue.
upvote count: 5
type: Answer
downvote count: 0
score: 5
type: AcceptedAnswer

http://stackoverflow.com/a/50589289
has comment: http://stackoverflow.com/comment/88202225
has comment: http://stackoverflow.com/comment/88189138
has comment: http://stackoverflow.com/comment/88193762
upvote count: 4
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/50589085
type: Answer
has body: import svgutils.transform as st template = st.fromfile('firstLayer.svg') second_svg = st.fromfile('secondLayer.svg') template.append(second_svg) template.save('merged.svg') This is a solution from another post. The catch is that you will need to choose different class names for each file, or the styles from each file will interfere with each other. For example cls-1 class from the first document will also have applied to it opacity:0.05 from the second document. secondLayer.svg will be the file that you append, because appending it will mean its further down the document, which for SVG means it will be on top.
has comment: http://stackoverflow.com/comment/88195652

http://stackoverflow.com/comment/88108665
has text: ok so name of the variable cant be "read" some how by the function and return as string? thank you! :)
type: Comment
comment on: http://stackoverflow.com/q/50547975
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88111163
type: Comment
has text: https://www.cnbc.com/ali-montag/?page=31 this one is also selected in links file which is not required
comment on: http://stackoverflow.com/a/50550045
score: 0
type: AnswerComment

http://stackoverflow.com/q/50605918
tagged with: flask
has comment: http://stackoverflow.com/comment/109797814
favorite count: 0
has comment: http://stackoverflow.com/comment/88224272
has comment: http://stackoverflow.com/comment/128778648
tagged with: python
downvote count: 0
has answer: http://stackoverflow.com/a/56474482
has comment: http://stackoverflow.com/comment/88241488
has comment: http://stackoverflow.com/comment/88223966
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/88241472
score: 1
has body: I have a Flask Uwsgi deploy It was working fine until today Curl to the server will get below curl http://ip:5000/api -i curl: (52) Empty reply from server The uwsgi log shows below （Please do not say check logs any more. Logs are here already） [pid: 15778|app: 0|req: 552000/854000] 8.8.8.8 () {22 vars in 241 bytes} [Wed May 30 16:40:51 2018] HEAD / => generated 0 bytes in 0 msecs (HTTP/1.0 404) 2 headers in 72 bytes (0 switches on core 0) ...The work of process 15778 is done. Seeya! worker 1 killed successfully (pid: 15778) Respawned uWSGI worker 1 (new pid: 18478 Also this one is not duplicate to the question Django, uWSGI & nginx: Process dies for "no reason" The cause for that one is that he has a setting --max-requests 10 And he do not have the Master setting. So in his log you can see req 1000/1000 which reach the limit. Mine is not!!! I set the master=true in my conf also you can see from the wsgi log. not reaching the max request!!! The config of uwsgi is like below [uwsgi] socket = /opt/CephMGRServer/ceph_mgr_server/var/tmp/uwsgi.sock http= 0.0.0.0:5000 chdir=/opt/CephMGRServer/ceph_mgr_server wsgi-file = app.py callable=app master = true processes=2 threads=2 max-requests=2000 chmod-socket=664 vacuum=true daemonize = /opt/CephMGRServer/ceph_mgr_server/var/log/uwsgi.log I can see the process still there and the 5000 port being listened ps -ef | grep wsgi| grep -v grep| grep -v tail root 2083 22075 0 May28 ? 00:00:00 uwsgi --ini /opt/CephMGRServer/ceph_mgr_server/conf/wsgi.ini root 18478 22075 0 16:40 ? 00:00:00 uwsgi --ini /opt/CephMGRServer/ceph_mgr_server/conf/wsgi.ini root 22075 1 0 May24 ? 00:02:50 uwsgi --ini /opt/CephMGRServer/ceph_mgr_server/conf/wsgi.ini root 22090 22075 0 May24 ? 00:01:48 uwsgi --ini /opt/CephMGRServer/ceph_mgr_server/conf/wsgi.ini Although it is worth noticing that only two process listening 5000 and uwsgi have 4 process lsof -i:5000 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME uwsgi 22075 root 3u IPv4 76455578 0t0 TCP *:com…
has title: Why uwsgi return empty when curl?
linked to: http://stackoverflow.com/q/5430370
tagged with: uwsgi
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/88165422
comment on: http://stackoverflow.com/q/50577761
has text: @GeneByun:i omitted the 5th condition.But it shows None.Thanks
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50692572
linked to: http://stackoverflow.com/q/1369526
favorite count: 0
tagged with: python-3.x
type: Question
score: 0
upvote count: 1
possible better answer: http://stackoverflow.com/a/50692809
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/50692809
has body: i m trying to extract a specific column from a arabic file to another file this is my code # coding=utf-8 import csv from os import open file = open('jamid.csv', 'r', encoding='utf-8') test = csv.reader(file) f = open('col.txt','w+', 'wb' ,encoding='utf-8') for row in test: if len(row[0].split("\t"))&gt;3 : f.write((row[0].split("\t"))[3].encode("utf-8")) f.close() and the file is like this : 4 جَوَارِيفُ جواريف جرف اسم 18 حَرْقى حرقى حرق اسم 24 غَزَواتٌ غزوات غزو اِسْمٌ i keep gitting the same error : File "col.py", line 5, in &lt;module&gt; file = open('jamid.csv', 'r', encoding='utf-8') TypeError: an integer is required (got type str)
has comment: http://stackoverflow.com/comment/88395710
answer count: 3
has comment: http://stackoverflow.com/comment/88395729
has comment: http://stackoverflow.com/comment/88394993
has answer: http://stackoverflow.com/a/50693163
has comment: http://stackoverflow.com/comment/88395518
has comment: http://stackoverflow.com/comment/88395638
accepted answer: http://stackoverflow.com/a/50693163
has comment: http://stackoverflow.com/comment/88394926
tagged with: arabic
has comment: http://stackoverflow.com/comment/88395371
has comment: http://stackoverflow.com/comment/88394864
has comment: http://stackoverflow.com/comment/88395974
has comment: http://stackoverflow.com/comment/88395778
has comment: http://stackoverflow.com/comment/88394633
has title: extract a column from a csv arabic file python
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/50692884
linked to: http://stackoverflow.com/q/18766955
has comment: http://stackoverflow.com/comment/88395482

http://stackoverflow.com/comment/88154858
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50572602
has text: Your call to `super().__init__(self,name)` in `Wizard.__init__()` would fail because you need to pass `player_type` as well.

http://stackoverflow.com/q/50595953
has answer: http://stackoverflow.com/a/50598928
answer count: 3
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50597758
tagged with: http://stackoverflow.com/tag/docx
has body: I'm using python-docx to put a text into MS Word. I can make it bold or center,but how to do both. Here's the bold: p=document.add_paragraph().add_run('test word') p.font.size = Pt(16) p.bold = True Here's the center: p=document.add_paragraph('test word') p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER how to do both bold and center?
has comment: http://stackoverflow.com/comment/88207117
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has title: How do I apply both bold and center in python-docx?
accepted answer: http://stackoverflow.com/a/50595990
type: Question
possible better answer: http://stackoverflow.com/a/50597758
has answer: http://stackoverflow.com/a/50595990
tagged with: python-docx

http://stackoverflow.com/a/50665603
has comment: http://stackoverflow.com/comment/88341915
has comment: http://stackoverflow.com/comment/88343215
has comment: http://stackoverflow.com/comment/88393001
type: Answer
score: 11
has comment: http://stackoverflow.com/comment/88406412
accepted answer of: http://stackoverflow.com/q/50664839
has comment: http://stackoverflow.com/comment/88342906
answers question: http://stackoverflow.com/q/50664839
has comment: http://stackoverflow.com/comment/88342999
has comment: http://stackoverflow.com/comment/88342956
has comment: http://stackoverflow.com/comment/88343268
has body: You can use Pandas Excel output with user defined header format with solution for change width by content: writer = pd.ExcelWriter("file.xlsx", engine='xlsxwriter') # Convert the dataframe to an XlsxWriter Excel object. Note that we turn off # the default header and skip one row to allow us to insert a user defined # header. Also remove index values by index=False df.to_excel(writer, sheet_name='Sheet1', startrow=1, header=False, index=False) workbook = writer.book worksheet = writer.sheets['Sheet1'] # Add a header format. header_format = workbook.add_format({ 'bold': True, 'fg_color': '#ffcccc', 'border': 1}) for col_num, value in enumerate(df.columns.values): worksheet.write(0, col_num, value, header_format) column_len = df[value].astype(str).str.len().max() # Setting the length if the column header is larger # than the max column value length column_len = max(column_len, len(value)) + 3 print(column_len) # set the column length worksheet.set_column(col_num, col_num, column_len) # Close the Pandas Excel writer and output the Excel file. writer.save() Changed your solution: writer = pd.ExcelWriter('final.xlsx'), engine='xlsxwriter') for f in glob.glob(os.path.join(Path, "*.csv")): df = pd.read_csv(f) df.to_excel(writer, sheet_name=os.path.basename(f)) workbook = writer.book worksheet = writer.sheets[os.path.basename(f)] # Add a header format. header_format = workbook.add_format({ 'bold': True, 'fg_color': '#ffcccc', 'border': 1}) for col_num, value in enumerate(df.columns.values): worksheet.write(0, col_num, value, header_format) column_len = df[value].astype(str).str.len().max() # Setting the length if the column header is larger # than the max column value length column_len = max(column_len, len(value)) + 3 print(column_len) # set the column length worksheet.set_column(col_num, col_num, column_len) writer.save() EDIT: writer = pd.ExcelWriter("file.xlsx", engine='xlsxwriter') #skip 2 rows df.to_excel(writer, sheet_name='Sheet1', startrow=2, header=False, index=Fal…
has comment: http://stackoverflow.com/comment/134032639
has comment: http://stackoverflow.com/comment/88343032
upvote count: 11
has comment: http://stackoverflow.com/comment/88341945
has comment: http://stackoverflow.com/comment/88341655
has comment: http://stackoverflow.com/comment/88343247
has comment: http://stackoverflow.com/comment/88342975
has comment: http://stackoverflow.com/comment/88343018
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88341776

http://stackoverflow.com/q/50633765
tagged with: character-encoding
has answer: http://stackoverflow.com/a/50633803
accepted answer: http://stackoverflow.com/a/50633803
answer count: 1
downvote count: 0
has body: I have a string which I converted to binary representation using str.encode('utf-8'). After that I expect getsizeof() and len() return the same value, but it appears that sys.getsizeof() always return a bigger value. I then send this binary data over socket to node.js server and store them in Buffer. Both Buffer.length and Buffer.byteLength return the same value, which is equal to len() value in Python. I can't figure out what is going on there and why Buffer.byteLength is not the same as sys.getsizeof(). My data is not always strings or may have different encoding, so I want to make sure that I know the size in bytes, not in characters.
favorite count: 0
tagged with: byte
has title: Get byte size of the binary data (python3.6)
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88277765
upvote count: 2
type: Question

http://stackoverflow.com/comment/88432152
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50696370
type: QuestionComment
has text: @KamranHosseini Please take a look at my answer

http://stackoverflow.com/comment/88296432
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50643121
has text: Try `df[df["S"] == 0.65]`

http://stackoverflow.com/comment/88116081
score: 0
comment on: http://stackoverflow.com/a/50552648
type: AnswerComment
type: Comment
has text: How strange, I find your solution more elegant.

http://stackoverflow.com/q/50624537
has comment: http://stackoverflow.com/comment/88259295
tagged with: python
has title: Flask UnboundLocalError: local variable 'latitu' referenced before assignment
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88259125
has comment: http://stackoverflow.com/comment/88259407
has answer: http://stackoverflow.com/a/50624749
type: UnansweredQuestion
has body: I have two files csv the first is for restaurants and the second is for tourist places so I have two list of longitude and latitude and I want to view them in a map, my problem is when I want to view both at the same time i get this error : UnboundLocalError: local variable 'latitu' referenced before assignment I managed this code as below : fullmap = Map( identifier="fullmap", varname="fullmap", style=( "height:100%;" "width:100%;" "top:0;" "left:0;" "position:absolute;" "z-index:200;" ), lat= 46.160329 , lng=-1.151139, markers=[ { 'icon': icons.dots.red, 'title': prix, 'lat': lat, 'lng': lng, 'infobox': ( titre+ " &lt;b style='color:#ffcc00;'&gt; " +prix+ "&lt;/b&gt;" "&lt;h3&gt;surface:&lt;b style='color:#33BBFF;'&gt;" +surface+"&lt;/b&gt;&lt;/h2&gt;" "&lt;br&gt;Longitude: "+lng+ "" "&lt;br&gt;Latitude: "+lat+ "" ) }for lat,lng ,titre,surface,prix in zip(Lat,Lng,Titre,Surface,Prix), { 'icon': icons.dots.yellow, 'lat': latitu, 'lng': longitu, 'infobox': ( title+ " &lt;b style='color:#ffcc00;'&gt; &lt;/b&gt;" "&lt;br&gt;Longitude: "+latitu+ "" "&lt;br&gt;Latitude: "+lat+ "" ) }for latitu,longitu ,title in zip(Latitude,Longitude,Title) ], circles=[{ 'fill_color': '#FF00FF', 'fill_opacity': 0.2, 'center': { 'lat': 46.160329, 'lng': -1.151139 }, 'radius': 1300, 'infobox': "Centre ville" }], fit_markers_to_bounds = True # maptype = "TERRAIN", # zoom="5" ) Any help would be appreciated.
tagged with: flask
upvote count: 0
favorite count: 0
score: -1
type: Question

http://stackoverflow.com/q/50603012
has comment: http://stackoverflow.com/comment/88215171
score: 0
has comment: http://stackoverflow.com/comment/88216012
has answer: http://stackoverflow.com/a/50606560
linked to: http://stackoverflow.com/q/8949252
answer count: 1
has body: I am trying to run a python script that logs into Amazon Redshift DB and then execute a SQL command. I use a tool called Airflow for workflow management. When running the below code, I am able to login fine to the DB but when trying to execute the SQL command get the below error. **AttributeError: 'NoneType' object has no attribute 'execute'** Code: ## Login to DB def db_log(**kwargs): global db_con try: db_con = psycopg2.connect( " dbname = 'name' user = 'user' password = 'pass' host = 'host' port = '5439'") except: print("I am unable to connect") print('Connection Task Complete') task_instance = kwargs['task_instance'] task_instance.xcom_push(key="dwh_connection" , value = "dwh_connection") return (dwh_connection) def insert_data(**kwargs): task_instance = kwargs['task_instance'] db_con_xcom = task_instance.xcom_pull(key="dwh_connection", task_ids='DWH_Connect') cur = db_con_xcom cur.execute("""insert into tbl_1 select limit 2 ;""") Could anyone help me fix this. Thanks.. Complete code: ## Third party Library Imports import pandas as pd import psycopg2 import airflow from airflow import DAG from airflow.operators.python_operator import PythonOperator from airflow.operators.bash_operator import BashOperator from datetime import datetime, timedelta from sqlalchemy import create_engine import io # Following are defaults which can be overridden later on default_args = { 'owner': 'airflow', 'depends_on_past': False, 'start_date': datetime(2018, 5, 29, 12), 'email': ['airflow@airflow.com'] } dag = DAG('sample1', default_args=default_args) ## Login to DB def db_log(**kwargs): global db_con try: db_con = psycopg2.connect( " dbname = 'name' user = 'user' password = 'pass' host = 'host' port = '5439'") except: print("I am unable to connect") print('Connection Task Complete') task_instance = kwargs['task_instance'] task_instance.xcom_push(key="dwh_connection" , value = "dwh_connection") return (dwh_connection) t1 = PythonOperator( task_id='DWH_Connect', python_callable=data_…
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88215563
duplicate of: http://stackoverflow.com/q/8949252
type: UnansweredQuestion
has title: AttributeError: 'NoneType' object has no attribute 'execute'
tagged with: python
upvote count: 1
downvote count: 1
type: Question
tagged with: airflow
has comment: http://stackoverflow.com/comment/88228027

http://stackoverflow.com/q/50542266
score: 1
has comment: http://stackoverflow.com/comment/88096338
downvote count: 1
type: Question
has body: I am trying to write program that print maximal points of the input but it is not giving correct output. Definition of maximal- Given a set of points P = {p1,p2,...,pn} in 2-space, each represented by its x and y integer coordinates, output the set of the maximal points of P, that is, those points pi, such that pi is not dominated by any other point of P (not both coordinate are dominated) Example input: p1(5,7),p2(47,84),p3(89,4),(46,54),(100,1) Example outut: p2(47,84),(89,4),(100,1) The idea of my program is to first sort the point according to x axis then compare the y coordinate. a=[[5,7],[47,84],[89,4][46,54],[100,1]] #sort according to x axis mylist.sort(key=lambda x: x[0]) #compare y coordinate of i to all element right to i for i in reversed(range(len(a)): j=i+1 while (j&lt;len(a)): if(mylist[i][1]&gt;mylist[j][1]): j+=1 if(j==len(a)): print(mylist[i])
has comment: http://stackoverflow.com/comment/88096487
has answer: http://stackoverflow.com/a/50542567
answer count: 1
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50542567
has title: python program to find maximal in 2d array
tagged with: python
has comment: http://stackoverflow.com/comment/88096409
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88096224
upvote count: 2

http://stackoverflow.com/q/50592188
tagged with: graphviz
accepted answer: http://stackoverflow.com/a/50596258
downvote count: 0
answer count: 1
has body: I am making graph using graph. Is there any way I can get default edge label ? digraph G { a -&gt; b [label="a -&gt; b" ]; b -&gt; c [label=" b -&gt;" ]; } I want to get label default not manually.
linked to: http://stackoverflow.com/q/1806870
favorite count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50596258
type: AnsweredQuestion
has title: Graphviz default label for edge
score: 1
type: Question

http://stackoverflow.com/comment/88333672
has text: would two bugs with same priority, happening in same months but different years, end up as being counted the same ?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50661541

curl
tags question: http://stackoverflow.com/q/50552484
tag name: curl
tags question: http://stackoverflow.com/q/50554302
type: Tag

http://stackoverflow.com/q/50574021
type: Question
score: 3
tagged with: python
has comment: http://stackoverflow.com/comment/88157561
tagged with: file
answer count: 1
upvote count: 3
tagged with: bitwise-operators
has title: Get "average" of several randomly broken copies of a same file
has answer: http://stackoverflow.com/a/50574094
downvote count: 0
type: UnansweredQuestion
has body: Due to a broken controller, files get randomly corrupted while being downloaded from a USB flash drive. I have downloaded several copies of the same file and the errors seem to be generally unique and random for each copy. Thus, I need a script to compare several (3 to 5) broken copies of a same file (~100 Mb in size each) and 'vote' for correct value for each byte, appending it afterwards to an output file. Is there a quick and easy way to implement this in Python 3?
favorite count: 0

http://stackoverflow.com/comment/88324617
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50657166
has text: I assume this is homework, and `set`s are either not introduced or verboten?
score: 0

http://stackoverflow.com/q/50697612
tagged with: sorting
accepted answer: http://stackoverflow.com/a/50697712
tagged with: tuples
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50697712
has title: Python sorting multiple tuples
has comment: http://stackoverflow.com/comment/88404383
tagged with: python
has body: I am using python for image matching. The feature vectors for reference images is stored in a mysql database. For every new image, i generate the feature vector, find the difference between the test image and the reference vectors in mysql db and return the matches based on distance. This is working well. However, I want to sort the results based on the distance and get only the top 10 results that has the highest distance. My code so far is as follows: for i,a in enumerate(data): features=[float(x) for x in a[6:]] d = chi2_distance(features, queryFeatures) results=a[1],d #res=sorted(results, key=itemgetter(1)) #results.sort(key=lambda x:x[1]) #results=sorted(results,key=lambda x: x[1]) #results=sorted(results, key=lambda x: x[1], reverse=True) print(type(results)) When I print type of results i get the following: &lt;type 'tuple'&gt; &lt;type 'tuple'&gt; &lt;type 'tuple'&gt; When I print just the results, I get: (127209905L, 6.459347693123215) (127281515L, 7.790508647801378) (127312977L, 6.374409391826666) I tried various methods including, converting the tuples to list and then sorting by list, but none of them worked. I am relatively a new bee working on python...any guidance on how to go about this would be very helpful. The expected output is (127281515L, 7.790508647801378) (127209905L, 6.459347693123215) (127312977L, 6.374409391826666)
type: AnsweredQuestion
type: Question

http://stackoverflow.com/q/50578088
tagged with: cpanel
score: 0
answer count: 2
has body: I am getting a 503 error trying to test the initial install of a Python 3.6 project on my host which uses cPanel. I am not adding anything yet, literally just hitting the URL. Here is the boilerplate passenger_wsgi.py file created when adding the app via cPanel: import os import sys sys.path.insert(0, os.path.dirname(__file__)) def application(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) message = 'It works!\n' version = 'Python %s\n' % sys.version.split()[0] response = '\n'.join([message, version]) return [response.encode()] The public URL can be found here: https://slickmcfavorite.com/36 I can deploy a Python 2.7 project and get the "It works!" no problem. This is my first attempt at a Python app on cPanel, so I don't know if there are extra settings needed for 3.6 vs 2.7. Unfortunately, my host says they're an "Unmanaged Host" so they won't help me. Any advice from troubleshooting to how to approach my host's support team would be appreciated. Even as an unmanaged host, seems strange that using "their" provided software to install an app doesn't work and they won't support it. Again a noob, so any advice is welcome. Thanks in advance.
has title: 503 Error Deploying a Python 3.6 Project on cPanel
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/71960698
has answer: http://stackoverflow.com/a/53859106
type: Question
tagged with: http-status-code-503

http://stackoverflow.com/a/50596423
has comment: http://stackoverflow.com/comment/88203003
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88202201
type: Answer
has comment: http://stackoverflow.com/comment/88202973
has comment: http://stackoverflow.com/comment/88202899
score: 0
has comment: http://stackoverflow.com/comment/88202478
has comment: http://stackoverflow.com/comment/88203179
has comment: http://stackoverflow.com/comment/88203143
accepted answer of: http://stackoverflow.com/q/50595909
has body: I think the closest you can get is storing data as bytes. Bytes actually have a built in method in python .hex() so you can always see a hex representation of it. my_bytes = b'some words' my_bytes.hex() #'736f6d6520776f726473' If you are sending the data raw as bytes, you could then do a direct comparison without worrying about hex at all. However, if you want to still send the hex as a string, you will need binascii.unhexlify() import binascii binascii.unhexlify('736f6d6520776f726473') # b'some words' Though it is generally preferred to send bytes, as then you do not have to worry about encoding and other issues. Hope this helps! Edit: Wanted to add dealing directly with the code you provided, it would look something like: comparable_bytes = b'verify_me' comparable_hex = '7665726966795f6d65' ip_hex = binascii.unhexlify(input('&gt;&gt; ')) # Input the Hex numbers assert ip_hex == comparable_bytes assert ip_hex.hex() == comparable_hex Edit 2: Multiple hex character input # Remove whitespace, allow for entry with or without spaces ip = input().strip().replace(' ', '') bytestring = binascii.unhexlify(ip) Then you can directly send bytestring.
has comment: http://stackoverflow.com/comment/88202815
has comment: http://stackoverflow.com/comment/88202626
answers question: http://stackoverflow.com/q/50595909
has comment: http://stackoverflow.com/comment/88203056
has comment: http://stackoverflow.com/comment/88202400
has comment: http://stackoverflow.com/comment/88202641
has comment: http://stackoverflow.com/comment/88202065

http://stackoverflow.com/q/50668028
tagged with: python
has body: def Date_Form(request): if request.method == 'POST': form = DateForm(request.POST) if form.is_valid(): date = form.cleaned_data['date'] date1 = DateOptions.objects.get(date=date) flight_date = Flight.objects.filter(date_options=date1) form1 = KeyWordForm(request.POST) return render(request, 'app/index.html',{'flight_date': flight_date, 'date': date, 'form1': form1}) else: form = DateForm() return render(request, 'app/options.html', {'form':form}) def Search_Destination(request): if request.method =='POST': form1 = KeyWordForm(request.POST) if form1.is_valid(): destination = form1.cleaned_data['destination'].capitalize() result= Flight.objects.filter(destination__icontains=destination, date_options=????) return render(request, 'app/search.html', {'result':result, 'destination':destination}) else: form1 = KeyWordForm() return render(request, 'app/searchfield.html', {'form1':form1}) This part is where I struggle: result= Flight.objects.filter(destination__icontains=destination, date_options=????) I want to be able to use the same date_option as date1. I know I can't say date_options=date1. The system won't recognize it.
type: AnsweredQuestion
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/50668131
has answer: http://stackoverflow.com/a/50668131
score: 0
has answer: http://stackoverflow.com/a/50668809
accepted answer: http://stackoverflow.com/a/50668809
has title: Django: how do I use object from a previous form to filter object?
tagged with: python-3.x
tagged with: django

http://stackoverflow.com/q/50654531
has body: I'm trying to return each item in a row based off places in Column D. At the moment I'm doing this via df = df.loc[df['D'] == '#specific place']. This works fine but if I have 50 different places this code becomes very inefficient. I would have to alter df = df.loc[df['D'] == '#another specific place'] 50 times. I would do this if the places stayed the same but each dataset contains different places. Is there a more efficient way to return the rows for each place? I have a separate df with each place that I can return to a list. Can I use the values in this list to return the functions in import pandas as pd places = ['Home','Away','Shops'] d = ({ 'C' : ['08:00:00','XX','08:10:00','XX','08:41:42','XX','08:50:00','XX', '09:00:00', 'XX','09:15:00','XX','09:21:00','XX','09:30:00','XX','09:40:00','XX'], 'D' : ['Home','','Home','','Away','','Shops','','Away','','Shops','','Home','','Away','','Home',''], 'E' : ['Num:','','Num:','','Num:','','Num:','','Num:', '','Num:','','Num:','','Num:', '','Num:', ''], 'F' : ['1','','1','','1','','1','','1', '','2','','2','','1', '','2',''], 'A' : ['A','','A','','A','','A','','A','','A','','A','','A','','A',''], 'B' : ['Stop','','Res','','Stop','','Start','','Res','','Stop','','Res','','Start','','Start',''] }) df = pd.DataFrame(data=d) #Select desired place Home = df.loc[df['D'] == 'Home'] Shops = df.loc[df['D'] == 'Shops'] Away = df.loc[df['D'] == 'Away'] Intended Output: A B C D E F 0 A Stop 08:00:00 Home Num: 1 2 A Res 08:10:00 Home Num: 1 12 A Res 09:21:00 Home Num: 2 16 A Start 09:40:00 Home Num: 2 6 A Start 08:50:00 Shops Num: 1 10 A Stop 09:15:00 Shops Num: 2 4 A Stop 08:41:42 Away Num: 1 8 A Res 09:00:00 Away Num: 1 14 A Start 09:30:00 Away Num: 1
has answer: http://stackoverflow.com/a/50654912
tagged with: pandas
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/50659514
answer count: 2
tagged with: python
has title: Efficiently return specific rows in a pandas df
accepted answer: http://stackoverflow.com/a/50659514
score: 0
tagged with: loops
possible better answer: http://stackoverflow.com/a/50654912

http://stackoverflow.com/a/50691892
has body: def price_check(value): if value.isdigit(): return value else: return False Then something like this: price_input = false while not price_input: price_input = price_check(input('OK. Please input the product price: ')) if not price_input: print('Invalid input') products1={"id": str(int(products[-1]['id'])+1), "name": name_input, "system": system_input, "line": line_input, 'price': price_input} products.append(products1) This will work if you never want the user to enter an invalid input into the dictionary. You can easily customise this to work with try and excepts but it seems like you may be doing homework so I'll let you figure that out. If you want it to just print 'invalid' and continue along without saving then you'll want to do: price_input = price_check(input('OK. Please input the product price: ')) if not price_input: print('Invalid input') else: products1={"id": str(int(products[-1]['id'])+1), "name": name_input, "system": system_input, "line": line_input, 'price': price_input} products.append(products1)
answers question: http://stackoverflow.com/q/50691808
score: 0
type: Answer

http://stackoverflow.com/a/50652121
type: Answer
has body: I used the Transpose function to reshape scaled_train_samples from a 2 by 2100 matrix into a 2100 by 2 matrix. Thanks guys for your contributions. #Transpose scaled_train_samples = scaled_train_samples.transpose() However, running the line of code below gives the accuracy of the model. And currently, I am getting an accuracy of 51.52%, is there anything I can do to improve the accuracy of this model? #Evaluate the model scores = model.evaluate(scaled_train_samples, train_labels) print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50634095

http://stackoverflow.com/q/50581979
has answer: http://stackoverflow.com/a/50582314
has answer: http://stackoverflow.com/a/50582097
tagged with: python
has body: Let B inherit from A. Suppose that some of B's behavior depends on the class attribute cls_x and we want to set up this dependency during construction of B objects. Since it is not a simple operation, we want to wrap it in a class method, which the constructor will call. Example: class B(A): cls_x = 'B' @classmethod def cm(cls): return cls.cls_x def __init__(self): self.attr = B.cm() Problem: cm as well as __init__ will always be doing the same things and their behavior must stay the same in each derived class. Thus, we would like to put them both in the base class and not define it in any of the derived classes. The only difference will be the caller of cm - either A or B (or any of B1, B2, each inheriting from A), whatever is being constructed. So what we'd like to have is something like this: class A: cls_x = 'A' @classmethod def cm(cls): return cls.cls_x def __init__(self): self.attr = ClassOfWhateverIsInstantiated.cm() #how to do this? class B(A): cls_x = 'B' I feel like it's either something very simple I'm missing about Python's inheritance mechanics or the whole issue should be handled entirely differently. This is different than this question as I do not want to override the class method, but move its implementation to the base class entirely.
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
answer count: 2
tagged with: class-method
has title: Inheriting a virtual class method - how to call it from base class?
tagged with: inheritance
accepted answer: http://stackoverflow.com/a/50582314
upvote count: 1
linked to: http://stackoverflow.com/q/20925137
favorite count: 0
possible better answer: http://stackoverflow.com/a/50582097

http://stackoverflow.com/comment/88332544
type: QuestionComment
has text: Please edit your post to `print(response.text)` before every attempt to `json.loads(response.text)`... This will help you and us debug the problem (which is that your URL isn't always returning a full JSON body)
score: 0
comment on: http://stackoverflow.com/q/50660600
type: Comment

http://stackoverflow.com/comment/88599073
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50681988
has text: Glad that worked. Please, also see [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers)
score: 0

http://stackoverflow.com/comment/88155682
has text: Python 2 treats "str" and "bytes" as the same thing - but "unicode" as different object. Python 3 treads "str" and "unicode" as the same thing - but "bytes" as different object.
comment on: http://stackoverflow.com/q/50565380
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/comment/88309084
type: AnswerComment
comment on: http://stackoverflow.com/a/50649052
score: 0
type: Comment
has text: This is not a solution to her problem, more like a comment than an answer.

http://stackoverflow.com/comment/110645233
has text: "(using './/*[@class="text"]/text()' does also give the result you want)." - This saved my whole night Merci
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50670941

http://stackoverflow.com/a/52230603
answers question: http://stackoverflow.com/q/50626087
score: 1
has body: VCRTestCase is built on top of vcr. It doesn't make much sense to use both simultaneously. If you remove the line @vcr.use_cassette(), you should see a cassette named TwitterRetrievalAndStorageTests.test_recorded_session.yaml (or json) in your cwd. If instead, you don't inherit from VCRTestCase and use @vcr.use_cassette(), the cassette name should be test_recorded_session.yaml and it should be in the same folder as your class. In general, if you use both, I have noticed that vcr takes precedence over vcrpy-unittest but that is not consistently the case.
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/99754045
has text: Actually, I had to white-list `pygame` to get rid of these false errors. Should I edit this answer accordingly? Does white-listing `lxml` work for some users?
type: AnswerComment
comment on: http://stackoverflow.com/a/52600893
type: Comment
score: 2

http://stackoverflow.com/comment/88263010
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50626360
has text: Take advantage of the fact that `f(x*100 + y) == f(x*100) + f(y)` for `0 <= x, y < 100`.

http://stackoverflow.com/q/50623755
has answer: http://stackoverflow.com/a/67351509
tagged with: python
answer count: 4
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has body: My GA individual is a random sequence of int (eg: [4, 5, 10, 11, 8, 12, 9, 13, 2, 6, 3, 7, 0, 14, 15, 1]) that follows certain order constraint which is dealt with in another self-defined function. How can I incorporate my order constraint function in the DEAP individual initialization? I implemented this way with the inspiration from https://groups.google.com/forum/#!msg/deap-users/KZYYHCGrFyY/x1nXcXpCyscJ: class MyContainer(list): def __init__(self, attributes): # Some initialisation with received values # self.attr1 = attributes[0] pass def generate_individual(ind_class, size): # ind_class will receive a class inheriting from MyContainer # individual = ind_class(random.random() for _ in range(size)) individual = ind_class(random.sample(range(IND_SIZE), k=size)) individual = make_individual_valid(individual, other_parameters) # make_individual_valid is the self-defined order constraint function return individual creator.create('FitnessMin', base.Fitness, weights=(-1.0,)) creator.create('Individual', MyContainer, fitness=creator.FitnessMin) toolbox = base.Toolbox() toolbox.register('individual', generate_individual, creator.Individual, size=IND_SIZE) toolbox.register('population', tools.initRepeat, list, toolbox.individual) But I got below error: AttributeError: 'list' object has no attribute 'fitness'
has comment: http://stackoverflow.com/comment/103745500
has title: How to define custom Genetic Algorithm individuals that follow certain order pattern using DEAP
score: 2
has answer: http://stackoverflow.com/a/67363264
tagged with: genetic-algorithm
has answer: http://stackoverflow.com/a/50847403
type: Question
tagged with: deap
downvote count: 0
has answer: http://stackoverflow.com/a/63450201
linked to: http://stackoverflow.com/q/42841985

http://stackoverflow.com/comment/88272442
type: Comment
type: QuestionComment
has text: Possible duplicate of [How to import other Python files?](https://stackoverflow.com/questions/2349991/how-to-import-other-python-files)
comment on: http://stackoverflow.com/q/50631205
score: 3

http://stackoverflow.com/comment/88342561
type: Comment
comment on: http://stackoverflow.com/q/50666277
has text: And in what order did you run these functions? Because you're modifying `y` for every `g(y)`
type: QuestionComment
score: 0

http://stackoverflow.com/q/50547218
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50547322
tagged with: django-2.0
tagged with: python
has answer: http://stackoverflow.com/a/57334689
tagged with: python-3.x
type: UnansweredQuestion
tagged with: pip
has body: Why does the python code below crash my website? But the code at the very bottom does not crash the website Here is the code that crashes the website: from django.urls import path, include from django.contrib import admin urlpatterns = [ path('admin/', admin.site.urls), path('', include('learning_logs.urls')), ] Here is the code that does not crash: from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), ] Thank you
type: Question
linked to: http://stackoverflow.com/q/47947673
has title: What is incorrect with my urls.py file? Chapter 18 of Python Crash Course

http://stackoverflow.com/q/50618058
upvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88245979
has answer: http://stackoverflow.com/a/50630173
tagged with: python
tagged with: tree
tagged with: breadth-first-search
downvote count: 1
type: Question
has body: I coded a Tree level order traversal and although my code has the right output, it throws a Line 21: AttributeError: 'NoneType' object has no attribute 'val' I know that one of the values somewhere is returning Null and I can't find where. # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None import queue class Solution(object): def levelOrder(self, root): L = queue.Queue() local = [] result = [] L.put(root) counter = 0 while not L.empty(): counter = L.qsize() local = [] while counter &gt;0: node = L.get() local.append(node.val) if(node.left): L.put(node.left) if(node.right): L.put(node.right) counter -=1 result.append(local) return result
score: -1
has title: Code not working Tree BFS search
has comment: http://stackoverflow.com/comment/88246433

http://stackoverflow.com/comment/88317895
has text: Before or after, whatever works
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50652915

http://stackoverflow.com/comment/112719175
type: Comment
type: QuestionComment
has text: As mentioned by @rhaertel80, the solution is to remove [`tf.decode_base64()`](https://www.tensorflow.org/api_docs/python/tf/io/decode_base64) from [`ServingInputReceiver`](https://stackoverflow.com/q/53410469/5524090) because the base64 decoding is done behind the scenes if passing data to the network via the `"b64"` JSON key. This was surprising because it is not currently mentioned in the [AI Platform docs](https://cloud.google.com/ai-platform/prediction/docs/reference/rest/v1/projects/predict#data-encoding).
comment on: http://stackoverflow.com/q/50597376
score: 0

http://stackoverflow.com/q/50582470
upvote count: 2
has title: Is there a way to get a list of all the parameters in protobufs in python?
type: Question
score: 2
has body: I want to write a script to fill protocol buffers values with the values given in a JSON file without knowing what is in the .proto file.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50602855
has comment: http://stackoverflow.com/comment/88175475
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88175174
tagged with: protocol-buffers
has comment: http://stackoverflow.com/comment/88174059
has answer: http://stackoverflow.com/a/50602855
tagged with: python
has comment: http://stackoverflow.com/comment/88175058
has comment: http://stackoverflow.com/comment/88175793

http://stackoverflow.com/comment/88194594
comment on: http://stackoverflow.com/q/50592552
score: 0
has text: Possible duplicate of https://stackoverflow.com/questions/10615901/trim-whitespace-using-pil/10616717
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50638138
has comment: http://stackoverflow.com/comment/88289239
has comment: http://stackoverflow.com/comment/88287933
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/88286604
has comment: http://stackoverflow.com/comment/88289731
tagged with: python-3.x
tagged with: pycharm
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50639825
has comment: http://stackoverflow.com/comment/88287552
tagged with: python
has answer: http://stackoverflow.com/a/50639827
tagged with: python-requests
has title: python - Not Found The requested URL was not found on the server
type: Question
has body: I am new to Python web programming, I created a small program. But everytime I run, I am getting this error, The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error. This is my code below Sample.py: from flask import Flask, render_template app = Flask(__name__) @app.route("/profile/<name>") def profile(name): return render_template("profile.html", name=name) if __name__ == "__main__": app.run(debug=True) profile.html: Welcome to thefunnybone Hey there, {{name}} Description: I am writting a name in the url, and it returns some text on the browser. As said earlier, I am new to this language, therfore, please help me that I could provide any info regarding the program. This is my project structure:
has comment: http://stackoverflow.com/comment/88289588
has comment: http://stackoverflow.com/comment/88289716

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

http://stackoverflow.com/comment/88331907
comment on: http://stackoverflow.com/a/50660675
type: Comment
has text: This `base` problem is exactly what I was trying to solve... I don't know where it came from
score: 0
type: AnswerComment

http://stackoverflow.com/q/50587621
tagged with: orm
tagged with: mysql
tagged with: django
upvote count: 1
downvote count: 1
type: Question
has title: How to Join two tables in Django
has comment: http://stackoverflow.com/comment/90622024
has comment: http://stackoverflow.com/comment/88184681
linked to: http://stackoverflow.com/q/13092268
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50588045
has comment: http://stackoverflow.com/comment/88184643
has body: select * from article_article left join article_upvote ON article_article.id=article_upvote.article_id I want to write this query with Django ORM. How can I write this? Please help
type: UnansweredQuestion
tagged with: python
score: 0

http://stackoverflow.com/q/50645280
has comment: http://stackoverflow.com/comment/88302900
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50647362
has comment: http://stackoverflow.com/comment/88302546
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88303076
type: Question
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/88301245
has title: Python: CSV file with multiple headers - combine into one data frame?
favorite count: 0
has body: I want to use some data from the NOAA website. It is a csv file with data for all hurricanes since 1851, with a format like this: <a href="https://storage.googleapis.com/kaggle-datasets/692/1307/atlantic.pdf?GoogleAccessId=web-data@kaggle-161607.iam.gserviceaccount.com&amp;Expires=1528119944&amp;Signature=N5nu8BId0S5GBN0btBrvAYXzuBrOdgCuJrwcfNGXcLVgzDvjFV3BCNNAW2Qj1Fhkl2m%2FTkkgJMwchR3DK5V39fKZANhAoe64BGpKcwGJuBLZ3UulZ6syq43vqAWNf29siHy3ghzsE%2FOdoZssHIwK%2B0MY1lMs1R41p%2FZzVdjZ7%2Bg4n0EtVir4is0zwRfQLi0Z1wT0dgJrNrLFzmjtTpZhuDN75x4Tl5u%2FEeA3o9Rx31GH8ts3emEIK2jXPNf567wvXt6%2FOAMJWJSigOrYYQ4CrIbbEy%2FUPkR3rIgc4oGG%2FFSFUvHL2TEkB5Y%2F6Ub4FWIu%2BzMjO%2FrhLx2GO7TjCZq%2Fng%3D%3D" rel="nofollow noreferrer" title="Format example / README">Format example / README file As you can see, although everything is contained within one csv file, each hurricane has it's own table, with a separate header. How can I remove the headers and put the information in a "Hurricane Name" column instead? I want to combine everything into a single data frame, so it's easier to use. Thanks! Example: AL092011, IRENE, 3, 20110821, 0000, , TS, 15.0N, 59.0W, 45, 1006, 105, 0, 0, 45, 0, 0, 0, 0, 0, 0, 0, 0, 20110821, 0600, , TS, 16.0N, 60.6W, 45, 1006, 130, 0, 0, 80, 0, 0, 0, 0, 0, 0, 0, 0, 20110821, 1200, , TS, 16.8N, 62.2W, 45, 1005, 130, 0, 0, 70, 0, 0, 0, 0, 0, 0, 0, 0, AL092012, ANOTHER_NAME, 2, 20110821, 1800, , TS, 17.5N, 63.7W, 50, 999, 130, 20, 0, 70, 30, 0, 0, 0, 0, 0, 0, 0, 20110822, 0000, , TS, 17.9N, 65.0W, 60, 993, 130, 30, 30, 90, 30, 0, 0, 30, 0, 0, 0, 0, I would like the header information into columns, like so: AL092011, IRENE, 20110821, 0000, , TS, 15.0N, 59.0W, 45, 1006, 105, 0, 0, 45, 0, 0, 0, 0, 0, 0, 0, 0, AL092011, IRENE, 20110821, 0600, , TS, 16.0N, 60.6W, 45, 1006, 130, 0, 0, 80, 0, 0, 0, 0, 0, 0, 0, 0, AL092011, IRENE, 20110821, 1200, , TS, 16.8N, 62.2W, 45, 1005, 130, 0, 0, 70, 0, 0, 0, 0, 0, 0, 0, 0, AL092012, ANOTHER_NAME, 20110821, 1800, , TS, 17.5N, 63.7W, 50, 999, 130, …
has comment: http://stackoverflow.com/comment/88303418
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/50647362
tagged with: python
has comment: http://stackoverflow.com/comment/88303399
linked to: http://stackoverflow.com/q/45876998
score: -1
has comment: http://stackoverflow.com/comment/88303258
downvote count: 2
tagged with: data-cleaning
upvote count: 1
has comment: http://stackoverflow.com/comment/88303178

dataframe
tags question: http://stackoverflow.com/q/50548818
tags question: http://stackoverflow.com/q/50696680
tags question: http://stackoverflow.com/q/50683529
tags question: http://stackoverflow.com/q/50656469
tags question: http://stackoverflow.com/q/50618066
tags question: http://stackoverflow.com/q/50607119
tags question: http://stackoverflow.com/q/50686319
tags question: http://stackoverflow.com/q/50571210
tags question: http://stackoverflow.com/q/50606882
tags question: http://stackoverflow.com/q/50565746
tags question: http://stackoverflow.com/q/50609312
tags question: http://stackoverflow.com/q/50576086
tags question: http://stackoverflow.com/q/50595924
tags question: http://stackoverflow.com/q/50659623
tags question: http://stackoverflow.com/q/50575053
tags question: http://stackoverflow.com/q/50667088
tags question: http://stackoverflow.com/q/50641588
tags question: http://stackoverflow.com/q/50556537
tags question: http://stackoverflow.com/q/50579484
tags question: http://stackoverflow.com/q/50599934
tags question: http://stackoverflow.com/q/50682535
tags question: http://stackoverflow.com/q/50660949
tags question: http://stackoverflow.com/q/50677770
tags question: http://stackoverflow.com/q/50608966
tags question: http://stackoverflow.com/q/50608418
tags question: http://stackoverflow.com/q/50619447
tags question: http://stackoverflow.com/q/50688694
tags question: http://stackoverflow.com/q/50572331
tags question: http://stackoverflow.com/q/50629848
tags question: http://stackoverflow.com/q/50542039
tags question: http://stackoverflow.com/q/50662176
tags question: http://stackoverflow.com/q/50645280
tags question: http://stackoverflow.com/q/50640267
tags question: http://stackoverflow.com/q/50547614
tags question: http://stackoverflow.com/q/50657239
tags question: http://stackoverflow.com/q/50587318
tags question: http://stackoverflow.com/q/50589099
tags question: http://stackoverflow.com/q/50594636
tags question: http://stackoverflow.com/q/50593621
tags question: http://stackoverflow.com/q/50631670
tags question: http://stackoverflow.com/q/50631849
tags question: http://stackoverflow.com/q/50623347
tags question: http://stackoverflow.com/q/50655222
tags question: http://stackoverflow.com/q/50632256
tags question: http://stackoverflow.com/q/50677554
tags question: http://stackoverflow.com/q/50582361
tags question: http://stackoverflow.com/q/50551289
tags question: http://stackoverflow.com/q/50664424
tags question: http://stackoverflow.com/q/50553413
tags question: http://stackoverflow.com/q/50600944
tags question: http://stackoverflow.com/q/50685107
tags question: http://stackoverflow.com/q/50578481
tags question: http://stackoverflow.com/q/50549011
tags question: http://stackoverflow.com/q/50591076
tags question: http://stackoverflow.com/q/50647832
tags question: http://stackoverflow.com/q/50595548
tags question: http://stackoverflow.com/q/50697536
tags question: http://stackoverflow.com/q/50596972
tags question: http://stackoverflow.com/q/50612682
tags question: http://stackoverflow.com/q/50580427
tags question: http://stackoverflow.com/q/50608790
tags question: http://stackoverflow.com/q/50685689
tags question: http://stackoverflow.com/q/50634988
tags question: http://stackoverflow.com/q/50552644
tags question: http://stackoverflow.com/q/50634552
tags question: http://stackoverflow.com/q/50591949
tags question: http://stackoverflow.com/q/50561412
tags question: http://stackoverflow.com/q/50574077
tags question: http://stackoverflow.com/q/50609465
tags question: http://stackoverflow.com/q/50689985
tags question: http://stackoverflow.com/q/50657545
tags question: http://stackoverflow.com/q/50612340
tags question: http://stackoverflow.com/q/50618889
tags question: http://stackoverflow.com/q/50687955
tags question: http://stackoverflow.com/q/50619846
tags question: http://stackoverflow.com/q/50672875
tags question: http://stackoverflow.com/q/50607740
tags question: http://stackoverflow.com/q/50547040
tags question: http://stackoverflow.com/q/50615848
tags question: http://stackoverflow.com/q/50675667

http://stackoverflow.com/comment/88132218
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50560806
has text: @stonerock - so need `df = pd.DataFrame({'id':testdata['id'].values[:-1], 'predictions':predictions})`
score: 1

http://stackoverflow.com/q/50631905
tagged with: socketserver
has answer: http://stackoverflow.com/a/50633312
favorite count: 0
tagged with: sockets
tagged with: multithreading
accepted answer: http://stackoverflow.com/a/50633312
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: tcp
has body: I'm trying to create a threaded TCP socket server that can handle multiple socket request at a time. To test it, I launch several thread in the client side to see if my server can handle it. The first socket is printed successfully but I get a [Errno 32] Broken pipe for the others. I don't know how to avoid it. import threading import socketserver import graphitesend class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler): def handle(self): data = self.request.recv(1024) if data != "": print(data) class ThreadedTCPServer(socketserver.ThreadingTCPServer): allow_reuse_address = True def __init__(self, host, port): socketserver.ThreadingTCPServer.__init__(self, (host, port), ThreadedTCPRequestHandler) def stop(self): self.server_close() self.shutdown() def start(self): threading.Thread(target=self._on_started).start() def _on_started(self): self.serve_forever() def client(g): g.send("test", 1) if __name__ == "__main__": HOST, PORT = "localhost", 2003 server = ThreadedTCPServer(HOST, PORT) server.start() g = graphitesend.init(graphite_server = HOST, graphite_port = PORT) threading.Thread(target = client, args=(g,)).start() threading.Thread(target = client, args=(g,)).start() threading.Thread(target = client, args=(g,)).start() threading.Thread(target = client, args=(g,)).start() threading.Thread(target = client, args=(g,)).start() threading.Thread(target = client, args=(g,)).start() threading.Thread(target = client, args=(g,)).start() server.stop()
type: Question
has title: Multithreaded TCP socket
linked to: http://stackoverflow.com/q/1294382
downvote count: 0
answer count: 1
score: 1

http://stackoverflow.com/q/50585963
favorite count: 0
has comment: http://stackoverflow.com/comment/88181220
tagged with: python-3.x
tagged with: terminal-emulator
tagged with: terminal
tagged with: python
has answer: http://stackoverflow.com/a/50586463
has answer: http://stackoverflow.com/a/50586129
type: AnsweredQuestion
has body: Getting bored with the traditional cmd on windows, so wanted to build one myself. Any tutorial, library, etc would help. Thanks in advance! :)
has comment: http://stackoverflow.com/comment/88181483
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/50586129
score: 0
answer count: 2
upvote count: 1
has title: How to create a terminal emulator in Python
tagged with: shell
has comment: http://stackoverflow.com/comment/88181343
accepted answer: http://stackoverflow.com/a/50586463

http://stackoverflow.com/q/50674923
type: Question
score: 3
has comment: http://stackoverflow.com/comment/119850506
has comment: http://stackoverflow.com/comment/88831068
has answer: http://stackoverflow.com/a/67806331
has comment: http://stackoverflow.com/comment/89057219
tagged with: python
answer count: 1
has body: When my script is pulling the data from Intacct 100 xml object at a time everything is working fine using my resultid to remember the offset and pull the next once, and for some reason, it gets to one of the loops and it throws an error saying not well-formed (invalid token): line 1, column 57565 knowing I'm using the same credentials all the time. With that error thrown it skips a 100 object and move to the next one and keep pulling the data. My question is: how to rollback after I get an error so my resultid won't skip the data when the error is thrown? is there's a function or something I should add to my XML query? Please see below for my current XML query. Thank you! headers = {'Content-type': 'x-intacct-xml-request'} API_URL = 'https://api.intacct.com/ia/xml/xmlgw.phtml' req_shell_next="""<?xml version="1.0" encoding="iso-8859-1"?> %s %s testRequestId false 3.0 false %s %s %s %s """ request_data_next = urllib2.Request(API_URL, req_shell_next % (auth_info_senderid, auth_info_password, auth_info_userid, auth_info_companyid, auth_info_userpw, resultId ), headers) response_str_data_next = urllib2.urlopen(request_data_next).read() response_xml_data_next = ET.ElementTree(ET.fromstring(response_str_data_next))
tagged with: intacct
upvote count: 3
has comment: http://stackoverflow.com/comment/88904921
has title: rollback to the previous offset when an error is throw while pulling data from Intacct
has comment: http://stackoverflow.com/comment/88932557
has comment: http://stackoverflow.com/comment/88819064
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88882129
favorite count: 0
tagged with: accounting

http://stackoverflow.com/comment/88159744
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50575254
has text: Are you sure you were in the correct console?

http://stackoverflow.com/q/50607740
type: Question
accepted answer: http://stackoverflow.com/a/50607852
answer count: 8
has answer: http://stackoverflow.com/a/50607856
linked to: http://stackoverflow.com/q/26762100
tagged with: dataframe
has answer: http://stackoverflow.com/a/74096660
score: 45
tagged with: pandas
has answer: http://stackoverflow.com/a/50607795
downvote count: 0
upvote count: 45
has title: Reverse a get_dummies encoding in pandas
possible better answer: http://stackoverflow.com/a/61251205
favorite count: 0
has answer: http://stackoverflow.com/a/61251205
has answer: http://stackoverflow.com/a/62085741
has answer: http://stackoverflow.com/a/74552813
has answer: http://stackoverflow.com/a/76426558
has body: Column names are: ID,1,2,3,4,5,6,7,8,9. The col values are either 0 or 1 My dataframe looks like this: ID 1 2 3 4 5 6 7 8 9 1002 0 1 0 1 0 0 0 0 0 1003 0 0 0 0 0 0 0 0 0 1004 1 1 0 0 0 0 0 0 0 1005 0 0 0 0 1 0 0 0 0 1006 0 0 0 0 0 1 0 0 0 1007 1 0 1 0 0 0 0 0 0 1000 0 0 0 0 0 0 0 0 0 1009 0 0 1 0 0 0 1 0 0 I want the column names in front of the ID where the value in a row is 1. The Dataframe i want should look like this: ID Col2 1002 2 // has 1 at Col(2) and Col(4) 1002 4 1004 1 // has 1 at col(1) and col(2) 1004 2 1005 5 // has 1 at col(5) 1006 6 // has 1 at col(6) 1007 1 // has 1 at col(1) and col(3) 1007 3 1009 3 // has 1 at col(3) and col(7) 1009 7 Please help me in this, Thanks in advance
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50607852

http://stackoverflow.com/a/50542032
type: Answer
has comment: http://stackoverflow.com/comment/88095413
answers question: http://stackoverflow.com/q/50541926
has comment: http://stackoverflow.com/comment/88095335
has body: Use str.strip() Ex: cldb = ('\t\tm\mrcg1234', '\t\tmrcg1235', '\t\tmrcg1235.me.com') cldb = tuple([i.strip() for i in cldb]) print(cldb) Output: ('m\\mrcg1234', 'mrcg1235', 'mrcg1235.me.com')
has comment: http://stackoverflow.com/comment/88095357
score: 0

http://stackoverflow.com/comment/88235663
type: QuestionComment
has text: Is this line oriented data? Text or binary? Encoded text like utf-8? On your destination machine you could write a program that does `for line in sys.stdin: do your processing` then run it the same way you run cat on the destination.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50612710

http://stackoverflow.com/a/51136873
answers question: http://stackoverflow.com/q/50661037
score: 0
type: Answer
has body: You need to specify bounds as the latitude and longitude for two points describing a rectangular boundary for the search: southwest corner latitude/longitude,northeast corner latitude/longitude. So the request will be something like this: www.strava.com/api/v3/segments/explore?bounds=41.002403,28.963957,41.016741,28.986722&amp;activity_type=running It is better specify activity_type parameter to request only running/cycling segments. Last but not least: remember that the request only returns the top 10 segments matching a specified query. So if you want every segment of Istanbul you need to send different requests at different latitude/longitude and then mix the results.

http://stackoverflow.com/a/50592357
upvote count: 7
has body: Set index and columns names to None: df.index.name = None df.columns.name = None Or use rename_axis: df = df.rename_axis(None).df.rename_axis(None, axis=1)
score: 7
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50592334
type: Answer
answers question: http://stackoverflow.com/q/50592334

http://stackoverflow.com/a/50615728
answers question: http://stackoverflow.com/q/50615711
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88241591
type: Answer
has comment: http://stackoverflow.com/comment/88241435
downvote count: 0
score: 1
has body: outfile = open('Test_between_dates' + str(the_date) + '.csv',"a",newline='') outfile is determined by the_date and therefore different every day.
accepted answer of: http://stackoverflow.com/q/50615711

http://stackoverflow.com/q/50669309
has answer: http://stackoverflow.com/a/50669330
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50669377
tagged with: separator
possible better answer: http://stackoverflow.com/a/50669328
has answer: http://stackoverflow.com/a/50669334
has answer: http://stackoverflow.com/a/50669328
has body: I have multiple str-variables and I want to concatenate them to single line but with separator: var_a + 'SEPARATOR' + var_b + 'SEPARATOR' + var_c + 'SEPARATOR' + var_d As you can see, it looks disgusting and unefficient. So, is there any way to make it simpler by adding separator automatically between separate strings? P.S. I like the way it works in print function: print(var_a, var_b, var_c, var_d, sep="SEPARATOR")
has answer: http://stackoverflow.com/a/50669355
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/50669377
has title: Less complicated concatenation in Python
tagged with: concatenation
tagged with: string
score: 0
answer count: 5
tagged with: python

http://stackoverflow.com/comment/88098171
has text: That did the trick! Thanks for your response! I normally dont use 'apply' functions against the entire dataframe, so using the axis did not occur to me.
comment on: http://stackoverflow.com/q/50543453
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88201634
type: AnswerComment
comment on: http://stackoverflow.com/a/50596199
type: Comment
has text: yes, works the same except the connection should be specified with `cursorclass=MySQLdb.cursors.DictCursor`
score: 0

http://stackoverflow.com/a/50661608
has body: In the kv file, do the following. Please refer to the example below for details. Replace GridLayout: with BoxLayout: because GridLayout with cols: 1 has the similar presentation as BoxLayout with orientation: 'vertical'. Remove cols: 1 At Image:, add size_hint_x: 0.4 Replace pos_hint: {'right': 0.5} with pos_hint: {'right': 1} Note GridLayout does not has an attribute called orientation. Example main.py from kivy.lang import Builder from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition Builder.load_string(""" &lt;ClientScreen&gt;: BoxLayout: id: main_grid_layout orientation: 'vertical' Label: id: name_label text: '&lt;NO MENU NAME&gt;' size_hint_y: None size: self.texture_size halign: 'left' valign: 'center' text_size: self.size padding_x: 35 canvas.before: Color: rgb: .6, .6, .6 Rectangle: pos: self.pos size: self.size Image: id: image source: 'raspberrypi.png' size_hint_x: 0.4 pos_hint: {'right': 1} ScrollView: id: text_scroll_view bar_width: 10 size: self.size GridLayout: id: text_grid_layout orientation: 'vertical' cols: 1 size_hint_y: None height: self.minimum_height ScrollView: size: self.size bar_width: 10 size_hint_y: 0.40 GridLayout: id: action_grid_layout # padding: [10, 10, 10, 10] orientation: 'vertical' cols: 1 size_hint_y: None # row_default_height: 30 height: self.minimum_height """) class LoginScreen(Screen): pass class ClientScreen(Screen): pass class MyApp(App): def build(self): from kivy.core.window import Window sm = ScreenManager() sm.transition = NoTransition() global CLIENT_SCREEN LOGIN_SCREEN = LoginScreen(name='login') CLIENT_SCREEN = ClientScreen(name='client') sm.add_widget(LOGIN_SCREEN) sm.add_widget(CLIENT_SCREEN) sm.current = 'client' Window.size = (300, 120) self.title = 'xNemesis Client V0' return sm MyApp().run() Output
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/50661401
upvote count: 1
answers question: http://stackoverflow.com/q/50661401
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/88113973
score: 0
comment on: http://stackoverflow.com/q/50551439
has text: what does it mean? what you want to do explain your question
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88337593
comment on: http://stackoverflow.com/q/50663716
type: Comment
score: 1
has text: Try `"".count("")`. Now try `"a".count("")`. Now try `"aa".count("")`. Now try `"aaa".count("")`. Now try `"aaaa".count("")`.
type: QuestionComment

http://stackoverflow.com/q/50612655
has comment: http://stackoverflow.com/comment/88235295
has comment: http://stackoverflow.com/comment/88236520
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50613511
type: Question
score: 0
has comment: http://stackoverflow.com/comment/88235440
answer count: 1
has comment: http://stackoverflow.com/comment/88235369
has body: I have got this code, and in order to understand it better I added a line to track where the pid is equal to zero: import os, time def counter(count): # run in new process for i in range(count): time.sleep(0.00001) # simulate real work print('[%s] =&gt; %s' % (os.getpid(), i)) for i in range(5): pid = os.fork() print("The pid is: ", pid)# the one I added if pid != 0: print('Process %d spawned' % pid) # in parent: continue else: counter(5) # else in child/new process os._exit(0) # run function and exit print('Main process exiting.') Questions: 1) what activates the call to counter? are the new processes checking their pid and if this is equal to zero, then call to counter? 2) If I change the sleep time to 1 second (instead of tenths of mils), then no data for child processes is printed. What is going on in the background then ? I got this result: the pid is: 6 Prociss 6 spawned the pid is: 7 Prociss 7 spawned the pid is: 8 Prociss 8 spawned the pid is: 9 Prociss 9 spawned the pid is: 10 Prociss 10 spawned Main prociss exiting. the pid is: 0 the pid is: 0 the pid is: 0 the pid is: 0 [6] =&gt; 0 [8] =&gt; 0 [7] =&gt; 0 [6] =&gt; 1 the pid is: 0 [8] =&gt; 1 [6] =&gt; 2 [7] =&gt; 1 [9] =&gt; 0 [6] =&gt; 3 [8] =&gt; 2 [7] =&gt; 2 [9] =&gt; 1 [8] =&gt; 3 [6] =&gt; 4 [7] =&gt; 3 [8] =&gt; 4 [7] =&gt; 4 [9] =&gt; 2 [10] =&gt; 0 [9] =&gt; 3 [10] =&gt; 1 [9] =&gt; 4 [10] =&gt; 2 [10] =&gt; 3 [10] =&gt; 4 ...Program finished with exit code 0
tagged with: fork
has comment: http://stackoverflow.com/comment/88235387
tagged with: python
has title: Understanding the flow of this "forked" script
accepted answer: http://stackoverflow.com/a/50613511

http://stackoverflow.com/q/50619062
tagged with: python
has body: So I have a dynamic library file named "libxlearn_api.dylib". I can load this library from within python code by lib = ctypes.cdll.LoadLibrary(/path/to/lib) I can also see what functions are defined in the above library by dir(lib). But, this just gives the list of names of the functions in it. I need to view the description/definition of these functions(how they are written/implemented, i.e the actual code.) How can I do this?
tagged with: shared-libraries
has comment: http://stackoverflow.com/comment/88248264
upvote count: 3
has comment: http://stackoverflow.com/comment/88249084
linked to: http://stackoverflow.com/q/4506121
tagged with: dylib
downvote count: 1
has comment: http://stackoverflow.com/comment/88247922
type: Question
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50619142
has comment: http://stackoverflow.com/comment/88247814
tagged with: http://stackoverflow.com/tag/c
accepted answer: http://stackoverflow.com/a/50619142
has title: How to view definition of functions of a dynamic library file (.dylib)?
answer count: 1
has comment: http://stackoverflow.com/comment/88248063
favorite count: 0

http://stackoverflow.com/comment/88300170
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50644641
type: QuestionComment
has text: Sorry my point wasn't clear : django settings are to be considered read-only during the process execution. Of course you have to edit the settings files every now and then - those are settings, that's what they are for - but not during process execution.

http://stackoverflow.com/q/50689599
answer count: 1
has comment: http://stackoverflow.com/comment/88388953
favorite count: 0
has answer: http://stackoverflow.com/a/50689701
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: django
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50689701
tagged with: django-models
has body: I am working on a website made in Django and i want to implement a facebook type (or any social media type) like button. I have a user table, and a post table, and i want users to be able to like the posts. I am confused about some particular things : How can I bind user info with likes so that one user can like only one time? My current approach is: I am thinking of creating a new field in post table, say post_likes, which have list of users who currently like the post. Then, before rendering the 'post' template, i have to loop over all the users (in field post_likes) to check if the request.user likes the post or not (in views.py), and send that data to template (to change the ui of like button to liked), but this approach seems very naive to me, also slow. What could be the better approaches?
has title: Implement a facebook type simpler 'like' feature in backend
downvote count: 0

http://stackoverflow.com/a/50598390
upvote count: 0
score: -1
answers question: http://stackoverflow.com/q/50594600
type: Answer
has body: You are supposed to use manage.py, not django-admin.py.
downvote count: 1

http://stackoverflow.com/a/50641763
type: AcceptedAnswer
has body: I found a solution myself using a metaclass: class M(type): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.d = {} class A(metaclass=M): pass Then one can create subclasses of A which all have their own d attribute: class B(A): pass B.d is A.d False
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50639137
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50639137

http://stackoverflow.com/q/50580002
upvote count: 4
has comment: http://stackoverflow.com/comment/88169192
type: AnsweredQuestion
score: 3
tagged with: list
has answer: http://stackoverflow.com/a/50580066
accepted answer: http://stackoverflow.com/a/50580066
has title: What does a backslash mean in a string literal?
type: Question
has body: I made a list of strings like this: >>> example = ["\0","\1","\2","\3","\4","\5","\6","\7","\8","\9","\10","\11"] But if I try to print it, I get a very different looking result: >>> print(example) ['\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\\8', '\\9', '\x08', '\t'] Why does this happen? Does the \ character have some special meaning here?
has comment: http://stackoverflow.com/comment/88169193
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python

http://stackoverflow.com/q/50669450
tagged with: list
score: 0
has body: I'm new at Python, and I'm trying to pull a list of artists and songs from Billboard's Hot 100 charts. I'm getting newline characters in my list of artists. How can I remove them without messing up the pairing and appearance of the list? What I have: from lxml import html import requests page = requests.get('https://www.billboard.com/charts/hot-100') tree = html.fromstring(page.content) songs = tree.xpath('//h2[@class="chart-row__song"]/text()') artists = tree.xpath('//a[@class="chart-row__artist"]/text()') pairedlist = [list(pair) for pair in zip(artists, songs)] for item in pairedlist: print (item) What I get (sample): ['\nDrake\n', 'Nice For What'] ['\nChildish Gambino\n', 'This Is America'] ['\nDrake\n', "God's Plan"] ['\nElla Mai\n', 'Psycho'] ['\nAriana Grande\n', 'The Middle'] ['\nBTS\n', 'Yes Indeed'] ['\nCamila Cabello\n', 'Meant To Be'] ['\nEd Sheeran\n', "Boo'd Up"] ['\nCardi B\n', 'No Tears Left To Cry'] ['\nImagine Dragons\n', 'Fake Love'] ['\nShawn Mendes\n', 'Friends'] ['\nKane Brown\n', 'Look Alive'] ['\nRich The Kid\n', 'Never Be The Same'] ['\nMaroon 5\n', 'Walk It Talk It'] ['\nNicki Minaj\n', 'Perfect'] ['\nPost Malone\n', 'Be Careful'] ['\nThe Weeknd\n', 'Whatever It Takes']
has answer: http://stackoverflow.com/a/50669476
has comment: http://stackoverflow.com/comment/88348811
type: Question
has title: Python removing newline characters from beginning and ending of each item in a list
has comment: http://stackoverflow.com/comment/88348854
linked to: http://stackoverflow.com/q/7984169
has comment: http://stackoverflow.com/comment/88348839
answer count: 1
duplicate of: http://stackoverflow.com/q/7984169
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50547023
tagged with: edx
has title: python guess my number exercise marked wrong on edX
has body: The program works as follows: you (the user) thinks of an integer between 0 (inclusive) and 100 (not inclusive). The computer makes guesses, and you give it input - is its guess too high or too low? Using bisection search, the computer will guess the user's secret number! My code: guess number using bisection Ask for an input of number from the user high = 100 low = 0 correct = False response = "" user_number = input("Please think of a number between 0 and 100!") while (response != "c"): guess = int((high + low)/2) print("Is your secret number", guess, "?") response = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly") if not (response == "h" or response == "c" or response == "l"): print("Sorry, I did not understand your input.") elif (response is "h"): high = guess elif (response is "l"): low = guess print ("Game over. Your secret number was:", guess) Currently the EdX website is marking my answer as incorrect, I checked the out put by trying input numbers such as 83, 8,42 it came out correctly as the edX website code's showing. Can someone give me some suggestions on where my code is flawed? Thank you.
answer count: 0
score: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/88104796
has comment: http://stackoverflow.com/comment/88104743
tagged with: python

http://stackoverflow.com/q/50667413
tagged with: pip
upvote count: 1
type: Question
has body: I'm trying to pip install python-binance but cannot do it :/.. I looked for similar errors before asking and I found some but when I do what people say (for exemple pip install setuptools --upgrade returns an error), it still doesn't work. Can somebody help me please ? Here is what the terminal out put : AirdeGuillaume:~ guigui$ pip install python-binance Collecting python-binance Using cached https://files.pythonhosted.org/packages/da/fe/c923be9df86a7d540f31e1292990a14f77652371f1800741129e9fa3e9e4/python_binance-0.6.9-py2.py3-none-any.whl Collecting cryptography (from python-binance) Using cached https://files.pythonhosted.org/packages/58/c1/23bea66007d4be75ce02056fac665f9a207535e89fb3c7931420fa4a5f57/cryptography-2.2.2-cp27-cp27m-macosx_10_6_intel.whl Requirement already satisfied: six in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from python-binance) (1.4.1) Requirement already satisfied: urllib3 in /Library/Python/2.7/site-packages (from python-binance) (1.22) Collecting autobahn (from python-binance) Using cached https://files.pythonhosted.org/packages/71/0c/af6e79f0cc23668454f4a73ec10b96bdb5b7f172509179da4fc92bce4142/autobahn-18.5.2-py2.py3-none-any.whl Collecting Twisted (from python-binance) Using cached https://files.pythonhosted.org/packages/12/2a/e9e4fb2e6b2f7a75577e0614926819a472934b0b85f205ba5d5d2add54d0/Twisted-18.4.0.tar.bz2 Requirement already satisfied: chardet in /Library/Python/2.7/site-packages (from python-binance) (3.0.4) Requirement already satisfied: pyOpenSSL in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from python-binance) (0.13.1) Collecting dateparser (from python-binance) Using cached https://files.pythonhosted.org/packages/ac/9e/1aa87c0c59f9731820bfd20a8b148d97b315530c2c92d1fb300328c8c42f/dateparser-0.7.0-py2.py3-none-any.whl Requirement already satisfied: requests in /Library/Python/2.7/site-packages (from python-binance) (2.18.4) Collecting service-identity (from pytho…
has comment: http://stackoverflow.com/comment/88345082
linked to: http://stackoverflow.com/q/19629685
has title: Error pip install python-binance (Command "/usr/bin/python -u -c "import setuptools...)
has comment: http://stackoverflow.com/comment/88345254
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88352575
type: UnansweredQuestion
tagged with: python
tagged with: binance
has answer: http://stackoverflow.com/a/50668833
has comment: http://stackoverflow.com/comment/88344991
score: 1
tagged with: setuptools

http://stackoverflow.com/q/50669907
has answer: http://stackoverflow.com/a/50675541
type: AnsweredQuestion
score: 3
upvote count: 3
accepted answer: http://stackoverflow.com/a/50675541
type: Question
tagged with: ctypes
has body: The Python Library Reference, Release 3.6.5, paragraph 16.16 ctypes - A foreign function library for Python, gives this example, demonstrating output parameters, in section Function prototypes: The win32 GetWindowRect function: WINUSERAPI BOOL WINAPI GetWindowRect(HWND hWnd, LPCRECT lprect); The ctypes wrapper: from ctypes import POINTER, WINFUNCTYPE, windll, WinError from ctypes.wintypes import BOOL, HWND, RECT prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT)) paramflags = (1, 'hwnd'), (2, 'lprect') GetWindowRect = prototype(('GetWindowRect', windll.user32), paramflags) Now, how do I actually use GetWindowRect? Trying from ctypes import byref, cast r = RECT() h = cast(65552, HWND) # _65552_ is the return value of _GetDesktopWindow_ on my system result = GetWindowRect([h, byref(r)]) returns ctypes.ArgumentError: argument 1: &lt;class 'TypeError'&gt;: wrong type.
answer count: 1
downvote count: 0
favorite count: 0
has title: How to use ctypes' errcheck?
tagged with: python

http://stackoverflow.com/comment/88385104
has text: Do you have a config script where the location of python.h could be specified as an option?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50687541
type: AnswerComment

http://stackoverflow.com/comment/88110751
type: Comment
type: QuestionComment
score: 0
has text: @coldspeed If everything is True then return 1 if one value doesn't match my condition then return 0 (False)
comment on: http://stackoverflow.com/q/50549910

http://stackoverflow.com/q/50553261
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50553376
has title: Changeable variable in a list
has answer: http://stackoverflow.com/a/50553386
tagged with: python
type: AnsweredQuestion
tagged with: blackjack
downvote count: 1
type: Question
score: -1
has body: I'm trying to create a simple game of Pontoon (similar to blackjack) and I have made a list of cards as a deck. My current build of the game works if I give ACE a value of 1 or 14, but I need it to have both values so if a hand goes over 21, ACE returns to 1. deck = [ACE, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, ACE, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, ACE, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, ACE, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] So the basicly the card picking happens like this: while True: hand = [] hand.extend(random.sample(deck, 1)) print(hand) while True: hit = input("new card? (k/e)") if hit == "k": hand.extend(random.sample(deck, 1)) print("") print("HAND:") print(hand) a = sum(hand) print("") print("SUM:") print(a) if a &gt; 21: print("") print("OVER") break elif a == 21: print("") print("Pontoon") break else: continue I have tried to make ACE as a function, but random.sample doesn't work with that def ACE(): if a &gt; 21: A = 1 else: A = 14 return int(A) So how do I get ACE to work as a 1 and a 14?
accepted answer: http://stackoverflow.com/a/50553376
answer count: 2
upvote count: 0
possible better answer: http://stackoverflow.com/a/50553386

http://stackoverflow.com/q/50637158
favorite count: 0
has answer: http://stackoverflow.com/a/50637271
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88284489
tagged with: python
has body: This function generates a list of 10 random numbers. I need to modify this function to select and print the smallest number from the randomly generated list Please help, I am having a very hard time with it: import random my_randoms=[] for i in range (10): my_randoms.append(random.randrange(1,101,1)) print (my_randoms)
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50637935
score: 0
answer count: 3
has title: Python write a function that selects the smallest number from a list of 10 randomly generated numbers
has answer: http://stackoverflow.com/a/50637240

http://stackoverflow.com/q/50641637
linked to: http://stackoverflow.com/q/50622180
tagged with: python
type: AnsweredQuestion
has title: Identify colour space of any image if icc_profile is empty (PIL)
tagged with: python-imaging-library
has answer: http://stackoverflow.com/a/50656128
tagged with: image-processing
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/50656128
has body: I have a huge amount of images and a lot of them have empty icc_profile when I read it using PIL. The way I am checking icc profile is: from PIL import Image img = Image.open('image.jpg') icc = img.info.get('icc_profile', '') Is there a way to identify colour space of an image (preferably using PIL) even if icc_profile is empty?
score: 4
tagged with: image
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/88328271
score: 0
type: Comment
type: QuestionComment
has text: Hey, would you also mention weather you are using windows, linux or macos?
comment on: http://stackoverflow.com/q/50659044

http://stackoverflow.com/q/50592137
has comment: http://stackoverflow.com/comment/88193549
score: -2
has title: python: create a new 1D list with values from 2 different lists:
linked to: http://stackoverflow.com/q/252703
duplicate of: http://stackoverflow.com/q/1720421
has comment: http://stackoverflow.com/comment/88193533
possible better answer: http://stackoverflow.com/a/50592415
has comment: http://stackoverflow.com/comment/88193587
favorite count: 0
has comment: http://stackoverflow.com/comment/88193670
accepted answer: http://stackoverflow.com/a/50592247
has body: Below is a simple example. What I want is to create a new list that contain the values [0,1,2,3,4] by merging list1 and list 2 together. But the code below doesn't work and I am not really sure how I should solve it. list1 = [3] list2 = [i for i in range(3)] newlist = list1.append(list2)
has comment: http://stackoverflow.com/comment/88193618
linked to: http://stackoverflow.com/q/1720421
tagged with: python
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/50592415
has answer: http://stackoverflow.com/a/50592247
type: Question
answer count: 2
downvote count: 2

http://stackoverflow.com/comment/88256041
has text: did you try saving it as macro enabled ..with .xlsm extension
comment on: http://stackoverflow.com/q/50622888
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50627023
has body: Consider this line of code: b1_oval = bottom_frame.create_oval( 25,180,65,205, fill='') In the above code, create_oval is returning an integer identifier which represents the object that was created. You are storing this in a variable named b1_oval. Now consider this code: for j in ovalLONG: i_oval = i_oval + 1 w_oval = str('b'+str(i_oval)+'_oval') # Not flying Wilbur if i == j: bottom_frame.itemconfigure(w_oval, fill='goldenrod3') First, you are creating a string that looks like "b1_oval". You are storing this string in a variable named w_oval. In other words, it's no different than if you did w_oval = "b1_oval". When you call itemconfigure(w_oval, ...) it is identical to calling `itemconfigure("b1_oval", ...). That first parameter is taken by the canvas to be a tag or an id. Since it's not an integer it is treated as a tag. You have not created any objects on the canvas with the tag `"b1_oval", so nothing has changed. Just to be clear: tags and variable names are two completely different things. You have one of two options: either give each oval a tag that matches that pattern (via the tag option), or store the ids in a way that you can use in the loop. The second of those solutions is the best and easiest in my opinion. Instead of creating a bunch of variables that have numbers in the name, store the ids in a list or dictionary. Then it's just a simple lookup, without having to compute the name of a variable. For example: ovals = [] ovals.append(bottom_frame.create_oval(...)) ovals.append(bottom_frame.create_oval(...)) ... for j in ovalLONG: if i == j: bottom_frame.itemconfigure(ovals[i], ...) I doubt the above is exactly what you want, because I don't know where you're computing i -- it's not in the code you provided. Still, the point is that you save the object ids in a list rather than trying to compute a variable name. The main disadvantage to using lists is that you can't control the indexes. Lists always start counting at zero, so the first oval you create …
type: Answer
answers question: http://stackoverflow.com/q/50614498
score: 0

http://stackoverflow.com/q/50556514
score: 1
has body: I have some issues with styling a QListWidget. I've been looking for how to set the style to a ScrollBar within a QListWidget, but I can't find the answer.
downvote count: 2
tagged with: pyqt
answer count: 1
favorite count: 0
upvote count: 3
has title: How to set the style to a ScrollBar within a QListWidget?
tagged with: python
has answer: http://stackoverflow.com/a/50556757
type: Question
tagged with: qt
accepted answer: http://stackoverflow.com/a/50556757
type: AnsweredQuestion
tagged with: qtstylesheets

http://stackoverflow.com/q/50650521
answer count: 1
has body: Trying to figure this out, because there is an inconsistency between when I run the code from Pycharm and from terminal. Pycharm add automatically the current working directory; so if I add a module that is contained in my CWD, that is not in Pythonpath, it works just fine. But when running from terminal, Python does complain, because my import statements refer to modules that are not reachable, because the CWD is not added to PYTHONPATH (I did verify this printing out the content of the variable, while running from Pycharm and from Terminal). So at this point I am assuming that in my startup code, I need to add to Pythonpath the current directory, or this is not correct? I have no way to tell where the final user may put my code in; I just assume that the whole directory containing all my different modules, is located in a specific place. To be more specific, this is where I am at: my CWD when I run from Pycharm is /apps/myapp/logic/, I run the script after cd in that directory, and I call the script with ./myscript.py The script has the #!/usr/bin/python3 line as first line, instead of running it with python3 -m myscript.py The error I get, is when loading a module that is either in the same directory of my script (/apps/myapp/logic/) or one level above (/apps/myapp/); sadly the module load happen before my __main__ is running; so I can't add to sys.path the current directory from which the script run. All these issues are not happening if I just run the script from Pycharm
downvote count: 0
has comment: http://stackoverflow.com/comment/88313339
has comment: http://stackoverflow.com/comment/88314272
tagged with: python
has comment: http://stackoverflow.com/comment/88314760
favorite count: 0
has title: Pycharm run the code adding the current working dir to PYTHONPATH
has comment: http://stackoverflow.com/comment/88312994
has comment: http://stackoverflow.com/comment/88312337
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/88314331
has comment: http://stackoverflow.com/comment/88314116
has comment: http://stackoverflow.com/comment/88314070
score: 1
type: Question
has answer: http://stackoverflow.com/a/50652494
has comment: http://stackoverflow.com/comment/88313032
has comment: http://stackoverflow.com/comment/88312249
has comment: http://stackoverflow.com/comment/88312399

http://stackoverflow.com/a/50665057
score: 0
has body: def make_mask(labels): mask = tf.clip_by_value(labels, - 1, 0) mask = tf.ones_like(mask) - tf.abs(mask) return mask def my_cross_entropy(y_true, y_pred): mask = make_mask(y_true) log_val = tf.clip_by_value(y_pred, 1e-7, 1 - 1e-7) hx_0 = tf.log(log_val) hx_1 = tf.log(1 - log_val) cross_entropy = (y_true * hx_0 + (1 - y_true) * hx_1) * mask return tf.reduce_mean(-tf.reduce_sum(cross_entropy, reduction_indices=[1])) this is what I finally came up with to not penalize the segmentation model on unlabeled parts
type: Answer
answers question: http://stackoverflow.com/q/50664699

http://stackoverflow.com/a/50562414
has body: You want $map: db.sample.aggregate([ {'$lookup': { 'from': 'locators', 'localField': "locator", 'foreignField': "_id", 'as': "metalocator" }}, { '$addFields': { 'metalocator': { '$map': { 'input': '$metalocator', 'in': { 'section': '$$this.section', 'cabinet': '$$this.cabinet' } } } }} ]) That is what you use to "re-map" the contents of an array, which is really what you are asking. It's usage is much the same as the operator of much the same name in python as well as many other languages. If you have MongoDB 3.6, you alternately can use a different $lookup syntax where you can actually "choose" which fields to return from there: db.sample.aggregate([ {'$lookup': { 'from': 'locators', 'let': { 'locator': '$locator' }, 'pipeline': [ { '$match': { '$expr': { '$eq': [ '$_id', '$$locator' ] } }}, { '$project': { 'section': 1, 'cabinet': 1, '_id': 0 } } ], 'as': "metalocator" }} ]) That would actually be more efficient where you can do it, since the data is simply not even returned into the target array and you don't need to "re-map" the array in order to discard the other fields. For the record, what you "missed" was the $first operator: db.sample.aggregate([ { "$lookup": { "from": "locators", "localField": "locator", "foreignField": "_id", "as": "metalocator" }}, { "$unwind": '$metalocator'}, { "$group": { "_id": "$_id", "locator": { "$first": "$locator" }, "record": { "$first": "$record" }, "metalocator": { "$push": { "section": "$metalocator.section", "cabinet": "$metalocator.cabinet" } } }} ]) But using $unwind and $group is not necessary here as the other methods shown above are far more efficient.
score: 9
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50562160
answers question: http://stackoverflow.com/q/50562160
upvote count: 9

regex
tags question: http://stackoverflow.com/q/50658758
tags question: http://stackoverflow.com/q/50675671
tags question: http://stackoverflow.com/q/50567434
tags question: http://stackoverflow.com/q/50674031
tags question: http://stackoverflow.com/q/50655446
tags question: http://stackoverflow.com/q/50608513
tags question: http://stackoverflow.com/q/50602962
tags question: http://stackoverflow.com/q/50692733
tags question: http://stackoverflow.com/q/50565514
tags question: http://stackoverflow.com/q/50645204
tags question: http://stackoverflow.com/q/50659268
tags question: http://stackoverflow.com/q/50586697
tags question: http://stackoverflow.com/q/50658722
tags question: http://stackoverflow.com/q/50568513
tags question: http://stackoverflow.com/q/50690173
tag name: regex
tags question: http://stackoverflow.com/q/50549854
tags question: http://stackoverflow.com/q/50674757
tags question: http://stackoverflow.com/q/50652473
tags question: http://stackoverflow.com/q/50570910
tags question: http://stackoverflow.com/q/50627686
tags question: http://stackoverflow.com/q/50569760
tags question: http://stackoverflow.com/q/50633198
tags question: http://stackoverflow.com/q/50617691
tags question: http://stackoverflow.com/q/50614223
tags question: http://stackoverflow.com/q/50614263
tags question: http://stackoverflow.com/q/50681795
tags question: http://stackoverflow.com/q/50545326
tags question: http://stackoverflow.com/q/50651146
tags question: http://stackoverflow.com/q/50547280
tags question: http://stackoverflow.com/q/50577761
tags question: http://stackoverflow.com/q/50609758
tags question: http://stackoverflow.com/q/50630388
tags question: http://stackoverflow.com/q/50545172
tags question: http://stackoverflow.com/q/50587373
tags question: http://stackoverflow.com/q/50625699
tags question: http://stackoverflow.com/q/50553585
tags question: http://stackoverflow.com/q/50672212
tags question: http://stackoverflow.com/q/50559811
tags question: http://stackoverflow.com/q/50634955
tags question: http://stackoverflow.com/q/50689067
tags question: http://stackoverflow.com/q/50556159
tags question: http://stackoverflow.com/q/50562428
tags question: http://stackoverflow.com/q/50586304
tags question: http://stackoverflow.com/q/50629480
tags question: http://stackoverflow.com/q/50559652
tags question: http://stackoverflow.com/q/50638264
tags question: http://stackoverflow.com/q/50679145
tags question: http://stackoverflow.com/q/50683833
tags question: http://stackoverflow.com/q/50644652
tags question: http://stackoverflow.com/q/50673360
tags question: http://stackoverflow.com/q/50689935
tags question: http://stackoverflow.com/q/50587886
tags question: http://stackoverflow.com/q/50546899
tags question: http://stackoverflow.com/q/50641495
tags question: http://stackoverflow.com/q/50593119
tags question: http://stackoverflow.com/q/50628396
tags question: http://stackoverflow.com/q/50621172
tags question: http://stackoverflow.com/q/50636902
tags question: http://stackoverflow.com/q/50559609
tags question: http://stackoverflow.com/q/50555464
tags question: http://stackoverflow.com/q/50565419
tags question: http://stackoverflow.com/q/50612296
tags question: http://stackoverflow.com/q/50649640
tags question: http://stackoverflow.com/q/50542645
tags question: http://stackoverflow.com/q/50685077
tags question: http://stackoverflow.com/q/50566855
tags question: http://stackoverflow.com/q/50571153
tags question: http://stackoverflow.com/q/50663898
tags question: http://stackoverflow.com/q/50648114
tags question: http://stackoverflow.com/q/50549742
tags question: http://stackoverflow.com/q/50570514
tags question: http://stackoverflow.com/q/50598674
tags question: http://stackoverflow.com/q/50608309
tags question: http://stackoverflow.com/q/50672361
tags question: http://stackoverflow.com/q/50577459
tags question: http://stackoverflow.com/q/50664769
tags question: http://stackoverflow.com/q/50581171
tags question: http://stackoverflow.com/q/50635699
tags question: http://stackoverflow.com/q/50622720

http://stackoverflow.com/a/50666191
score: 8
accepted answer of: http://stackoverflow.com/q/50665866
has comment: http://stackoverflow.com/comment/88343264
answers question: http://stackoverflow.com/q/50665866
has comment: http://stackoverflow.com/comment/88350208
has body: Turn the dict into a sorted list and then build a new dict without the words you want to remove: import itertools to_remove = {'apple', 'banana'} # Step 1: sort the words ordered_words = [None] * len(words) for word, index in words.items(): ordered_words[index] = word # ordered_words: ['apple', 'orange', 'banana', 'pear'] # Step 2: Remove unwanted words and create a new dict counter = itertools.count() words = {word: next(counter) for word in ordered_words if word not in to_remove} # result: {'orange': 0, 'pear': 1} This has a runtime of O(n) because manually ordering the list with indexing operations is a linear operation, as opposed to sorted which would be O(n log n). See also the documentation for itertools.count and next.
type: AcceptedAnswer
downvote count: 0
upvote count: 8
type: Answer

http://stackoverflow.com/comment/88306223
type: Comment
comment on: http://stackoverflow.com/a/50632920
type: AnswerComment
score: 0
has text: yep it's a useful module; the issue is it takes an escape character and a quoting character to escape/quote any quotes or commas contained in your columns already, and you can't set both to be the empty string

http://stackoverflow.com/comment/88119121
type: QuestionComment
comment on: http://stackoverflow.com/q/50554152
has text: `print( odd, "-", num,"=",odd-num)` or `print(f"{odd}-{num}={odd-num}")` or `print('{}-{}={}'.format(odd,num,odd-num))` or the outdated % formatting one... based back in pre-python-3
score: 0
type: Comment

http://stackoverflow.com/q/50672980
has comment: http://stackoverflow.com/comment/88355734
tagged with: pickle
tagged with: python
has comment: http://stackoverflow.com/comment/88355780
has body: I am creating a program that works as a database that stores students, as objects. Each object (student) has three attributes: name, grade, and average. I am trying to incorporate a binary search so that the user can search for an average. If the average is found in one of the object's attributes, then the program should display the object. Right now I am trying to get the binary search to work; if I search for an average that is stored in an even-index, then it works, however it doesn't work for any odd-indexes. Does anyone know why this is happening? Also, I am trying to display the object that contains the average that is being searched for, but so far I have only been able to display the index location of the object that contains the searched average. Any help with displaying the object would be appreciated! My program is as follows: import pickle class Student(): def __init__(self,nam,grd,avg): self.name = nam self.grade = grd self.average = avg def get_details(self): print(self.name, self.grade, self.average) def unpickle_database(filename): with open(filename, 'rb') as f: while True: try: yield pickle.load(f) except EOFError: break def display_database(): print("\nName: Grade: Average: ") for student in unpickle_database('student_data.pkl'): property_list = [student.name, student.grade, student.average] print(''.join([v.ljust(20,' ') for v in property_list])) def store_averages_in_list(): students = list(unpickle_database('student_data.pkl')) students_average = [] for student in students: students_average.append(int(student.average)) return students_average def bin_search(x, type): my_list = list(sorted(store_students_in_list(), key=attrgetter(type), reverse=False)) bottom = 0 top = len(my_list)-1 found = False location = -1 while (bottom &lt;= top) and not(found): middle = int((bottom + top)/2) if (my_list[middle] == x): location = middle found = True elif (my_list[middle] &lt; x): bottom = middle + 1 else: top = middle -1 return location while True: user_in…
has comment: http://stackoverflow.com/comment/88355710
answer count: 0
has comment: http://stackoverflow.com/comment/88355699
type: Question
tagged with: object
has comment: http://stackoverflow.com/comment/88355764
tagged with: binary-search
score: 0
has title: How to use binary search to find a pickle object attribute
has comment: http://stackoverflow.com/comment/88355806
type: UnansweredQuestion

http://stackoverflow.com/comment/104616269
comment on: http://stackoverflow.com/a/59199034
score: 0
type: Comment
has text: in that case, you have the choise of editing how jango gets data, by direclty injecting sql code. like done in the django doc : https://docs.djangoproject.com/en/2.2/topics/db/sql/#mapping-query-fields-to-model-fields
type: AnswerComment

http://stackoverflow.com/q/50656955
score: 5
has comment: http://stackoverflow.com/comment/88325444
has comment: http://stackoverflow.com/comment/88324145
upvote count: 6
has comment: http://stackoverflow.com/comment/88324576
has comment: http://stackoverflow.com/comment/88324254
has answer: http://stackoverflow.com/a/51854826
tagged with: google-maps-api-3
tagged with: google-distancematrix-api
has comment: http://stackoverflow.com/comment/88324610
tagged with: o-d-matrix
answer count: 1
has title: Google Distance Matrix API: How to specify origin-destination pairs?
has comment: http://stackoverflow.com/comment/88324423
has comment: http://stackoverflow.com/comment/88325412
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88324216
has body: I am using the Python client library for Google Maps API (Github link). I would like to get the duration_in_traffic figures for the following trips: Address1 to Address2 Address2 to Address1 Address1 to Address3 Address3 to Address1 But the syntax of the Google Distance Matrix API (documentation) is problematic in its presumptuousness. It assumes that the user wants data for all conceivable pairings of origin and destination addresses. The issue is that the following code (source)... origins = [Address1, Address2, Address3] destinations = [Address1, Address2, Address3] matrix = client.distance_matrix(origins, destinations, mode="driving", language="en", units="imperial", departure_time=now, traffic_model="best_guess") produces nine results (that is, every possible combination of origin-destination pairings), when I only need the previously-stated four. I realize that I can parse these results to extract only the four durations that I need, but I don't want to needlessly double the execution time of my script by forcing it to download data that I do not want. I also realize that I can send 4 separate requests to get just the durations that I want (that is, one pairing per request), but I am trying not to surpass the quota for my free, non-premium Distance Matrix API account. So, is it possible to specify the origin-destination pairings within the same request?
downvote count: 1
has comment: http://stackoverflow.com/comment/88324801
type: Question
has comment: http://stackoverflow.com/comment/88324652

http://stackoverflow.com/a/50975064
downvote count: 2
score: -2
has comment: http://stackoverflow.com/comment/118803072
upvote count: 0
accepted answer of: http://stackoverflow.com/q/50678758
type: AcceptedAnswer
has body: Correctly, I checked this. If you use CACHALOT_UNCACHABLE_TABLES setting this variable with the table names that tables doesn't cache with Cachalot.
type: Answer
has comment: http://stackoverflow.com/comment/118833297
answers question: http://stackoverflow.com/q/50678758

http://stackoverflow.com/comment/88112000
type: AnswerComment
type: Comment
has text: Very clever @peter , and for my lack of sleep brain, this 'simple helper' function is liquid Adderall, thanks. One thing, the resulting array still need to have the `first_name` key/value ... Currently it spits out the `[{'email': 'new@email.com'},]` only. Possible?
comment on: http://stackoverflow.com/a/50550507
score: 0

http://stackoverflow.com/a/50544184
has comment: http://stackoverflow.com/comment/88142622
has comment: http://stackoverflow.com/comment/88141965
has body: import keras.backend as K a = K.variable([0.5]) l1 = Lambda(lambda x: x * (1-a))(l1) l2 = Lambda(lambda x: x * a)(l2) l3 = keras.layers.Add()([l1,l2]) Change a with K.set_value(a,[newValue]) If you have dimensions mismatch (which I don't see in Keras 2.1.0 with tensorflow 1.4.0, and very very probably also works in newer versions), you can force a 4D a that matches your 4D data: a = K.variable([[[[0.5]]]])
score: 0
has comment: http://stackoverflow.com/comment/88165898
answers question: http://stackoverflow.com/q/50542371
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88175156
has comment: http://stackoverflow.com/comment/88143032
accepted answer of: http://stackoverflow.com/q/50542371
has comment: http://stackoverflow.com/comment/88101920
has comment: http://stackoverflow.com/comment/88143959
type: Answer
has comment: http://stackoverflow.com/comment/88101385

http://stackoverflow.com/q/50651466
has title: Access kivy widgets from Python code using dynamic IDs
accepted answer: http://stackoverflow.com/a/50651644
tagged with: python
type: AnsweredQuestion
tagged with: widget
score: 1
has answer: http://stackoverflow.com/a/50651644
type: Question
downvote count: 0
answer count: 1
has body: I have a kv file with several widgets, their IDs being numbers (in string representation). Let's say it's numbers from 1 - 10. Can I somehow access those widgets from Python with a loop by using their ID in the method call (which is an integer in string form) instead of using the ID name explicitly? For example (as illustration, it doesn't really work), I would like to use something like: for i in range (1, 11) self.root.ids.str(i).text = str(i*5) instead of: self.root.ids.1.text = str(5) self.root.ids.2.text = str(10) self.root.ids.3.text = str(15) ... etc The reason is this list of widgets can grow large. Also the ranges (slices) I want to access can vary.
upvote count: 1
tagged with: kivy
favorite count: 0

recurly
tags question: http://stackoverflow.com/q/50593150
type: Tag
tag name: recurly

http://stackoverflow.com/comment/123038043
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50662773
has text: In my case, I got this error when Python could not find the image file at the path I had put. I corrected the path and it started working.

http://stackoverflow.com/comment/88185319
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50587752
has text: 99% sure this is the correct answer. Now I gotta figure out how to do it with my current code. Thanks

http://stackoverflow.com/q/50653870
has comment: http://stackoverflow.com/comment/88318163
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/88318149
has answer: http://stackoverflow.com/a/50653951
type: UnansweredQuestion
tagged with: python
has title: Error when adding a new column to pandas dataframe
has comment: http://stackoverflow.com/comment/88318159
has body: I am trying to modify .csv files in a folder. The files contain flight information from years 2011-2016. However, year information cannot be found in the values. I would like to solve this by using the filename of the .csv file which contains the year. I am adding a new 'year' column after reading it into a pandas dataframe. I will then export the modified file to a new .csv with only the year as its filename. However, I am encountering this error: ValueError:Length of values does not match length of index Code below for your reference. import pandas as pd import glob import re import os path = r'data_caap/' all_files = glob.glob(os.path.join(path, "*.csv")) for f in all_files: df = pd.read_csv(f) year= re.findall(r'\d{4}', f) #Error here df['year']=year #Error here df.to_csv(year)
type: Question
score: 0

recursion
type: Tag
tags question: http://stackoverflow.com/q/50587433
tags question: http://stackoverflow.com/q/50655768
tag name: recursion
tags question: http://stackoverflow.com/q/50676165
tags question: http://stackoverflow.com/q/50639090
tags question: http://stackoverflow.com/q/50633762
tags question: http://stackoverflow.com/q/50563372
tags question: http://stackoverflow.com/q/50615723
tags question: http://stackoverflow.com/q/50670669
tags question: http://stackoverflow.com/q/50574241
tags question: http://stackoverflow.com/q/50629277
tags question: http://stackoverflow.com/q/50546091
tags question: http://stackoverflow.com/q/50607128
tags question: http://stackoverflow.com/q/50635554
tags question: http://stackoverflow.com/q/50620304
tags question: http://stackoverflow.com/q/50594178
tags question: http://stackoverflow.com/q/50656519
tags question: http://stackoverflow.com/q/50593248
tags question: http://stackoverflow.com/q/50543093

http://stackoverflow.com/q/50585491
has title: Error using the feather format package
has answer: http://stackoverflow.com/a/51117211
has body: I am having trouble using the feather format to export data. I have installed the package using: conda install feather-format -c conda-forge however, when I use pd.to_feather() I get an error telling me to install the package (which is already installed). ImportError: the feather-format library is not installed you can install via conda conda install feather-format -c conda-forge or via pip pip install -U feather-format I also tried using pyarrow, but I am getting another error, saying ImportError: cannot import name 'cpu_count' Can you please tell what am I doing wrong? Thank you
tagged with: python
has comment: http://stackoverflow.com/comment/88181316
type: UnansweredQuestion
upvote count: 3
score: 3
tagged with: feather
type: Question
has comment: http://stackoverflow.com/comment/88181686
tagged with: pandas
has comment: http://stackoverflow.com/comment/88185823
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/88200473
has text: @AGN Gazer thanks for the comment; then, what 's the solution in these situations?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50595072

http://stackoverflow.com/comment/88333832
comment on: http://stackoverflow.com/a/50661702
type: Comment
has text: Basically I am selecting an element with that contains class `price`. Look into this link: https://www.w3schools.com/cssref/css_selectors.asp
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88193515
score: 0
has text: Please add a line of a different length to your example. Which component varies in length?
comment on: http://stackoverflow.com/q/50592013
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50673733
type: Question
has title: Is there a way to use OCR (python or java + linux terminal possible) to operate in real time?
has comment: http://stackoverflow.com/comment/88394330
has body: I'm starting to work on a program with python (could switch to java no prob) that uses Optical character recognition, but the only obvious method that this utilizes is importing image files, is there a way to instead have it running in real time on certain parts of the screen or is a cropping/snipping tool as good as I can hope for? Also, Is there a tool, library, language or approach I could use for something like this. Any help appreciated.
tagged with: inputstream
score: 0
has comment: http://stackoverflow.com/comment/88357355
tagged with: image-recognition
type: UnansweredQuestion
tagged with: input
tagged with: python
has comment: http://stackoverflow.com/comment/88390703
answer count: 0
tagged with: java

http://stackoverflow.com/a/50597549
answers question: http://stackoverflow.com/q/50596456
type: Answer
has body: see you have alert , sizerange,sizenumber, then after it click on the add to bag button and colour i kept defaut black colour 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 import time browser = webdriver.Chrome("/Users/mymac/Documents/AutoFill/chromedriver") browser.maximize_window() selectsizerange = input("Enter SIZE RANGE") sizenumber = input("ENTER SIZE NUMBER") browser.get("https://www.jcpenney.com/p/a-n-a-skinny-denim-ankle-crop-jeans/ppr5007199315?pTmplType=regular&amp;catId=cat100250096&amp;deptId=dept20000013&amp;urlState=/g/womens-jeans/N-bwo3xD1nopgw&amp;badge=onlyatjcp") time.sleep(5) browser.switch_to_active_element() browser.find_element_by_id('closeButton').click() time.sleep(3) browser.find_element_by_id('SIZE_RANGE').send_keys(selectsizerange) browser.find_element_by_id('SIZE').send_keys(sizenumber) browser.find_element_by_css_selector("ul#COLOR li:nth-child(1) &gt; img").click() time.sleep(3) browser.find_element_by_css_selector("div.pp__cta__all &gt; div:nth-child(1) &gt; button").click()
score: 0
has comment: http://stackoverflow.com/comment/88204419

http://stackoverflow.com/a/50554923
has body: This solution is not efficient by any means, but I had fun thinking about it, so wrote it down. Basically, you ravel the array, and create an array of row labels, and an array of indices. You shuffle the index array, and index the original and row label arrays with that. Then you apply a stable argsort to the row labels to gather the data into rows. Apply that index and reshape and viola, data shuffled independently by rows: import numpy as np r, c = 3, 4 # x.shape x = np.arange(12) + 1 # Already raveled inds = np.arange(x.size) rows = np.repeat(np.arange(r).reshape(-1, 1), c, axis=1).ravel() np.random.shuffle(inds) x = x[inds] rows = rows[inds] inds = np.argsort(rows, kind='mergesort') x = x[inds].reshape(r, c) Here is an IDEOne Link
type: Answer
answers question: http://stackoverflow.com/q/50554272
score: 3
downvote count: 0
upvote count: 3

http://stackoverflow.com/q/50585246
tagged with: python
has answer: http://stackoverflow.com/a/54357929
has comment: http://stackoverflow.com/comment/88180720
has title: pip install . creates only the dist-info not the package
has answer: http://stackoverflow.com/a/74660555
has answer: http://stackoverflow.com/a/77764280
tagged with: setuptools
tagged with: pip
has body: I am trying to make a python package which I want to install using pip install . locally. The package name is listed in pip freeze but import &lt;package&gt; results in an error No module named &lt;package&gt;. Also the site-packages folder does only contain a dist-info folder. find_packages() is able to find packages. What am I missing? import io import os import sys from shutil import rmtree from setuptools import find_packages, setup, Command # Package meta-data. NAME = '&lt;package&gt;' DESCRIPTION = 'description' URL = '' EMAIL = 'email' AUTHOR = 'name' # What packages are required for this module to be executed? REQUIRED = [ # 'requests', 'maya', 'records', ] # The rest you shouldn't have to touch too much :) # ------------------------------------------------ # Except, perhaps the License and Trove Classifiers! # If you do change the License, remember to change the Trove Classifier for that! here = os.path.abspath(os.path.dirname(__file__)) # Where the magic happens: setup( name=NAME, #version=about['__version__'], description=DESCRIPTION, # long_description=long_description, author=AUTHOR, author_email=EMAIL, url=URL, packages=find_packages(), # If your package is a single module, use this instead of 'packages': # py_modules=['mypackage'], # entry_points={ # 'console_scripts': ['mycli=mymodule:cli'], # }, install_requires=REQUIRED, include_package_data=True, license='MIT', classifiers=[ # Trove classifiers # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy' ], )
linked to: http://stackoverflow.com/q/62983756
has answer: http://stackoverflow.com/a/54170221
type: Question
has comment: http://stackoverflow.com/comment/88181286
score: 120
has answer: http://stackoverflow.com/a/68107843
upvote count: 120
downvote count: 0
answer count: 7
favorite count: 0
has answer: http://stackoverflow.com/a/73149171
has answer: http://stackoverflow.com/a/79405536
tagged with: setup.py
type: UnansweredQuestion
tagged with: package
has comment: http://stackoverflow.com/comment/95529673
has comment: http://stackoverflow.com/comment/90628125

http://stackoverflow.com/comment/88353139
type: QuestionComment
type: Comment
has text: if you want to vectorize you need numpy
comment on: http://stackoverflow.com/q/50671083
score: 0

http://stackoverflow.com/q/50591049
has comment: http://stackoverflow.com/comment/88229071
linked to: http://stackoverflow.com/q/190010
has comment: http://stackoverflow.com/comment/88192550
has comment: http://stackoverflow.com/comment/88192686
tagged with: python-multithreading
type: UnansweredQuestion
tagged with: nidaqmx
has comment: http://stackoverflow.com/comment/88191639
has comment: http://stackoverflow.com/comment/88193719
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/88192696
has comment: http://stackoverflow.com/comment/88220107
type: Question
has comment: http://stackoverflow.com/comment/88192131
has title: Continuous data acquisition with a PyQt GUI
has body: I am building an application where I acquire data continuously from a National Instruments device and do some real time processing on it. I am trying to hook the acquisition part to a PyQt GUI so that the user can start, stop and configure the data acquisition and see the data. I have one class for the data acquisition and one class for the GUI. I start the data acquisition process as a thread within the GUI: # data acquisition class class intensimetre(): #initialize the data acquisition def __init__(self,app=None,l1=None,l2=None,l3=None): #... #start the data acquisition def demarrer(self,fs=51200.,sensibilite0=12.2,sensibilite1=10.7, rho=1.21, espaceur=0.012, c=343): #start the acquisition task nidaq.DAQmxStartTask(tache) #if i add this line it works #raw_input(u'appuyez sur entree pour continuer') #gui class class GUI_acquisition(QtGui.QWidget): def __init__(self, app=None): super(GUI_acquisition, self).__init__() #create the gui #... #create an instance of the data acquisition class self.intensimetre= intensimetre(app=self.app,l1=self.l1,l2=self.l2,l3=self.l3) def demarrer(self): #start the data acquisition in a thread t = threading.Thread(target=self.intensimetre.demarrer) t.start() The problem is that the application crashes as soon as I start the data acquisition. If I add the raw_input line after starting the acquisition, then it works as it should. However, it doesn't feel like the right way to do it. It seems that once the acquisition is started, the thread returns and the callbacks from the acquisition are not processed properly. Any idea of how to fix this? Update I've replaced the raw_input line by an infinite loop polling the state a status attribute: while self.isRunning: sleep(0.1) I set the isRunning to True attribute when the user presses the start button and to False upon pressing of the stop button. While this works, I don't like polling as I think it can have a negative impact on the performance of my app.
has comment: http://stackoverflow.com/comment/88191960
score: 0
has comment: http://stackoverflow.com/comment/88192448
tagged with: pyqt
has comment: http://stackoverflow.com/comment/88192727

http://stackoverflow.com/comment/88434066
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50678866
has text: `mpl.use('Agg') ` works for me

http://stackoverflow.com/q/50578810
possible better answer: http://stackoverflow.com/a/50578871
type: Question
has answer: http://stackoverflow.com/a/50578871
tagged with: python
has answer: http://stackoverflow.com/a/50583706
has body: I'm trying to get the adidas shoe link from a search page, can't figure it out what I'm doing wrong. I tried tags = soup.find("section", {"class": "productList"}).findAll("a") Doesnt work :( I also tried to print all href and the desired link is not in there :( So I'm expecting to print this : https://www.tennisexpress.com/adidas-mens-adizero-ubersonic-50-yrs-ltd-tennis-shoes-off-white-and-signal-blue-62138 from bs4 import BeautifulSoup import requests url = "https://www.tennisexpress.com/search.cfm?searchKeyword=BB6892" # Getting the webpage, creating a Response object. response = requests.get(url) # Extracting the source code of the page. data = response.text # Passing the source code to BeautifulSoup to create a BeautifulSoup object for it. soup = BeautifulSoup(data, 'lxml') # Extracting all the tags into a list. tags = soup.find("section", {"class": "productList"}).findAll("a") # Extracting URLs from the attribute href in the tags. for tag in tags: print(tag.get('href')) Here's the html code for that link SALE Adidas Men`s Adizero Ubersonic 50 Yrs LTD Tennis Shoes Off White and Signal Blue $140.00 0% OFF $139.95
upvote count: 2
answer count: 3
tagged with: web-scraping
has answer: http://stackoverflow.com/a/50582739
tagged with: python-requests
accepted answer: http://stackoverflow.com/a/50583706
type: AnsweredQuestion
score: 2
downvote count: 0
has title: Scrape a url in Python
favorite count: 0
tagged with: beautifulsoup
tagged with: ajax

python-3.x
tags question: http://stackoverflow.com/q/50578454
tags question: http://stackoverflow.com/q/50688017
tags question: http://stackoverflow.com/q/50572655
tags question: http://stackoverflow.com/q/50588944
tags question: http://stackoverflow.com/q/50563745
tags question: http://stackoverflow.com/q/50573260
tags question: http://stackoverflow.com/q/50615482
tags question: http://stackoverflow.com/q/50621438
tags question: http://stackoverflow.com/q/50616566
tags question: http://stackoverflow.com/q/50544855
tags question: http://stackoverflow.com/q/50665581
tags question: http://stackoverflow.com/q/50557233
tags question: http://stackoverflow.com/q/50563867
tags question: http://stackoverflow.com/q/50664601
tags question: http://stackoverflow.com/q/50649171
tags question: http://stackoverflow.com/q/50659967
tags question: http://stackoverflow.com/q/50590023
tags question: http://stackoverflow.com/q/50686671
tags question: http://stackoverflow.com/q/50638571
tags question: http://stackoverflow.com/q/50563646
tags question: http://stackoverflow.com/q/50614701
tags question: http://stackoverflow.com/q/50669309
tags question: http://stackoverflow.com/q/50692125
tags question: http://stackoverflow.com/q/50658360
tags question: http://stackoverflow.com/q/50657228
tags question: http://stackoverflow.com/q/50610838
tags question: http://stackoverflow.com/q/50546034
tags question: http://stackoverflow.com/q/50557792
tags question: http://stackoverflow.com/q/50608705
tags question: http://stackoverflow.com/q/50569253
tags question: http://stackoverflow.com/q/50587126
tags question: http://stackoverflow.com/q/50623430
tags question: http://stackoverflow.com/q/50659490
tags question: http://stackoverflow.com/q/50694835
tags question: http://stackoverflow.com/q/50629427
tags question: http://stackoverflow.com/q/50553432
tags question: http://stackoverflow.com/q/50654215
tags question: http://stackoverflow.com/q/50663145
tags question: http://stackoverflow.com/q/50569247
tags question: http://stackoverflow.com/q/50546540
tags question: http://stackoverflow.com/q/50600105
tags question: http://stackoverflow.com/q/50546451
tags question: http://stackoverflow.com/q/50680028
tags question: http://stackoverflow.com/q/50566982
tags question: http://stackoverflow.com/q/50542767
tags question: http://stackoverflow.com/q/50596574
tags question: http://stackoverflow.com/q/50553261
tags question: http://stackoverflow.com/q/50568396
tags question: http://stackoverflow.com/q/50698390
tags question: http://stackoverflow.com/q/50586304
tags question: http://stackoverflow.com/q/50608167
tags question: http://stackoverflow.com/q/50685450
tags question: http://stackoverflow.com/q/50567595
tags question: http://stackoverflow.com/q/50662220
tags question: http://stackoverflow.com/q/50582759
tags question: http://stackoverflow.com/q/50649461
tags question: http://stackoverflow.com/q/50590714
tags question: http://stackoverflow.com/q/50572997
tags question: http://stackoverflow.com/q/50669917
tags question: http://stackoverflow.com/q/50562946
tags question: http://stackoverflow.com/q/50670392
tags question: http://stackoverflow.com/q/50689217
tags question: http://stackoverflow.com/q/50667036
tags question: http://stackoverflow.com/q/50674350
tags question: http://stackoverflow.com/q/50559652
tags question: http://stackoverflow.com/q/50642064
tags question: http://stackoverflow.com/q/50612386
tags question: http://stackoverflow.com/q/50627218
tags question: http://stackoverflow.com/q/50664839
tags question: http://stackoverflow.com/q/50614980
tags question: http://stackoverflow.com/q/50649425
tags question: http://stackoverflow.com/q/50577930
tags question: http://stackoverflow.com/q/50636155
tags question: http://stackoverflow.com/q/50547519
tags question: http://stackoverflow.com/q/50564620
tags question: http://stackoverflow.com/q/50693203
tags question: http://stackoverflow.com/q/50696386
tags question: http://stackoverflow.com/q/50671360
tags question: http://stackoverflow.com/q/50668927
tags question: http://stackoverflow.com/q/50585350

http://stackoverflow.com/q/50572894
has comment: http://stackoverflow.com/comment/88181638
has body: I have a question about zsh and numpy module for python3. I have problem with python3 interpreter and jupyter notebook, when I open my console by default /bin/zsh now and enter to python3 interpreter after importing module 'numpy' it could not find it, but when I start /bin/zsh go to bash and then to zsh it magically appeared I don't know where the problem is, I've searched through $PATH and rc srcipt for zsh and I found nothing.just ignore my cd ./- login script command
score: 0
tagged with: bash
tagged with: jupyter-notebook
tagged with: zsh
type: UnansweredQuestion
tagged with: python
answer count: 0
has title: ZSH no module named numpy for python3 interpreter and jupyter notebook
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88155667

http://stackoverflow.com/comment/88450472
score: 0
has text: Running locally (8813ms), remotely (8811ms).
comment on: http://stackoverflow.com/q/50698165
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50545596
accepted answer: http://stackoverflow.com/a/50545879
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50545879
tagged with: nlp
tagged with: conv-neural-network
downvote count: 0
type: AnsweredQuestion
has body: I have seen many papers explaining the use of pretrained word embeddings (such as Word2Vec or Fasttext) on sentence sentiment classification using CNNs (like Yoon Kim's paper). However, these classifiers also account for order that the words appear in. My application of word embeddings is to predict the class of "pools" of words. For example, in the following list of lists example = [["red", "blue", "green", "orange"], ["bear", "horse", "cow"], ["brown", "pink"]] The order of the words doesn't matter, but I want to classify the sublists into either class of color or animal. Are there any prebuilt Keras implementations of this, or any papers you could point me to which address this type of classification problem based on pretrained word embeddings? I am sorry if this is off-topic in this forum. If so, please let me know where would be a better place to post it.
has title: Using pretrained word embeddings to classify "pools" of words
score: 1
has comment: http://stackoverflow.com/comment/88102475
type: Question
tagged with: deep-learning
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/88102190
has comment: http://stackoverflow.com/comment/88102265
tagged with: keras

http://stackoverflow.com/q/50614257
upvote count: 1
tagged with: socket.io
type: Question
has title: Flask-SocketIO not receiving message
tagged with: javascript
has comment: http://stackoverflow.com/comment/88242584
tagged with: flask
accepted answer: http://stackoverflow.com/a/50616500
answer count: 1
downvote count: 0
has body: SocketIO version 1.3.6 Python 3.6 I am using Flask-SocketIO in my python app to send and receive message. I am able to send message (I see the output in terminal) but the client is not receiving the message (no output in console). $(document).ready(function() { var socket = io.connect('http://localhost:5000/'); socket.on('connect', function() { console.log("connected") }); socket.on('message', function(msg) { console.log('Received message'); }); $('#submitmsg').on('click', function() { socket.send($('#usermsg').val()); $('#usermsg').val(''); }); }); Chat window HTML: Welcome Exit EDIT: Adding server code: from flask import Flask, render_template from flask_socketio import SocketIO, send app = Flask(__name__) socketio = SocketIO(app) @app.route("/") def index(): return render_template('index.html') @socketio.on('message') def handleMessage(msg): print('Message: ' + msg) send(msg, broadcast=True) if __name__ == '__main__': socketio.run(app) If the received message works, I should see 'Received message' in the browser console but I do not see it. What am I missing? Any suggestion?
favorite count: 0
has comment: http://stackoverflow.com/comment/88242591
tagged with: python
has comment: http://stackoverflow.com/comment/88242046
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50616500
has comment: http://stackoverflow.com/comment/88240493
score: 1
tagged with: flask-socketio

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

http://stackoverflow.com/comment/88314120
has text: maybe you were confusing `groupby` and `filter`?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50651429

http://stackoverflow.com/a/50711409
upvote count: 1
has body: you can use x_axis_type='datetime' inside the bokeh.plotting.figure function to indicate that your x axis is going to display time. import pandas as pd import numpy as np import bokeh import bokeh.plotting N = 4 cats = 3 data = [[2,3,4], [2,2,3], [0,0,0], [1,2,3]] df = pd.DataFrame(data, columns=['y0', 'y1', 'y2']) print df dates = ['2016-06-01','2016-06-02','2016-06-03','2016-06-04'] dt = [pd.datetime.strptime(x,'%Y-%m-%d') for x in dates] def stacked(df): df_top = df.cumsum(axis=1) df_bottom = df_top.shift(axis=1).fillna({'y0': 0})[::-1] df_stack = pd.concat([df_bottom, df_top], ignore_index=True) return df_stack areas = stacked(df) colors = bokeh.palettes.brewer['Spectral'][areas.shape[1]] x2 = np.hstack((dt[::-1], dt)) p = bokeh.plotting.figure(x_axis_type='datetime', y_range=(0, 10)) p.xaxis.formatter = bokeh.models.formatters.DatetimeTickFormatter( days=["%Y-%m-%d"]) p.grid.minor_grid_line_color = '#eeeeee' p.patches([x2] * areas.shape[1], [areas[c].values for c in areas], color=colors, alpha=0.8, line_color=None) bokeh.io.output_file('brewer.html', title='brewer.py example') bokeh.io.show(p)
accepted answer of: http://stackoverflow.com/q/50689985
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50689985
type: Answer
score: 1

http://stackoverflow.com/comment/88235782
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50612059
has text: Ah ok; don't use pyplot when working with several axes. Replace `plt.title("...")` by `ax.set_title("...")` etc.
type: Comment

http://stackoverflow.com/comment/88277198
type: QuestionComment
comment on: http://stackoverflow.com/q/50633189
has text: Possible duplicate of [How do I pass a variable by reference?](https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference)
score: 1
type: Comment

http://stackoverflow.com/comment/88344016
comment on: http://stackoverflow.com/q/50667057
score: 4
type: Comment
type: QuestionComment
has text: `for i in nums:` isn't iterating over the indices, it is iterating over the actual list items.

http://stackoverflow.com/comment/88371172
score: 0
comment on: http://stackoverflow.com/a/50680818
type: AnswerComment
type: Comment
has text: @user3280146 - You are welcome! Btw, small advice - [don't post images of code (or links to them)](http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question)

http://stackoverflow.com/q/50662674
type: Question
has title: OSError: [Errno 8] Exec format error: 'geckodriver' when trying to open firefox using selenium in python
answer count: 2
tagged with: firefox
downvote count: 0
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50662736
possible better answer: http://stackoverflow.com/a/70890086
has answer: http://stackoverflow.com/a/70890086
tagged with: selenium
has body: from selenium import webdriver browser = webdriver.Firefox(executable_path="/usr/bin/geckodriver") browser.get('http://www.ubuntu.com/') The entire stack trace looks like: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/firefox/webdriver.py", line 160, in __init__ self.service.start() File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/common/service.py", line 76, in start stdin=PIPE) File "/usr/lib/python3.6/subprocess.py", line 709, in __init__ restore_signals, start_new_session) File "/usr/lib/python3.6/subprocess.py", line 1344, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) OSError: [Errno 8] Exec format error: 'geckodriver' my path to geckodriver is: /usr/bin/geckodriver And selenium is in: selenium in /usr/local/lib/python3.6/dist-packages (3.12.0) Thanks in advance!
type: AnsweredQuestion
score: 10
accepted answer: http://stackoverflow.com/a/50662736
has comment: http://stackoverflow.com/comment/88335584
upvote count: 10

http://stackoverflow.com/comment/88280377
type: Comment
comment on: http://stackoverflow.com/a/50628945
score: 0
type: AnswerComment
has text: Updated the answer, use `form.as_p` in template.

http://stackoverflow.com/a/50657054
has body: There are some mistakes in your code . You calculate the wrong p2 value ,p2 value is just a 10$ . Not a 10 times of balance. If p3 value is greater than balance value,prints the balance value .Not the p3 value .Because in this case balance value is lesser than minimum payment 'p3' value. p1 = balance * 0.021; p2 = 10; p3 = max(p1,p2); if ( balance &lt; p3 ) : print(balance); else : print(p3);
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50656813

http://stackoverflow.com/q/50563984
tagged with: pip
has comment: http://stackoverflow.com/comment/88138617
has answer: http://stackoverflow.com/a/50568297
has answer: http://stackoverflow.com/a/50568360
tagged with: paramiko
has comment: http://stackoverflow.com/comment/88138211
has comment: http://stackoverflow.com/comment/88138597
score: 2
has comment: http://stackoverflow.com/comment/88138602
has title: How to install pip3 and paramiko in ubuntu 16.04 LTS?
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88138462
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/88143294
has comment: http://stackoverflow.com/comment/88138562
type: Question
has comment: http://stackoverflow.com/comment/88138404
has body: I am trying to install python paramiko using below command: pip3 install paramiko then I got an error: The program 'pip3' is currently not installed. You can install it by typing: sudo apt install python3-pip then tried to install pip using above command, the result is: Reading package lists... Done Building dependency tree Reading state information... Done python3-pip is already the newest version (8.1.1-2ubuntu0.4). The following packages were automatically installed and are no longer required: python3-babel python3-dateutil python3-decorator python3-funcsigs python3-gevent python3-greenlet python3-html2text python3-mock python3-ofxparse python3-passlib python3-pbr python3-psutil python3-psycopg2 python3-pydot python3-pyinotify python3-pypdf2 python3-serial python3-stdnum python3-tz python3-usb python3-vatnumber python3-werkzeug python3-yaml Use 'sudo apt autoremove' to remove them. 0 upgraded, 0 newly installed, 0 to remove and 82 not upgraded. Then I tried to install paramiko again but getting the same error, pip is not installed. When I type pip3 --version the output is: The program 'pip3' is currently not installed. You can install it by typing: sudo apt install python3-pip pip --version Output is: pip 10.0.1 from /usr/local/lib/python2.7/dist-packages/pip (python 2.7) How can I resolve this?
tagged with: python
has comment: http://stackoverflow.com/comment/88138623
has comment: http://stackoverflow.com/comment/88138189
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88138653
upvote count: 2
has comment: http://stackoverflow.com/comment/88138296
has comment: http://stackoverflow.com/comment/88138639
answer count: 2

http://stackoverflow.com/q/50687810
tagged with: command-line
has body: I am trying to run the main() from my python test from my RF file with optional keyword-arguments range, domain, and timeout. The test works fine if I hard-code the args in the RF file, but I am hopefully looking to be able to set them from the command-line. I am looking to be able to run the RF file giving any, all, or none of the 3 args listed above with something similar to robot -v dict_args:range=5_domain=4 -E space=_ run_test.robot. According to the documentation, "Only scalar variables can be set using this syntax and they can only get string values", but I've seen people on here that are able to write a workaround for lists (How to pass a list as command line argument in robot framework.?). Haven't been able to find anything on dicts, any advice/help would be greatly appreciated. run_test.robot: *** Settings *** Library my_test Library Process *** Test Cases *** Run RNTester Run Program ${dict-args} *** Keywords *** Run Program [Arguments] &amp;{configuration} main &amp;{configuration} my_test.py: def main(**kwargs): #process args if 'range' in kwargs: range_ = kwargs['range'].split(':') range_ = list(map(int,range_)) if len(range_) == 1: range_.insert(0,0) test_count = range_[1] - range_[0] else: range_ = None test_count = 0 if 'domain' in kwargs: domain = kwargs['domain'].split(',') else: domain = None if 'timeout' in kwargs: timeout = int(kwargs['timeout']) else: timeout = 30 run_test(domain, range_, test_count, timeout) FIXED Edited my code to write to a yaml file as @jil suggested. Added a YAMLCreator.py to make a yaml file that my RF file imports. Here's what I now have run_test.robot: *** Settings *** Library my_test Variables ${testname}.yaml *** Test Cases *** Run RNTester Run Program &amp;{test_name} *** Keywords *** Run Program [Arguments] &amp;{configuration} main &amp;{configuration} YAMLCreator.py: import yaml import sys def make_dict(**kwargs): data = dict() for key in kwargs: value = kwargs[key] data[key] = value return data if __name__ == '_…
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/50694725
tagged with: robotframework
score: 0
answer count: 2
has title: How to pass in a dict to a Robot Framework variable from the command-line
accepted answer: http://stackoverflow.com/a/50694725
tagged with: python-3.x
linked to: http://stackoverflow.com/q/44067832
possible better answer: http://stackoverflow.com/a/50688801
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/50688801

http://stackoverflow.com/q/50634988
has title: how to drop row base on lambda
has body: I have dataframe in which I have to drop row if some of values. for instance, x not in ['N/A', ''] where x is columns is there a way like, apply? df[x] = df[x].apply(lambda x: x.lower()) I am think in something like: df.drop.apply(lambda x: X not in ['N/A', ''])??? My DF F T l 0 0 "0" "0" 1 1 "" "1" 2 2 "2" "" drop row if T == "" or l == "" F T l 0 0 "0" "0" I could not use df.drop(df.T == "") since the condition ("") depend on runtime data
accepted answer: http://stackoverflow.com/a/50643908
has answer: http://stackoverflow.com/a/50635151
tagged with: python
linked to: http://stackoverflow.com/q/7623715
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50635151
tagged with: dataframe
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/11869910
has answer: http://stackoverflow.com/a/50643908
has comment: http://stackoverflow.com/comment/88280164
score: 0

http://stackoverflow.com/comment/88320367
type: QuestionComment
type: Comment
has text: I have formatted your question in a way I think is more readable. I also removed some parts of my answer as they were mere copies. Hope you find it more readable as I do and maybe apply it in the future :)
score: 0
comment on: http://stackoverflow.com/q/50654881

http://stackoverflow.com/comment/88310848
type: Comment
type: QuestionComment
has text: @Davis It's strange because it keeps giving me the spaces
comment on: http://stackoverflow.com/q/50649754
score: 0

http://stackoverflow.com/q/50696486
has body: i am writing the python dict to CSV file by using the following code. my_dict['date'] = time.strftime('%d-%m-%Y') my_dict['error_log'] = data file_exists = os.path.isfile('build_error_deatils.csv') with open('build_error_deatils.csv', 'a+') as f: w = csv.DictWriter(f, my_dict.keys()) if not file_exists: w.writeheader() w.writerow(my_dict) everything getting copy properly apart from a chunk of log data which is the string like below. data = """ ../../../../../../../src/junos/usr.sbin/l2cpd/os/l2cpd_rts_reader.c: In function 'l2cpd_vpls_iff_get_stp_index': ../../../../../../../src/junos/usr.sbin/l2cpd/os/l2cpd_rts_reader.c:129: error: 'RTM_IFF_RLT_ACTIVE_LINK' undeclared (first use in this function) ../../../../../../../src/junos/usr.sbin/l2cpd/os/l2cpd_rts_reader.c:129: error: (Each undeclared identifier is reported only once ../../../../../../../src/junos/usr.sbin/l2cpd/os/l2cpd_rts_reader.c:129: error: for each function it appears in.) cc1: warnings being treated as errors ../../../../../../../src/junos/usr.sbin/l2cpd/os/l2cpd_rts_reader.c:129: warning: unused variable 'addi' make[1]: *** [l2cpd_rts_reader.o] Error 1 *** """ my_dict['error_log'] = data i am getting the data like below. not sure why error log is coming as empty. need help here thankyou in advance...
answer count: 1
has comment: http://stackoverflow.com/comment/88439486
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88461246
type: Question
score: 0
has title: writing python dict data to CSV file
has answer: http://stackoverflow.com/a/50726570

http://stackoverflow.com/comment/88137945
comment on: http://stackoverflow.com/a/50563623
has text: Edited my answer for a suggestion :)
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50573196
has answer: http://stackoverflow.com/a/54000367
has comment: http://stackoverflow.com/comment/89862862
has body: According to Google API Client Libraries page it is possible to access the Google Photos API using the python client library, but after installing it using pip install -t lib/ google-api-python-client I don't see anything related to Photos API. How can I use the Google built client library instead of manually calling the REST APIs?
upvote count: 16
type: Question
has answer: http://stackoverflow.com/a/50577184
possible better answer: http://stackoverflow.com/a/50577184
downvote count: 0
linked to: http://stackoverflow.com/q/66689941
has answer: http://stackoverflow.com/a/56611943
favorite count: 0
has answer: http://stackoverflow.com/a/50573233
tagged with: google-app-engine
accepted answer: http://stackoverflow.com/a/56611943
tagged with: python
answer count: 4
has title: Access Google Photo API with Python using google-api-python-client
tagged with: google-photos-api
linked to: http://stackoverflow.com/q/56374316
type: AnsweredQuestion
score: 16

http://stackoverflow.com/comment/88299575
type: Comment
comment on: http://stackoverflow.com/a/50644262
score: 1
has text: It is probably better to calculate `val` with `heapq.nlargest(5, d.values())[-1]` (assuming `n` is quite small relative to `len(d)`)
type: AnswerComment

http://stackoverflow.com/comment/88203231
type: QuestionComment
comment on: http://stackoverflow.com/q/50594310
has text: Anyone else have a suggestion?
score: 0
type: Comment

http://stackoverflow.com/q/50644702
has comment: http://stackoverflow.com/comment/88310987
has title: Is there any abbreviation to actual word conversion feature in NLTK
tagged with: nltk
favorite count: 0
tagged with: nlp
has body: I'm new to NLTK/NLP, I want to know is there a option to get the text transformation as given below. Input is pwr and Output is power pwr =&gt; power tmp =&gt; temprature pres =&gt; pressure I'm able to achieve this by replacing the text(pwr) with the actual word(power). Do python nltk have such capability? Thanks
type: UnansweredQuestion
tagged with: corpus
tagged with: python
downvote count: 1
score: 2
answer count: 0
upvote count: 3
type: Question

http://stackoverflow.com/comment/88178266
comment on: http://stackoverflow.com/q/50584191
score: 0
has text: i tired to declare it after `if device in row` with ` N_off = None` and then i get the error: `'NoneType' object has no attribute '__getitem__'`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88187079
type: QuestionComment
has text: I changed the frame size and it appears, but the text doesn't appear and it seems inactive when I test it.
comment on: http://stackoverflow.com/q/50587961
score: 0
type: Comment

http://stackoverflow.com/q/50658722
answer count: 3
accepted answer: http://stackoverflow.com/a/50658983
upvote count: 0
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50659108
score: -2
has answer: http://stackoverflow.com/a/50659494
tagged with: regex
has answer: http://stackoverflow.com/a/50659108
has title: Regex for Python Needed
has answer: http://stackoverflow.com/a/50658983
favorite count: 0
type: Question
downvote count: 2
tagged with: python
has body: Here are my strings : -rwxrwx--- Administrators/unknown 563092 0% 2018-05-29 02:16:49 E:/program files/bak fil/sql server (mssqlserver)/var/work.log -rwxrwx--- kandep2/Domain Users 563092 0% 2018-05-29 02:16:49 E:/program files/bak fil/sql server (mssqlserver)/var/dummy.log I would like to capture everything in a group except 0%. So far, i have the following regex: ([rwexXst-]+) ([^1-9]+) +(\d+)+.+? +(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) (.*) This works for the first row, but it fails on the second row because second row username has a number in it. How should i modify my regex to get output like this: Group#1 -rwxrwx--- Administrators/unknown 563092 2018-05-29 02:16:49 E:/program files/bak fil/sql server (mssqlserver)/var/work.log Group #2 -rwxrwx--- kandep2/Domain Users 563092 2018-05-29 02:16:49 E:/program files/bak fil/sql server (mssqlserver)/var/dummy.log

http://stackoverflow.com/q/50674147
has comment: http://stackoverflow.com/comment/88358212
tagged with: formatting
tagged with: output
upvote count: 5
downvote count: 0
type: UnansweredQuestion
has title: How can I print numbers in python with thin space characters as the thousands separators?
has answer: http://stackoverflow.com/a/50674211
has answer: http://stackoverflow.com/a/50674304
has body: I know for example "{:,}".format(123456789) will print '123,456,789' as output in python. However, instead of the commas I would like the thin space character as the thousands separator. According to here, the python source encoding for the thin space character is u"\u2009". So I tried replacing the comma in "{:,}" by u"\u2009", but that results in a syntax error. This might be because python can't deal with the resulting nested double quotes and something needs to be escaped. So is there a way to make this, or some other mechanism work? And by the way I'd like to suppress the single quotes that appear in the output as well.
favorite count: 0
tagged with: python-3.x
type: Question
answer count: 2
score: 5
tagged with: python
has comment: http://stackoverflow.com/comment/88358991

http://stackoverflow.com/comment/88348300
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50669278
has text: What part of the error message is confusing to you?

http://stackoverflow.com/comment/88386439
has text: Thanks, it was a typo, Jimmy should be in result two times. He was on vacation once from 04-07 to 04-08 and then later he was apsent one day (04-10)
type: Comment
comment on: http://stackoverflow.com/q/50687296
score: 0
type: QuestionComment

http://stackoverflow.com/q/50687774
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88385240
type: Question
has title: python IndexError: list index out of range -beautifulsoup
has comment: http://stackoverflow.com/comment/88385306
linked to: http://stackoverflow.com/q/522563
duplicate of: http://stackoverflow.com/q/522563
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50687837
has body: i write some code which return two output the error appears,what is the main problem of my code??????? from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup import os import sys import unicodecsv as csv import codecs from urllib.request import urlopen for i in range(22): my_url = "https://www.bamilo.com/electronic_accessories/?source=gfm/?facet_is_mpg_child=0&amp;viewType=gridView&amp;page=" uClient = uReq(my_url + str(i)) page_html = uClient.read() uClient.close() page_soup = soup(page_html, "html.parser") containers = page_soup.findAll("div" , {"class" : "sku -gallery" }) filename = "product.csv" f = codecs.open(filename, "a" , "utf-8-sig") headers = "price_two\n" f.write(headers) for container in containers: price_old = container.findAll("span",{"class" : "price -old "} ) price_two = price_old[0].text.strip() print("price_two " + price_two) f.write(price_two.replace(",", "") + "\n") f.close() ERORR ::: &gt; price_two 1,800,000ریال price_two 2,800,000ریال Traceback (most recent call last): File "F:\bam.py", line 34, in &lt;module&gt; price_two = price_old[0].text.strip() IndexError: list index out of range
tagged with: python
accepted answer: http://stackoverflow.com/a/50687837

google-app-engine
tags question: http://stackoverflow.com/q/50592736
tag name: google-app-engine
type: Tag
tags question: http://stackoverflow.com/q/50644198
tags question: http://stackoverflow.com/q/50581156
tags question: http://stackoverflow.com/q/50551364
tags question: http://stackoverflow.com/q/50573196
tags question: http://stackoverflow.com/q/50552534
tags question: http://stackoverflow.com/q/50616924
tags question: http://stackoverflow.com/q/50567925
tags question: http://stackoverflow.com/q/50689441
tags question: http://stackoverflow.com/q/50624231
tags question: http://stackoverflow.com/q/50691734
tags question: http://stackoverflow.com/q/50630668
tags question: http://stackoverflow.com/q/50625452
tags question: http://stackoverflow.com/q/50545773

http://stackoverflow.com/comment/88217158
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50603725
has text: df.apply(sum) will of course sum on the column (i.e., reduce) df.apply(lambda x: 2*x) will just apply the lambda function to each element (i.e., it's a map). There is no means for passing df.apply(lambda x,y, (x+y)*y, reduce=True)

http://stackoverflow.com/comment/88271486
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50612523
has text: I only did `n_jobs = 1` because the error message is cleaner. I have it set up right now with manual `cv` but the `model_selection.cross_val_score` is just too good to not use :)

http://stackoverflow.com/a/67326284
has body: This easy solution worked great for me: from IPython.display import Video, Image, HTML, display image_path1 = "/myfolder/my_img1.jpg" image_path2 = "/myfolder/my_img2.jpg" HTML(f""" """) I put in different widths for if you have a portrait and a landscape picture, but that is up to you depending on the images and the aspect ratios.
answers question: http://stackoverflow.com/q/50559000
has comment: http://stackoverflow.com/comment/126063315
score: 2
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/a/50698448
score: 1
downvote count: 1
answers question: http://stackoverflow.com/q/50698175
has body: Here's one way using set. Downside is the list copy operation and initial set conversion. Upside is O(1) removal and lookup operations. a = [1,2,3,2,4,5] b = [2,5] b_set = set(b) c = a.copy() for i in range(len(c)): if c[i] in b_set: b_set.remove(c[i]) else: c[i] = 0 print(c) [0, 2, 0, 0, 0, 5]
type: Answer
upvote count: 2

http://stackoverflow.com/q/50623915
has body: I'm getting soup using this: soup = BeautifulSoup(html, 'lxml').find("tbody").find_all("tr") And then soup object contains multiple similar tr> objects just like this: 115 204 United States NY brown up groove So, my goal is - to get stripped text data from just 1,2,4 and put them together to small list. Like this: [115, 204, 'brown'] And after I got all the small lists from all , I have to add all of them to big list. Like this: [[115, 204, 'brown'], [32, 12, 'red'] ... [42, 87, 'yellow']] To be honest, I did it using two for loops, and sliced needed small list items to append a big list. But I assume, there is much better and simplier way to do that. Maybe you have some ideas how to use powerful abilities of BeautifulSoup in my case?
has comment: http://stackoverflow.com/comment/88257712
tagged with: python
type: AnsweredQuestion
has title: How to get parent items with BeautifulSoup4?
type: Question
score: 0
tagged with: strip-tags
answer count: 1
has answer: http://stackoverflow.com/a/50624068
accepted answer: http://stackoverflow.com/a/50624068
has comment: http://stackoverflow.com/comment/88257681
tagged with: beautifulsoup

http://stackoverflow.com/comment/88207972
has text: They have to be enclosed in braces.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50599387

http://stackoverflow.com/q/50619846
has comment: http://stackoverflow.com/comment/88249736
tagged with: matplotlib
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88249773
score: 0
answer count: 2
upvote count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88249392
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50619901
tagged with: python
has answer: http://stackoverflow.com/a/50620122
has title: Building subplots
has body: I'm trying to create a series of subplots: count=0 fig1, axes1 = plt.subplots(nrows=2, ncols=1, figsize=(10,80)) for x in b: """code gets data here as a dataframe""" axes1[count]=q1.plot() count=count+1 However this creates two plots rather than 2 subplots in one figure. I am using python 3.5 in Pycharm. Been racking my brain at what i'm doing wrong here
type: Question

http://stackoverflow.com/comment/88155661
has text: Also, process file is way to large to paste here... It works seamlessly with .apply_async and .map as well
comment on: http://stackoverflow.com/q/50572875
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88222519
has text: Is the file `http://localhost:8085/weather-2.html` available under this URL?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50603665

http://stackoverflow.com/q/50562552
has body: I'm new to PyTorch. It is working when I use gpu running my program with TensorFlow. But this is a problem with PyTorch. I search a lot, but cannot find any useful answer. Who can help me? Error: My environment: windows10 64bit python3.6 cuda9.0 cudnn64 gpu:GTX965m
score: -1
favorite count: 0
tagged with: pytorch
tagged with: python
tagged with: cuda
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50564621
downvote count: 1
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/88139409
answer count: 1
has title: Issue with torch.cuda() function
accepted answer: http://stackoverflow.com/a/50564621

http://stackoverflow.com/comment/88365191
comment on: http://stackoverflow.com/a/50677830
score: 0
type: AnswerComment
type: Comment
has text: Thanks, indeed the _errors_ input for which I was looking for! Will accept your answer after the 10 minute rule.

http://stackoverflow.com/a/50638327
answers question: http://stackoverflow.com/q/50637701
has body: If you are looking for one specific key's total, you can use the .count() list method as a direct query. Given a list of dicts: &gt;&gt;&gt; employees = [{'name': 'John', 'empID': '102', 'dpt': 'tech', 'title': 'programmer', 'salary': '75'}, {'name': 'Jane', 'empID': '202', 'dpt': 'tech', 'title': 'programmer', 'salary': '80'}, {'name': 'Joe', 'empID': '303', 'dpt': 'accounting', 'title': 'accountant', 'salary': '85'}] You can create a list of each with a list comprehension: &gt;&gt;&gt; [d['dpt'] for d in employees] ['tech', 'tech', 'accounting'] And that can then be tallied: &gt;&gt;&gt; [d['dpt'] for d in employees].count('tech') 2 &gt;&gt;&gt; [d['dpt'] for d in employees].count('accounting') 1 &gt;&gt;&gt; [d['dpt'] for d in employees].count('nothing') 0 Alternatively, you can construct a generator that will tally specific values: &gt;&gt;&gt; sum(1 for d in employees if d['dpt']=='tech') 2 If you want to have the count of all elements (other than using a Counter) you can do: &gt;&gt;&gt; lot=[d['dpt'] for d in employees] &gt;&gt;&gt; {c:lot.count(c) for c in set(lot)} {'accounting': 1, 'tech': 2}
score: 0
type: Answer

http://stackoverflow.com/q/50624409
has answer: http://stackoverflow.com/a/50637324
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/88285821
possible better answer: http://stackoverflow.com/a/66094853
type: Question
has title: Find index of duplicate rows in Openpyxl
has answer: http://stackoverflow.com/a/66094853
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/50637324
has body: I want to find the index of all duplicate rows in an excel file and add them to a list which will be handled later. unwantedRows = [] Row = [] item = "" for index, row in enumerate(ws1.iter_rows(max_col = 50), start = 1): for cell in row: if cell.value: item += cell.value if item in Row: unwantedRows.append(index) else: Row.append(item) However this fails to work. It only indexes rows that are completely empty. How do I fix this?
score: 3
favorite count: 0
tagged with: openpyxl
tagged with: python
tagged with: excel

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

http://stackoverflow.com/comment/88322859
comment on: http://stackoverflow.com/q/50656320
score: 0
type: Comment
has text: If you seek help with a bug in your code you are not asking the appropriate question. You should rewrite the question to explain what output you do get vs what output you require, asking for assistance with that, rather than a general question about the algorithm.
type: QuestionComment

http://stackoverflow.com/comment/88192633
type: Comment
comment on: http://stackoverflow.com/a/50591642
score: 1
has text: I'd suggest you add that using `shell=True` is considered to be less desirable.
type: AnswerComment

http://stackoverflow.com/q/50631221
upvote count: 1
downvote count: 1
type: Question
score: 0
tagged with: printing
tagged with: yaml
linked to: http://stackoverflow.com/q/36452052
favorite count: 0
has body: I have a script that parses a yaml file and extracts key/value pairs and prints them, but I keep getting single quotes in the output. How do I get rid of the quote marks? YML Snippet AsNum: description: Local AS for BGP global format: string type: string Function from Script def getVals(dict): for key,value in dict.items(): #print(keys) if isDict(value): if key != "properties" and key != "items": print(key) getVals(value) else: print("key: ", key, " value: ", value) Example Output AsNum ('key: ', 'type', ' value: ', 'string') ('key: ', 'description', ' value: ', 'Local AS for BGP global') ('key: ', 'format', ' value: ', 'string')
tagged with: python
has comment: http://stackoverflow.com/comment/88272443
has title: How to get rid of the quote marks from a dict key/value pair?
answer count: 0
has comment: http://stackoverflow.com/comment/88292818
type: UnansweredQuestion

http://stackoverflow.com/comment/88259939
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50623237
has text: Still getting excel popup "want to save your changes to workbook" :(
type: Comment

apache-spark-2.2
tags question: http://stackoverflow.com/q/50658159
tag name: apache-spark-2.2
type: Tag

http://stackoverflow.com/q/50671066
tagged with: python
has comment: http://stackoverflow.com/comment/88352331
linked to: http://stackoverflow.com/q/12773763
has comment: http://stackoverflow.com/comment/88352845
tagged with: django
has comment: http://stackoverflow.com/comment/88351959
has answer: http://stackoverflow.com/a/50703111
type: Question
linked to: http://stackoverflow.com/q/5149832
has comment: http://stackoverflow.com/comment/88352756
has comment: http://stackoverflow.com/comment/88351913
has comment: http://stackoverflow.com/comment/88352866
has comment: http://stackoverflow.com/comment/88352616
has comment: http://stackoverflow.com/comment/88352923
score: 0
has comment: http://stackoverflow.com/comment/88352817
answer count: 1
has comment: http://stackoverflow.com/comment/88351998
has body: I know such questions exist gallore in SO. But none satisfies my problem. My code however works in localhost in my PC but not in online server. The site is here. You can go to the English tab and click a news headline to see the ajax request. It is a simple ajax request from the template to the view.py file through a URL defined in the urls.py file. The url (i.e. show_recommendation) is defined in the following way : from django.contrib import admin #from django.urls import path from django.conf.urls import url from khobor import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^admin/', admin.site.urls), url(r'^find_feed/', views.find_feed, name="find_feed"), url(r'^show_articles/', views.show_articles, name="show_articles"), url(r'^clear_cookie/', views.clear_cookie, name="clear_cookie"), url(r'^show_recommendation', views.show_recommendation, name="show_recommendation"), ] JavaScript code in template is as follows: $.ajax({ url:"/show_recommendation/", method:"POST", dataType: 'JSON', data:{ id_found:id_found, csrfmiddlewaretoken: '{{ csrf_token }}' }, success:function (data) { //data=$.parseJSON(data); alert(data); if(window.console){ console.log(" response data = "); console.log(data); } if($.isArray(data)){ for(i=0; i&lt;data.length; i++){ var id_found=data[i][0]; if(window.console){ console.log(" id found = "+id_found+" id found result = "+jQuery.inArray(id_found, ids_all)); } if(jQuery.inArray(id_found, ids_all) ==-1){ ids_all.push(id_found); new_ids.push(id_found); if(window.console){ console.log(" id pushed = "+id_found); } //$("#recommendations").append('&lt;li&gt;'+data[i][0]+' ... '+data[i][1]+'&lt;/li&gt;'); $("#recommendations").append('&lt;li class="article_indiv inline_block"&gt;' + '&lt;span class="top_image inline_block" data-id="'+data[i][0]+'" &gt;&lt;img src="'+data[i][4]+'" alt="image"/&gt;'+ '&lt;/span&gt;' + '&lt;a class="link" data-id="'+data[i][0]+'" target="_blank" href="'+data[i][2]+'" &gt;'+data[i][3]+'&lt;/a&gt;' + '&lt…
tagged with: ajax
has comment: http://stackoverflow.com/comment/88352850
tagged with: python-3.x
has title: python django ajax : ValueError: The view didn't return an HttpResponse object. It returned None instead
type: UnansweredQuestion

http://stackoverflow.com/a/50567113
has body: You're getting the error because self.emoji_per_word[time_stamp] doesn't exist when time_stamp != 0 so you need to create the dictionary first before assigning values to it, like so: else: self.emoji_per_word[time_stamp] = {} self.emoji_per_word[time_stamp]['worte'] = worte self.emoji_per_word[time_stamp]['emojis'] = emojis
accepted answer of: http://stackoverflow.com/q/50567005
score: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50567005

http://stackoverflow.com/comment/88392471
comment on: http://stackoverflow.com/q/50691394
type: Comment
type: QuestionComment
has text: Exactly what doesn't return an output and what exactly isn't working here? Is the if-statement not being entered or is something inside your if statement not working? Your not storing the output of any method anywhere in your code. We don't have the code for: `games.guess_the_number(u_name)`. Including the value of `u_name`. See: https://stackoverflow.com/help/mcve
score: 0

http://stackoverflow.com/a/50553468
accepted answer of: http://stackoverflow.com/q/50553432
score: 2
downvote count: 0
has body: you can do the following for each in my_list: if each['user'] == "1001" #or you can use a variable here each['account1']+=100 # even here, instead of account1 you can use a variable The above code works because its the reference you are updating.
upvote count: 2
has comment: http://stackoverflow.com/comment/88117987
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50553432
type: Answer

http://stackoverflow.com/a/50695476
score: 1
upvote count: 1
has body: num = 5 pizza_name = 'pizza_' + str(num) print('Our pizza choices are ' + pizza_name + '!') #What you created above is a variable. That is not a list. Below is a list: #pizzas = ['pepperoni', 'extra cheese', 'cheese', 'veggie'] current_pizza = input('What pizza would you like: ') current_pizza_name = ('pizza_' + str(current_pizza) + '[1]') pizza_ammount = int(input('How many ' + current_pizza_name + "'s would you like?: ")) print('You would like ' + str(pizza_ammount) + ' ' + current_pizza_name + ' pizzas!') Here is your output: Our pizza choices are pizza_5! What pizza would you like: 5 How many pizza_5[1]'s would you like?: 10 You would like 10 pizza_5[1] pizzas! Now you've stated that you want a list, but in your example there is not list, so i'm not sure what you mean, but below is an example of a list of pizzas and attaching a number to each pizza after we access it: pizza_list = [1, 2, 3, 4, 5, 6, 7, 8] print('Our pizza choices are: ') for pizza in pizza_list: print('\t' + str(pizza)) pizza_choice = int(input('Which pizza would you like to select?: ')) if pizza_choice in pizza_list: current_pizza = 'pizza_' + str(pizza_choice) else: print('We do not have that pizza') pizza_amount = int(input('How many ' + current_pizza + "'s would you like?: ")) print('You would like ' + str(pizza_amount) + ' ' + current_pizza + " pizza's.") Above we have a list, which I do not see in your code example called pizza list. If the user selects a pizza within the list we can attach that pizza number to the end of the pizza_ string. We then ask the user how many pizza's they want. The pizza_list can server as your list. Here is the output: Our pizza choices are: 1 2 3 4 5 6 7 8 Which pizza would you like to select?: 5 How many pizza_5's would you like?: 20 You would like 20 pizza_5 pizza's.
has comment: http://stackoverflow.com/comment/88400219
downvote count: 0
has comment: http://stackoverflow.com/comment/88400287
has comment: http://stackoverflow.com/comment/88400326
has comment: http://stackoverflow.com/comment/88400738
answers question: http://stackoverflow.com/q/50695179
type: Answer
has comment: http://stackoverflow.com/comment/88400667
has comment: http://stackoverflow.com/comment/88400483

http://stackoverflow.com/comment/88386460
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50688189
has text: When you create an instance of the classifier there should be an argument called `random_state` that you should set to a number.

http://stackoverflow.com/comment/88114964
has text: I've been around 6 hours on the problem without getting any solutions...
comment on: http://stackoverflow.com/q/50550905
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50673678
has title: Argument mismatch in python constructor
favorite count: 0
tagged with: python-3.x
has body: I have written a python class whose constructor takes two lists as arguments. class nn: def __init__(layer_dimensions=[],activations=[]): self.parameters = {} self.cache = [] self.activations= [] initialize_parameters(layer_dimensions) initialize_activations(activations) net = nn(list([2,15,2]),list(['relu','sigmoid'])) On trying to pass two lists as arguments in the constructor I get the following error: TypeError: __init__() takes from 0 to 2 positional arguments but 3 were given The error states that 3 arguments have been passed but its quite obvious that I've passed only 2.
possible better answer: http://stackoverflow.com/a/50673707
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/50673691
has answer: http://stackoverflow.com/a/50673707
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50674337
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/88356983
type: Question
linked to: http://stackoverflow.com/q/23944657
accepted answer: http://stackoverflow.com/a/50673691
duplicate of: http://stackoverflow.com/q/23944657
answer count: 3

http://stackoverflow.com/q/50634615
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/88283185
type: Question
tagged with: pymysql
downvote count: 0
tagged with: virtualenv
tagged with: flask
favorite count: 0
tagged with: python-3.x
has body: A server's default Python version is 2.6. Python 3 is also installed and I created a virtual environment (python3 -m venv py3env) and installed Flask and PyMySQL within the virtual environment. However, after the web-server (Apache+WSGI) is configured, the application doesn't work and throws the following error: File "/var/www/webapp/py3env/lib/python3.6/site-packages/pymysql/__init__.py", line 90, in Connect return Connection(*args, **kwargs) File "/var/www/webapp/py3env/lib/python3.6/site-packages/pymysql/connections.py", line 699, in __init__ self.connect() File "/var/www/webapp/py3env/lib/python3.6/site-packages/pymysql/connections.py", line 935, in connect self._get_server_information() File "/var/www/webapp/py3env/lib/python3.6/site-packages/pymysql/connections.py", line 1249, in _get_server_information packet = self._read_packet() File "/var/www/webapp/py3env/lib/python3.6/site-packages/pymysql/connections.py", line 991, in _read_packet packet_header = self._read_bytes(4) File "/var/www/webapp/py3env/lib/python3.6/site-packages/pymysql/connections.py", line 1025, in _read_bytes data = self._rfile.read(num_bytes) File "/usr/lib64/python2.6/io.py", line 940, in read return self._read_unlocked(n) File "/usr/lib64/python2.6/io.py", line 974, in _read_unlocked chunk = self.raw.read(wanted) File "/usr/lib64/python2.6/io.py", line 591, in read n = self.readinto(b) File "/var/www/webapp/py3env/lib/python3.6/site-packages/pymysql/_socketio.py", line 59, in readinto return self._sock.recv_into(b) TypeError: recv_into() argument 1 must be pinned buffer, not bytearray I tried installing python-socketio via pip but it still isn't being used. MySQL-python is installed on the server. How does one force the application to use the Virtual environment's version?
has title: Python 3 virtual environment uses default Python's (2.6) socket connections for PyMySQL

http://stackoverflow.com/a/50566015
has body: The .keys() method on a dictionary gives you a dictionary view, which can act like a set. This means you can take the intersection between the key views of two dictionaries! You want the intersection between the inital targetDict and the dictionaries named in lookup: for word in lookup: other_dict = mainDict[word] common_keys = targetDict.keys() &amp; other_dict targetOutput.append([other_dict[common] for common in common_keys]) The targetDict.keys() &amp; other_dict expression produces the intersection here: &gt;&gt;&gt; mainDict = { ... 'x': {'one': 1, 'blue': 1, 'green' :1}, ... 'y': {'red': 1, 'blue': 2, 'two': 1}, ... 'z': {'one': 1, 'green': 1, 'red': 1} ... } &gt;&gt;&gt; targetDict = mainDict['x'] &gt;&gt;&gt; targetDict.keys() &amp; mainDict['y'] {'blue'} &gt;&gt;&gt; targetDict.keys() &amp; mainDict['z'] {'green', 'one'} The [other_dict[common] for common in common_keys] list comprehension takes those keys and looks up the values for them from the other dictionary. If you want to sum the values, just pass the same sequence of values to the sum() function: for word in lookup: other_dict = mainDict[word] common_keys = targetDict.keys() &amp; other_dict summed_values = sum(other_dict[common] for common in common_keys) targetOutput.append(summed_values) There is no point in wrapping the summed values in another list there as there is only ever going to be a single sum. The above gives you a targetOutput list with [2, 2], not [[2], [2]].
answers question: http://stackoverflow.com/q/50565860
type: Answer
upvote count: 4
score: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50565860

http://stackoverflow.com/q/50591308
has title: SNS - Introduce Consumption Delay
type: Question
has body: I have a lambda that transfer data from source s3 bucket to destination s3 bucket. There is a process that pushes message into source s3 bucket. This process sends a notification via SNS after data is pushed to source s3 bucket. A third party verification lambda is triggered once data is pushed into source bucket which validates the data pushed into source bucket. This process can take anywhere between 5-30 mins to complete. My lambda should transfer data from source to destination only after the validation is completed by third party app. They have exposed an api which I can use to determine if validation is complete. Once my lambda receives the message from the topic , it will call the external api if validation is complete. If the validation is not complete , I want to retry after 5 minutes. Can I push the message back into SNS topic and introduce a delay of 5 mins after which it can trigger my lambda again? If this is not possible are there any aws patterns available which can help achieve this without additional coding (and still use lambda for data transfer)?
tagged with: amazon-sqs
downvote count: 0
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/88192231
tagged with: aws-lambda
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90362821
tagged with: python
has comment: http://stackoverflow.com/comment/90362784
answer count: 0
score: 1
tagged with: amazon-sns
has comment: http://stackoverflow.com/comment/88192043
upvote count: 1

http://stackoverflow.com/comment/88234240
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50546154
has text: I'm using the 1.7, the sphinx.ext.napoleon doesn't change anything.

http://stackoverflow.com/q/50659944
type: AnsweredQuestion
tagged with: key-bindings
has answer: http://stackoverflow.com/a/50668264
type: Question
tagged with: tkinter-canvas
has body: I've made a program which draws an oval on click (mouse click=start point, mouse release= end point) as shown in code below, and I'd like to add if condition: when the shift key is pressed midst drawing, it would equalize the coordinates and therefore as a result, a circle (or perfect oval if you wish) will be drawn. from tkinter import * def draw(event): if str(event.type)=='ButtonPress': canvas.old_coords=event.x,event.y elif str(event.type)=='ButtonRelease': x,y=event.x,event.y x1,y1=canvas.old_coords canvas.create_oval(x,y,x1,y1) canvas=Canvas() canvas.pack() canvas.bind('&lt;B1-Motion&gt;',draw) canvas.bind('&lt;ButtonPress-1&gt;',draw) canvas.bind('&lt;ButtonRelease-1&gt;',draw) How could I possibly take in account pressed shift and then draw a circle?
has title: Tkinter - Using multiple key-binds
score: 0
accepted answer: http://stackoverflow.com/a/50668264
answer count: 1
tagged with: python
favorite count: 0
tagged with: tkinter
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/50661925
type: Question
tagged with: pandas
upvote count: 1
has title: Not able to install pandas for python 2.7 on centos
favorite count: 0
answer count: 0
has body: While Installing pandas for python 2.7 getting the below error. copying pandas/tests/io/data/stata5_115.dta -&gt; build/lib.linux-x86_64-2.7/pandas/tests/io/data copying pandas/tests/io/data/test4.xlsx -&gt; build/lib.linux-x86_64-2.7/pandas/tests/io/data copying pandas/tests/io/data/test_converters.xlsm -&gt; build/lib.linux-x86_64-2.7/pandas/tests/io/data copying pandas/tests/io/data/stata1_114.dta -&gt; build/lib.linux-x86_64-2.7/pandas/tests/io/data copying pandas/tests/io/data/stata11_115.dta -&gt; build/lib.linux-x86_64-2.7/pandas/tests/io/data copying pandas/tests/io/data/stata3_114.dta -&gt; build/lib.linux-x86_64-2.7/pandas/tests/io/data copying pandas/tests/io/data/test2.xlsx -&gt; build/lib.linux-x86_64-2.7/pandas/tests/io/data copying pandas/tests/io/data/testskiprows.xlsm -&gt; build/lib.linux-x86_64-2.7/pandas/tests/io/data copying pandas/tests/io/data/blank_with_header.xlsx -&gt; build/lib.linux-x86_64-2.7/pandas/tests/io/data copying pandas/tests/io/data/stata6.csv -&gt; build/lib.linux-x86_64-2.7/pandas/tests/io/data copying pandas/tests/io/data/stata6_113.dta -&gt; build/lib.linux-x86_64-2.7/pandas/tests/io/data copying pandas/tests/io/data/test_types.xlsx -&gt; build/lib.linux-x86_64-2.7/pandas/tests/io/data copying pandas/tests/io/data/test1.xls -&gt; build/lib.linux-x86_64-2.7/pandas/tests/io/data copying pandas/tests/io/data/test_types.xls -&gt; build/lib.linux-x86_64-2.7/pandas/tests/io/data copying pandas/tests/io/data/test_converters.xls -&gt; build/lib.linux-x86_64-2.7/pandas/tests/io/data copying pandas/tests/io/data/stata8_117.dta -&gt; build/lib.linux-x86_64-2.7/pandas/tests/io/data copying pandas/tests/io/data/testdtype.xlsm -&gt; build/lib.linux-x86_64-2.7/pandas/tests/io/data copying pandas/tests/io/data/stata4_117.dta -&gt; build/lib.linux-x86_64-2.7/pandas/tests/io/data copying pandas/tests/io/data/testdtype.xlsx -&gt; build/lib.linux-x86_64-2.7/pandas/tests/io/data copying pandas/tests/io/data/stata15.dta -&gt; build/lib.linux-x86_…
type: UnansweredQuestion
tagged with: pip
tagged with: python
downvote count: 0
score: 1

http://stackoverflow.com/comment/90423994
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50675354
has text: didn't solve my problem even after reinstalling the opencv
score: 0

http://stackoverflow.com/comment/88115173
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50552003
has text: Do you want to do different actions based on what the number is? If so, a better idea might be to - create a map (or even a list) of 'Actions' and use that index rather than trying to do `if XXXX` 100 times. But better if you can explain a bit what you want to do. Because the solution will likely be different (and perhaps shorter too)
type: Comment

http://stackoverflow.com/comment/88278796
comment on: http://stackoverflow.com/a/50633406
type: AnswerComment
score: 0
type: Comment
has text: Try doing that with a list longer than 10 numbers.

http://stackoverflow.com/q/50668191
answer count: 1
downvote count: 0
tagged with: asynchronous
favorite count: 0
upvote count: 2
tagged with: exception
tagged with: python
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/2491819
has body: im trying to check multiple imap login informations asynchronously with aioimaplib. This code works as long as the imap servers are reachable and / or the clients don't time out. What is the correct way to catch the exceptions? Example exception: ERROR:asyncio:Task exception was never retrieved future: &lt;Task finished coro=&lt;BaseEventLoop.create_connection() done, defined at G:\WinPython-3.5.4\python-3.5.4.amd64\lib\asyncio\base_events.py:679&gt; exception=TimeoutError(10060, "Connect call failed ('74.117.114.100', 993)")&gt; Code: account_infos = [ # User Password Server ('user1@web.com', 'password1', 'imap.google.com'), ('user2@web.com', 'password2', 'imap.yandex.com'), ('user3@web.com', 'password3', 'imap.server3.com'), ] class MailLogin: def __init__(self): self.loop = asyncio.get_event_loop() self.queue = asyncio.Queue(loop=self.loop) self.max_workers = 2 async def produce_work(self): for i in account_infos: await self.queue.put(i) for _ in range(max_workers): await self.queue.put((None, None, None)) async def worker(self): while True: (username, password, server) = await self.queue.get() if username is None: break while True: try: s = IMAP4_SSL(server) await s.wait_hello_from_server() r = await s.login(username, password) await s.logout() if r.result != 'NO': print('Information works') except Exception as e: # DOES NOT CATCH print(str(e)) else: break def start(self): try: self.loop.run_until_complete( asyncio.gather(self.produce_work(), *[self.worker() for _ in range(self.max_workers)], loop=self.loop, return_exceptions=True) ) finally: print('Done') if __name__ == '__main__': MailLogin().start()
has answer: http://stackoverflow.com/a/50769113
type: Question
accepted answer: http://stackoverflow.com/a/50769113
tagged with: aio
has title: Python: Aioimaplib catch exceptions

http://stackoverflow.com/comment/88273526
type: Comment
type: QuestionComment
has text: You would have to find all files that end with .txt in that directory, and then have a for loop that reads the file. Here is a way to grab only files with certain extensions in a directory: https://stackoverflow.com/questions/3964681/find-all-files-in-a-directory-with-extension-txt-in-python
score: 0
comment on: http://stackoverflow.com/q/50631741

http://stackoverflow.com/q/50657642
possible better answer: http://stackoverflow.com/a/50657682
has comment: http://stackoverflow.com/comment/88325269
has answer: http://stackoverflow.com/a/50657682
has title: IndexError: list index out of range in while loop
favorite count: 0
has answer: http://stackoverflow.com/a/50657665
tagged with: python
type: AnsweredQuestion
tagged with: list
downvote count: 3
tagged with: loops
upvote count: 1
type: Question
tagged with: indexing
has comment: http://stackoverflow.com/comment/88325385
accepted answer: http://stackoverflow.com/a/50657665
score: -2
has body: I cant get to understand why i`m getting Index Error. at a = array1[item] while item &lt;= n: a = array1[item] t = mid - a l = h_f(t) ab += l if ab &gt; k: item+=1 break ae += h_f(t + 1) - 1 item+=1 n - number of inputed values, item = 0 array1 = [2, 3, 4] Any help?
has comment: http://stackoverflow.com/comment/88325354
answer count: 2

http://stackoverflow.com/comment/88341716
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50656470
has text: Excellent!! Thanks a lot, Anthon

http://stackoverflow.com/comment/88269427
type: QuestionComment
comment on: http://stackoverflow.com/q/50629277
score: 0
type: Comment
has text: Have you tried the latest releases of both Python 2 (2.7.15?) and Libtiff (4.0.9?)? Why not?

http://stackoverflow.com/q/50582519
tagged with: django-views
has body: I am calling a django rest framework get api to create a barcode. Its working fine when I tried to save it as an image. @api_view(['GET']) def mybarcode(request): from elaphe import barcode code = barcode('datamatrix', "sampletext", encoding='utf-8', scale=2, options=dict(columns=24, rows=24), margin=2, data_mode='50bits') code.save("mybarcode.jpg") return Response({'status': True}) This working fine when I call this API as "http://127.0.0.1:9999/api/v1/testbarcode". An image will be created with the name "mybarcode.jpg" and the api return its status as True. But I would like to return the image as the result of this api call. Because I have to include this in a image tag. &lt;img src='http://127.0.0.1:9999/api/v1/testbarcode' /&gt; Is there any way to do this?
has answer: http://stackoverflow.com/a/63569110
has answer: http://stackoverflow.com/a/50583767
has comment: http://stackoverflow.com/comment/88176337
downvote count: 0
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/63562980
favorite count: 0
has comment: http://stackoverflow.com/comment/88175679
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/88175406
has title: Django rest framework - return image as response
has comment: http://stackoverflow.com/comment/88174780
type: UnansweredQuestion
score: 1
tagged with: django
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50584225

http://stackoverflow.com/a/63889041
has body: Since this questions still turns up in search, here is 2020 update version of Python3 HTTP2-compatible script to send push notifications.
type: Answer
answers question: http://stackoverflow.com/q/50599003
score: 0

http://stackoverflow.com/comment/88299898
type: Comment
comment on: http://stackoverflow.com/q/50567516
has text: @Uvar. I updated R to 3.5.0. Reinstalled ggplot2. Rerun the installation of ggburst. The error is still the same with ggplot part omitted. Here is the complete output. https://pastebin.com/qNQEEKam
score: 0
type: QuestionComment

mysql
tags question: http://stackoverflow.com/q/50652587
tags question: http://stackoverflow.com/q/50691759
tags question: http://stackoverflow.com/q/50657350
tags question: http://stackoverflow.com/q/50547017
tags question: http://stackoverflow.com/q/50583738
tags question: http://stackoverflow.com/q/50657368
tags question: http://stackoverflow.com/q/50651684
tags question: http://stackoverflow.com/q/50609824
tag name: mysql
tags question: http://stackoverflow.com/q/50647919
tags question: http://stackoverflow.com/q/50605801
tags question: http://stackoverflow.com/q/50622013
tags question: http://stackoverflow.com/q/50577413
tags question: http://stackoverflow.com/q/50544600
tags question: http://stackoverflow.com/q/50605055
tags question: http://stackoverflow.com/q/50686065
tags question: http://stackoverflow.com/q/50592213
tags question: http://stackoverflow.com/q/50619237
tags question: http://stackoverflow.com/q/50591662
tags question: http://stackoverflow.com/q/50557234
tags question: http://stackoverflow.com/q/50609009
tags question: http://stackoverflow.com/q/50659017
tags question: http://stackoverflow.com/q/50614758
tags question: http://stackoverflow.com/q/50626573
tags question: http://stackoverflow.com/q/50613173
tags question: http://stackoverflow.com/q/50551937
tags question: http://stackoverflow.com/q/50624255
type: Tag
tags question: http://stackoverflow.com/q/50552234
tags question: http://stackoverflow.com/q/50611599
tags question: http://stackoverflow.com/q/50608937
tags question: http://stackoverflow.com/q/50677576
tags question: http://stackoverflow.com/q/50620531
tags question: http://stackoverflow.com/q/50560801
tags question: http://stackoverflow.com/q/50597816
tags question: http://stackoverflow.com/q/50587621
tags question: http://stackoverflow.com/q/50625183
tags question: http://stackoverflow.com/q/50634875
tags question: http://stackoverflow.com/q/50656093
tags question: http://stackoverflow.com/q/50590578
tags question: http://stackoverflow.com/q/50616051
tags question: http://stackoverflow.com/q/50603329
tags question: http://stackoverflow.com/q/50638837
tags question: http://stackoverflow.com/q/50667582
tags question: http://stackoverflow.com/q/50641849

http://stackoverflow.com/q/50662998
has comment: http://stackoverflow.com/comment/88350205
downvote count: 0
answer count: 0
score: 1
has body: I have a function that builds a list from a very large file. That list is used several times at various stages. Obviously, it only needs to runs once and running it more would waste time. My question is how to have a function run once and return the list but when that function is called again it simply returns the list and doesn't run again. I'd rather not just make the list a global variable. I know I could use a while loop to remember it as well but that just seems wasteful. I assume there is a more elegant way of accomplishing what I'm looking for. Am I looking to use decorators or singletons (not sure if they are in python). Example: state_ab = ['OH', "test", 'CO'] def build_US_state_list(): state_dict = [] for state in pycountry.subdivisions: if state.country_code == 'US': state_dict.append({'name': state.name, 'code': state.code[3:]}) return state_dict def get_US_state_list(): try: return state_dict except: state_dict = build_US_state_list() print('ran') return state_dict def identify_and_add_US_states(): states = get_US_state_list() print(states) for i in range(0, len(state_ab)): for state in states: if state_ab[i] == state["code"]: return state["code"]
has comment: http://stackoverflow.com/comment/88336284
type: Question
linked to: http://stackoverflow.com/q/1988804
has comment: http://stackoverflow.com/comment/88343317
has comment: http://stackoverflow.com/comment/88336254
has comment: http://stackoverflow.com/comment/88350150
has title: [Python]Function that runs once then remembers result when called again
has comment: http://stackoverflow.com/comment/88336139
upvote count: 1
tagged with: function
has comment: http://stackoverflow.com/comment/88336261
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88336227
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88336210
has comment: http://stackoverflow.com/comment/88337779
tagged with: python
duplicate of: http://stackoverflow.com/q/1988804
has comment: http://stackoverflow.com/comment/88336240

http://stackoverflow.com/q/50550772
tagged with: matplotlib
downvote count: 0
type: UnansweredQuestion
has title: How to plot multiple plots on same row?
tagged with: pandas
has body: I am using the classic kaggle house price dataset. I want to plot each of the feature columns (bedrooms, bathrooms, sqft_living etc.) against the price target to check for any correlation, but I want to have say 3 or 4 plots on each row to make the plot more compact. What I have done so far: import pandas as pd import matplotlib.pylab as plt import seaborn as sns; sns.set_context('poster') sns.set_style('darkgrid') df = pd.read_csv('kc_house_data.csv') cols = [i for i in list(df.columns) if i not in ['id','price']] for col in cols: fig, ax = plt.subplots(figsize=(12,8)) df.plot(kind='scatter', x=col, y='price', ax=ax, s=10, alpha=0.5) plt.show() So, I am using the inbuilt pandas plotting functionality, but this plots each figure on a new line. What I would like to have is something like the pandas scatter matrix plot where multiple (in this case 4) plots appear on one line. (I don't need to plot the distribution along the diagonal as shown below). How can I have multiple plots in one row using the pandas scatter_matrix functionality or some other python plotting functionality? Nice to haves: Labeled axes Correlation between each feature and price displayed on each plot
linked to: http://stackoverflow.com/q/22483588
score: 1
favorite count: 0
type: Question
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50550870
answer count: 1
tagged with: plot
duplicate of: http://stackoverflow.com/q/22483588

http://stackoverflow.com/q/50574339
has title: Program stopping when running sklearn KNN prediction
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88162259
has comment: http://stackoverflow.com/comment/88158086
has body: I'm working on a Recommendation System and I have to test the K-Nearest Neighbors method to fit and predict my results. My program runs perfectly until the predict_proba # Create model model = KNeighborsClassifier(n_neighbors=5) # Fit model model.fit(X_train_sparse, y_train) # Predict antitrain_predictions_probs = model.predict_proba(X_antitrain_sparse) after this line the program simply stops without any error. It also happens when using model.predict(X_antitrain_sparse). Anyone can help? Thank you!
has comment: http://stackoverflow.com/comment/88169688
downvote count: 0
tagged with: scikit-learn
favorite count: 0
tagged with: knn
has comment: http://stackoverflow.com/comment/88200295
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/88158211

http://stackoverflow.com/a/50650532
has comment: http://stackoverflow.com/comment/88332926
has comment: http://stackoverflow.com/comment/88502580
has comment: http://stackoverflow.com/comment/88332836
upvote count: 10
type: Answer
has body: This is a partial answer to my own question. I'm saying partial, because I do believe there is a better way. Building on this post http://swig.10945.n7.nabble.com/Pass-a-Swig-wrapped-C-class-to-embedded-Python-code-td8812.html I generated the swig runtime header, as described here, section 15.4: http://www.swig.org/Doc2.0/Modules.html#Modules_external_run_time Including the generated header in the C++ code above, allow the following code to be written: PyObject* pObj = SWIG_NewPointerObj((void*)&amp;obj, SWIG_TypeQuery("_p_MyClass"), 0 ); This code is using information from the Swig python wrap source files, namely the "swig" name of the type MyClass, i.e. _p_MyClass. With the above PyObject* as an argument to the PyObject_CallObject function, the python execute() function in the code above executes fine, and the Python code, using the generated python module, do have proper access to the MyClass objects internal data. This is great. Although the above code illustrate how to pass, and retrieve data between C++ and Python in a quite simple fashion, its not ideal, in my opinion. The usage of the swig header file in the C++ code is really not that pretty, and in addition, it requires a user to "manually" look into swig generated wrapper code in order to find the "_p_MyClass" code. There must be a better way!? Perhaps something should be added to the swig interface file in order to get this looking nicer?
downvote count: 0
score: 10
answers question: http://stackoverflow.com/q/50613010

http://stackoverflow.com/a/50567515
has comment: http://stackoverflow.com/comment/88146094
type: Answer
has comment: http://stackoverflow.com/comment/88164654
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88145867
has comment: http://stackoverflow.com/comment/88145078
has comment: http://stackoverflow.com/comment/88145854
has comment: http://stackoverflow.com/comment/88146008
upvote count: 2
has body: Use list comprehension for list of DataFrames with concat and transpose: #add /*.* for read all files currentdir = 'path/*.*' L = [] #loop by files for file in glob.glob(currentdir): print (file) s = pd.read_csv(file, sep='|', header=None)[0] if (s.astype(str).str.strip().str.contains('\s+').any()): #print (s) df = s.str.rsplit(n=1, expand=True) df.columns = ['a','b'] L.append(df.set_index('a')['b']) df = pd.concat(L, axis=1, keys=range(len(L))).T
has comment: http://stackoverflow.com/comment/88145418
has comment: http://stackoverflow.com/comment/88146056
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50567440
has comment: http://stackoverflow.com/comment/88145483
has comment: http://stackoverflow.com/comment/88145811
accepted answer of: http://stackoverflow.com/q/50567440
has comment: http://stackoverflow.com/comment/88145654

http://stackoverflow.com/q/50645836
type: Question
has comment: http://stackoverflow.com/comment/88305395
accepted answer: http://stackoverflow.com/a/50646039
score: 0
answer count: 2
has title: Is there a better way to format these elements_by_id?
tagged with: xpath
has answer: http://stackoverflow.com/a/50664216
tagged with: python
has comment: http://stackoverflow.com/comment/88302340
possible better answer: http://stackoverflow.com/a/50664216
type: AnsweredQuestion
has body: I have the following code I'm repeating and wondered if anyone had some advise as to how to write this more efficiently: def get_description(links): for link in links: description = driver.find_elements_by_id('some-id') description = [x.text for x in description] description = " ".join(description) title = driver.find_elements_by_id('different-id') title = [x.text for x in title] title = " ".join(title) company = driver.find_elements_by_id('another-different-id') company = [x.text for x in company] company = " ".join(company) location = driver.find_elements_by_id('location-id') location = [x.text for x in location] location = " ".join(location)+ " United Kingdom" salary = driver.find_elements_by_xpath("//*[@id='randomly generated id']/div[3]/span[1]") salary = [x.text for x in salary] salary = " ".join(salary) I tried defining a separate function called 'element_parse' as follows: def parse_element(x) x = [y.text for y in x] x = " ".join(x) then calling this the main function by doing: description = driver.find_elements_by_id('some-id') parse_element(description) But alas! No joy. Not a show stopper as I've got it working but feel like there's a lot of repetition in here I want to clean up!
tagged with: selenium
tagged with: web-scraping
has answer: http://stackoverflow.com/a/50646039

http://stackoverflow.com/q/50651619
upvote count: 2
downvote count: 1
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50651658
type: Question
tagged with: functional-programming
has title: Is itertools.combinations() deterministic?
accepted answer: http://stackoverflow.com/a/50651658
answer count: 1
tagged with: python
favorite count: 0
has body: Is the order of items obtained from itertools.combinations() deterministic? I am currently writing a script which produces an excessively large number of objects using itertools.combinations, large enough that I can't retain it all in memory. For each combination, there is a function which returns a value that I store in a numpy array (since those are fairly memory efficient). I have just barely enough memory to store all of those floats. I then iterate over those floats, and if it's an index of interest, I run itertools.combinations again with a counter variable to access the combination that produced that result (which only takes a few seconds). I have tested this with various smaller datasets for which I have enough memory, and the entries all are the same in those cases, but I am worried that this is not a "safe" approach to doing what I want.
tagged with: combinatorics

http://stackoverflow.com/comment/88218772
has text: `<=` is a conditional statement which is suppose to return boolean value. what other answer do you expect?
type: Comment
comment on: http://stackoverflow.com/q/50604684
score: 0
type: QuestionComment

django
tags question: http://stackoverflow.com/q/50582137
tags question: http://stackoverflow.com/q/50620564
tags question: http://stackoverflow.com/q/50648312
tags question: http://stackoverflow.com/q/50642661
tags question: http://stackoverflow.com/q/50591662
tags question: http://stackoverflow.com/q/50574024
tags question: http://stackoverflow.com/q/50645519
tags question: http://stackoverflow.com/q/50603365
tags question: http://stackoverflow.com/q/50669185
tags question: http://stackoverflow.com/q/50668190
tags question: http://stackoverflow.com/q/50689328
tags question: http://stackoverflow.com/q/50681897
tags question: http://stackoverflow.com/q/50546084
tags question: http://stackoverflow.com/q/50605193
tags question: http://stackoverflow.com/q/50544151
tags question: http://stackoverflow.com/q/50642728
tags question: http://stackoverflow.com/q/50678758
tags question: http://stackoverflow.com/q/50676859
tags question: http://stackoverflow.com/q/50663584
tags question: http://stackoverflow.com/q/50658035
tags question: http://stackoverflow.com/q/50657196
tags question: http://stackoverflow.com/q/50630464
tags question: http://stackoverflow.com/q/50652057
tags question: http://stackoverflow.com/q/50568252
tags question: http://stackoverflow.com/q/50680125
tags question: http://stackoverflow.com/q/50590666
tags question: http://stackoverflow.com/q/50659964
tags question: http://stackoverflow.com/q/50599003
tags question: http://stackoverflow.com/q/50614189
tags question: http://stackoverflow.com/q/50691608
tags question: http://stackoverflow.com/q/50574940
tags question: http://stackoverflow.com/q/50651920
tags question: http://stackoverflow.com/q/50562761
tags question: http://stackoverflow.com/q/50678420
tags question: http://stackoverflow.com/q/50572611
tags question: http://stackoverflow.com/q/50635038
tags question: http://stackoverflow.com/q/50636257
tags question: http://stackoverflow.com/q/50625459
tags question: http://stackoverflow.com/q/50653892
tags question: http://stackoverflow.com/q/50675943
tags question: http://stackoverflow.com/q/50563459
tags question: http://stackoverflow.com/q/50583219
tags question: http://stackoverflow.com/q/50582912
tags question: http://stackoverflow.com/q/50614266
tags question: http://stackoverflow.com/q/50693780
tags question: http://stackoverflow.com/q/50670096
tags question: http://stackoverflow.com/q/50636884
tags question: http://stackoverflow.com/q/50692214
tags question: http://stackoverflow.com/q/50643808
tags question: http://stackoverflow.com/q/50663971
tags question: http://stackoverflow.com/q/50670643
type: Tag
tags question: http://stackoverflow.com/q/50551946
tags question: http://stackoverflow.com/q/50546689
tags question: http://stackoverflow.com/q/50558333
tags question: http://stackoverflow.com/q/50621262
tags question: http://stackoverflow.com/q/50669774
tags question: http://stackoverflow.com/q/50584249
tags question: http://stackoverflow.com/q/50660248
tags question: http://stackoverflow.com/q/50677301
tags question: http://stackoverflow.com/q/50655843
tags question: http://stackoverflow.com/q/50546244
tags question: http://stackoverflow.com/q/50669942
tags question: http://stackoverflow.com/q/50636661
tags question: http://stackoverflow.com/q/50585110
tags question: http://stackoverflow.com/q/50649919
tags question: http://stackoverflow.com/q/50613957
tags question: http://stackoverflow.com/q/50594779
tags question: http://stackoverflow.com/q/50661037
tags question: http://stackoverflow.com/q/50679343
tags question: http://stackoverflow.com/q/50672941
tags question: http://stackoverflow.com/q/50679857
tags question: http://stackoverflow.com/q/50579662
tags question: http://stackoverflow.com/q/50573276
tags question: http://stackoverflow.com/q/50637117
tags question: http://stackoverflow.com/q/50631477
tags question: http://stackoverflow.com/q/50556752
tags question: http://stackoverflow.com/q/50625057
tags question: http://stackoverflow.com/q/50682248
tags question: http://stackoverflow.com/q/50638300

http://stackoverflow.com/q/50683833
type: AnsweredQuestion
score: 4
has body: In Python, we have the re.VERBOSE argument that allows us to nicely format regex expressions and include comments, such as import re ric_index = re.compile(r'''( ^(?P&lt;delim&gt;\.) # delimiter "." (?P&lt;root&gt;\w+)$ # Root Symbol, at least 1 character )''',re.VERBOSE) Is there something similar in C#?
downvote count: 1
type: Question
tagged with: c#
answer count: 2
upvote count: 5
has answer: http://stackoverflow.com/a/50684227
has title: C# Regex "Verbose" like in Python
possible better answer: http://stackoverflow.com/a/50684032
tagged with: regex
favorite count: 0
has answer: http://stackoverflow.com/a/50684032
accepted answer: http://stackoverflow.com/a/50684227
tagged with: python

bitcoin
tags question: http://stackoverflow.com/q/50553749
tag name: bitcoin
type: Tag

http://stackoverflow.com/comment/88296073
comment on: http://stackoverflow.com/q/50642819
score: 0
type: Comment
type: QuestionComment
has text: I'd be surprised if that's your output, I'd expect it to end in an OR, you also appear to be missing at least one bracket

http://stackoverflow.com/q/50667401
has comment: http://stackoverflow.com/comment/88345031
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88344879
tagged with: python
has comment: http://stackoverflow.com/comment/88344912
tagged with: namespaces
has comment: http://stackoverflow.com/comment/88345387
has comment: http://stackoverflow.com/comment/88344840
type: Question
has body: I am quite confused with LEGB rule. At line 7, I was expecting 4 to be printed but it keeps printing 5. I am aware of the fact that whenever the bar() method is called, it looks for variable x in foo()'s scope since it doesn't have x declared in the local scope(bar()'s scope). but when the bar() method is called for the second time, It prints 5 rather than 4. Why are the results from first bar() and second bar() different in terms of LEGB rule? Here is the following code: def foo(): x=4 def bar(): print(x) # Accesses x from foo's scope bar() # Prints 4 x=5 bar() # Prints 5 &lt;---- Line 7 foo()
tagged with: variables
has comment: http://stackoverflow.com/comment/88345097
has comment: http://stackoverflow.com/comment/88345129
tagged with: scope
score: 0
has comment: http://stackoverflow.com/comment/88345131
has title: Is there any special order of finding variables in Python?

http://stackoverflow.com/q/50660092
tagged with: keras
has comment: http://stackoverflow.com/comment/88331559
has comment: http://stackoverflow.com/comment/88331124
has body: I am new to Keras and I am trying to make a comparison between Sequential and functional classifications using images(64x64, 1 channel), this is my model(sequential): x_pos_train = x_pos[int(x_pos.shape[0]* .20):] #shape(20,1,64,64) x_pos_test = x_pos[:int(x_pos.shape[0]* .20)] #shape(5,1,64,64) x_pos_noisy = x_pos_train + 0.05 * np.random.normal(loc=0., scale=1., size=x_pos_train.shape) #(20, 1, 64, 64) #----------------------------------------------------------------- from keras.models import Sequential from keras.layers import Dense, Activation, Conv2D, MaxPooling2D, UpSampling2D from keras import backend as K #image dim ordering in conv2d won't work K.set_image_dim_ordering('th') seqmodel = Sequential() seqmodel.add(Conv2D(32, (3,3), activation='relu', padding='same', input_shape=(1,64,64))) seqmodel.add(MaxPooling2D(pool_size=(2, 2), padding='same')) seqmodel.add(Conv2D(32, (3,3), activation='relu')) seqmodel.add(UpSampling2D((2, 2))) seqmodel.add(Conv2D(1, (3,3), activation='sigmoid')) seqmodel.compile(optimizer='adadelta', loss='binary_crossentropy') seqmodel.fit(x_pos_noisy, x_pos_train, epochs=10, batch_size=32, shuffle=True, validation_split=.20) x_pos is an array of images reshaped for keras (channels, rows, cols) The source is here: How to denoise images with neural networks. The problem is that when I run it, it throws an error at seqmodel.fit: ValueError: Error when checking target: expected conv2d_3 to have shape (1,58,58), but got array with shape (1,64,64) Since the original code wasn't working, I've made a few changes to fit my needs. Edit 1: Sequential Summary Image I know that the target(x_pos_train) is different from the output layer, but I want to know why is this happening, since the code is supposed to work.
has comment: http://stackoverflow.com/comment/88331567
tagged with: python
has title: ValueError: Error when checking target: expected conv2d_3 to have shape (1,58,58), but got array with shape (1,64,64)
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50660855
type: Question
has answer: http://stackoverflow.com/a/50660855
has comment: http://stackoverflow.com/comment/88330356
has comment: http://stackoverflow.com/comment/88331262
score: 0
answer count: 1

http://stackoverflow.com/q/50543358
linked to: http://stackoverflow.com/q/1373164
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/50543392
downvote count: 4
linked to: http://stackoverflow.com/q/3182183
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50543432
tagged with: oop
has comment: http://stackoverflow.com/comment/88097865
duplicate of: http://stackoverflow.com/q/285061
has title: Python: Create 50 objects using a for loop
type: Question
linked to: http://stackoverflow.com/q/2933470
has comment: http://stackoverflow.com/comment/88097824
tagged with: for-loop
has comment: http://stackoverflow.com/comment/88097813
tagged with: python-3.5
has body: I am new to python recently I am working on a project in I created a class:- class foo(): def __init__(self, name): self.name = name I want to create 50 objects of this class which sholud be named as obj1, obj2, obj3,..., obj50 I am trying to create these classes like for i in range(1,51): obj + i = foo(i) So that 50 objects like obj1, obj2, obj3,..., obj50 are created with names as 1, 2, 3,...,50. But for some reason this is not working for me. Can anyone tell what am I doing wrong here. I know that I can use a list to store the objects but for some reason I would like to do it this way. Any help is highly aprreciated.
linked to: http://stackoverflow.com/q/285061
possible better answer: http://stackoverflow.com/a/50543432
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/50543427
has comment: http://stackoverflow.com/comment/88097826
duplicate of: http://stackoverflow.com/q/1373164
accepted answer: http://stackoverflow.com/a/50543392
favorite count: 0
tagged with: python-3.x

global
type: Tag
tags question: http://stackoverflow.com/q/50592479
tag name: global
tags question: http://stackoverflow.com/q/50604799
tags question: http://stackoverflow.com/q/50559252
tags question: http://stackoverflow.com/q/50662164
tags question: http://stackoverflow.com/q/50626625
tags question: http://stackoverflow.com/q/50634086

http://stackoverflow.com/a/50693255
type: AcceptedAnswer
type: Answer
has body: With error you need to pass another parameter in the function which will give you array of messages printed in the shell script. PythonShell.run('test.py', options, function (err, results) { if (err) throw err; // results is an array consisting of messages collected during execution console.log('results: %j', results); }); More: https://www.npmjs.com/package/python-shell
accepted answer of: http://stackoverflow.com/q/50693158
answers question: http://stackoverflow.com/q/50693158
score: 0

http://stackoverflow.com/a/50591642
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88192633
has body: You can use the subprocess module to run commands from your script: subprocess.run(cmd.split()) The run() function also takes parameters like shell=True if you want to keep the environment variables or stdout=subprocess.PIPE if you want to retreive the output of the command. Honestly, just take a look at the docs ;) EDIT: as Alan mentionned, the shell=True option is often considered not desirable, as you cannot be sure which shell is used by the system. More details here.
upvote count: 1
has comment: http://stackoverflow.com/comment/88195146
answers question: http://stackoverflow.com/q/50591517
type: Answer

http://stackoverflow.com/q/50611296
has title: Pandas create dataframe from distance matrix with multiindex
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50611794
tagged with: multi-index
type: Question
linked to: http://stackoverflow.com/q/14507794
has answer: http://stackoverflow.com/a/50611794
score: 0
tagged with: pandas
has body: I have two kinds of objects - F and P - with tags on them and I want to calculate the distances between each tag that belongs to different category and then construct a dataframe with one row per pair of tags from different categories and their distance. The code below seems to do what I want: import itertools import operator import numpy as np import pandas as pd from scipy.spatial.distance import cdist i = np.sqrt(2) j = 2 * i # dicts mapping category and tag to x, y coordinates timeframe_f = {('F1', 'tag1f1'): (0, 0), ('F2', 'tag1f2'): (-i, -i)} timeframe_p = {('B1', 'tag1b1'): (i, i), ('B2', 'tag1b2'): (j, j), ('B2', 'tag2b2'): (2 * j, 2 * j)} # calculate the distances distances = cdist(np.array(list(timeframe_f.values())), np.array(list(timeframe_p.values())), 'sqeuclidean') print('distances:\n', distances, '\n') # here is the matrix with the MultiIndex distances_matrix = pd.DataFrame(data=distances, index=pd.MultiIndex.from_tuples( timeframe_f.keys(), names=['F', 'Ftags']), columns=pd.MultiIndex.from_tuples( timeframe_p.keys(), names=['P', 'Ptags']), ) print('distances_matrix:\n', distances_matrix, '\n') # hacky construction of the data frame index = list(map(lambda x: operator.add(*x), ( itertools.product(timeframe_f.keys(), timeframe_p.keys())))) # print(index) multi_index = pd.MultiIndex.from_tuples(index) distances_df = pd.DataFrame(data=distances.ravel(), index=multi_index, ).reset_index() print('distances_df:\n', distances_df) It prints: distances: [[ 4. 16. 64.] [ 16. 36. 100.]] distances_matrix: P B1 B2 Ptags tag1b1 tag1b2 tag2b2 F Ftags F1 tag1f1 4.0 16.0 64.0 F2 tag1f2 16.0 36.0 100.0 distances_df: level_0 level_1 level_2 level_3 0 0 F1 tag1f1 B1 tag1b1 4.0 1 F1 tag1f1 B2 tag1b2 16.0 2 F1 tag1f1 B2 tag2b2 64.0 3 F2 tag1f2 B1 tag1b1 16.0 4 F2 tag1f2 B2 tag1b2 36.0 5 F2 tag1f2 B2 tag2b2 100.0 but I would like to find a way to do this directly using the distances_matrix. I had a look at various other questions as: How to flatten a hierarchical index in …
answer count: 1
linked to: http://stackoverflow.com/q/40745981
tagged with: python

http://stackoverflow.com/comment/88346706
has text: Possible duplicate of [Convert date format python](https://stackoverflow.com/questions/10541640/convert-date-format-python)
comment on: http://stackoverflow.com/q/50668190
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/50613383
score: 3
has comment: http://stackoverflow.com/comment/88238491
answer count: 0
has comment: http://stackoverflow.com/comment/88237824
upvote count: 3
has comment: http://stackoverflow.com/comment/88236995
tagged with: stdout
has title: Python 3: Why in my case print (..., end=" "， flush=True) not working for output-overwriting?
has comment: http://stackoverflow.com/comment/88240669
has comment: http://stackoverflow.com/comment/88238563
linked to: http://stackoverflow.com/q/43477879
type: Question
has comment: http://stackoverflow.com/comment/88237518
has comment: http://stackoverflow.com/comment/88238452
has comment: http://stackoverflow.com/comment/88236740
downvote count: 0
has comment: http://stackoverflow.com/comment/88238503
tagged with: shell
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88236629
has comment: http://stackoverflow.com/comment/88240871
tagged with: terminal
has comment: http://stackoverflow.com/comment/88238582
has comment: http://stackoverflow.com/comment/88236706
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88240815
has comment: http://stackoverflow.com/comment/88238748
has body: I tried to update percent on the same line or the same two line by using print , rather than printing over and over again. I have already found some approaches for flush output on one line， but no one for multilines. Below is my code, But they are not working as expected, Could someone help me? # refresh in one line for i in range(10): print("Task A complete %d, Task B complete %d \n" % (i, i), end=" ", flush=True) # refresh in two line for j in range(10): print("Task A complete %d \n" % j, end=" ", flush=True) print("Task B complete %d \n" % j, end=" ", flush=True) Thank you all in advance Update: with code # refresh on one line for i in range(1000000000): print("Task A complete %d" %i, "Task B complete %d" %i, end='\r', flush=True) get output like: Task A complete 994 Task B complete 993 But How can I break this line in two lines like: Task A complete 994 Task B complete 993
tagged with: python

http://stackoverflow.com/a/51123558
type: Answer
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50607804
has body: What do you think about indexing your database queries in a dict, by their ascii equivilent? Assumeing there is only one forms of an ascii key: def ascii_word(word): accents=(("á","a"), ("é","e"), ("í","i"), ("ó","o"), ("ú","u"), ("ü","u"), ("ñ","n")) for acc in accents: word=word.replace(acc[0],acc[1]) return word query_result = ["Administración", "Administracion", "si", "sí", "hola"] filtered_dict={} for s in query_result: ascii=ascii_word(s) if ascii in filtered_dict.keys(): if s!=ascii: filtered_dict[ascii] = s else: filtered_dict[ascii] = s result=list(filtered_dict.values()) print(result) This prints to ['Administración', 'sí', 'hola']

http://stackoverflow.com/comment/94138667
type: AnswerComment
comment on: http://stackoverflow.com/a/50551250
type: Comment
has text: If I save the weights and biases on python 3.6 is it possible to load them on python 2.7?
score: 0

http://stackoverflow.com/comment/88110776
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50549801
has text: This is the kind of solution you want to use @KatarinaAlves. Of course you'll not write all the usernames by hand. But each time your loop will match a user, add it to the list

http://stackoverflow.com/comment/88200201
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50583310
has text: That was what I was looking for Green Cell- THANK YOU!

http://stackoverflow.com/q/50689082
has comment: http://stackoverflow.com/comment/88417252
favorite count: 0
has answer: http://stackoverflow.com/a/56583204
has comment: http://stackoverflow.com/comment/88417462
has comment: http://stackoverflow.com/comment/88422239
score: 32
has title: to_sql pyodbc count field incorrect or syntax error
has answer: http://stackoverflow.com/a/50706219
tagged with: python
tagged with: pyodbc
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88387902
downvote count: 0
has answer: http://stackoverflow.com/a/69299837
has comment: http://stackoverflow.com/comment/88414430
has comment: http://stackoverflow.com/comment/88421184
has comment: http://stackoverflow.com/comment/88392010
type: Question
has answer: http://stackoverflow.com/a/61905397
upvote count: 32
tagged with: sql-server
possible better answer: http://stackoverflow.com/a/69299837
has body: I am downloading Json data from an api website and using sqlalchemy, pyodbc and pandas' to_sql function to insert that data into a MSSQL server. I can download up to 10000 rows, however I have to limit the chunksize to 10 otherwise I get the following error: DBAPIError: (pyodbc.Error) ('07002', '[07002] [Microsoft][SQL Server Native Client 11.0]COUNT field incorrect or syntax error (0) (SQLExecDirectW)') [SQL: 'INSERT INTO [TEMP_producing_entity_details] There are around 500 Million rows to download, it's just crawling at this speed. Any advice on a workaround? Thanks,
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50706219

http://stackoverflow.com/a/50571844
answers question: http://stackoverflow.com/q/50571537
type: Answer
score: 3
upvote count: 3
has body: You can use loc with idxmax with both your original df and your inverted df. This will yield the index of your first and last True values. Just set the different indexes to False afterwards. For example: Setup z = sio("""i v FA154 False FA155 False FA155 True FA155 True FA155 True FA155 True FA155 True FA155 False FA156 False FA156 True FA156 False FA156 False FA156 True""") df = pd.read_table(z, delim_whitespace=True) i v 0 FA154 False 1 FA155 False 2 FA155 True 3 FA155 True 4 FA155 True 5 FA155 True 6 FA155 True 7 FA155 False 8 FA156 False 9 FA156 True 10 FA156 False 11 FA156 False 12 FA156 True idxmax() Which is the same thing as getting your df and using reset_index. Then, get list of indexes for you first (v1) and last (v2) True values: v1 = df.groupby("i").v.idxmax().values v2 = df[::-1].groupby("i").v.idxmax().values And use your logic: df.loc[v1, "v"] = True & df.loc[v1, "v"] df.loc[v2, "v"] = True & df.loc[v2, "v"] df.loc[~df.index.isin(np.concatenate([v1,v2])), "v"] = False The idea behind using & is not to accidentally set any False values to True. Result: >>> df.set_index("i") v i FA154 False FA155 False FA155 True FA155 False FA155 False FA155 False FA155 True FA155 False FA156 False FA156 True FA156 False FA156 False FA156 True
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50571537

http://stackoverflow.com/comment/88434121
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/172554/discussion-between-san-and-jezrael).
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50696442

cryptocurrency
tags question: http://stackoverflow.com/q/50547610
type: Tag
tag name: cryptocurrency

http://stackoverflow.com/q/50620422
has comment: http://stackoverflow.com/comment/88273100
score: 1
tagged with: linear-algebra
has comment: http://stackoverflow.com/comment/88271961
has comment: http://stackoverflow.com/comment/88289702
has comment: http://stackoverflow.com/comment/88273183
has comment: http://stackoverflow.com/comment/88276741
type: Question
has body: I am looking for help since it seems I can't find any solutions. The task I am interested in is to diagonalize (large) matrices that depend on a parameter (let's call it m). I first did the calculations on my Mac laptop by using a simple for loop and it seems to use all the availbale cores (4) by default. But now I want to do the same thing on my Linux machine (Ubuntu 18.04) with 16 cores but due to the GIL, the program only uses one core. First question, is the difference coming from the Mac Python interpreter or the linear algebra libraries used by numpy/scipy that are automatically parallelized on Mac and not on Linux? For the moment, I didn't look into the library (LAPACK, BLAS) problem. Then, using Python's multiprocessing, I have no problems doing it but where I am stuck is the data structure. Indeed, for all these matrices, I need both the eigenvalues and eigenvectors (and the m label but the order of inputs is automatically kept) but due to the structure of pool.map (or pool.starmap in the case of multiple arguments) I can't seem to find the most efficient way of collecting the whole set of eigenvalues and eigenvectors. Do you have any idea of how to do it or any good reference? I would appreciate help on this BLAS/LAPACK issue too. Thanks in advance, PS : see below for a naive code sample. def Diagonalize(m): Mat = np.array([[0, m+1],[m+1, 0]]) eigenvalues, eigenvectors = np.linalg.eigh(Mat) return list([eigenvalues, eigenvectors]) # using list() was one of my attempts Nprocesses = 4 # or whatever number if __name__ == '__main__': with Pool(processes = Nprocesses) as pool: pool.map(Diagonalize, m_values) # EDIT m_values being whatever list
tagged with: python-multiprocessing
linked to: http://stackoverflow.com/q/17468054
linked to: http://stackoverflow.com/q/26511430
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88273031
tagged with: data-structures
favorite count: 0
has comment: http://stackoverflow.com/comment/88289849
has comment: http://stackoverflow.com/comment/88304506
has comment: http://stackoverflow.com/comment/88273146
has title: Python multiprocessing diagonalization
tagged with: python
has comment: http://stackoverflow.com/comment/88273642
has comment: http://stackoverflow.com/comment/88277420
linked to: http://stackoverflow.com/q/25004564
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50646990
upvote count: 1
has comment: http://stackoverflow.com/comment/88272844
has comment: http://stackoverflow.com/comment/88273495

http://stackoverflow.com/q/50618993
has comment: http://stackoverflow.com/comment/88249852
tagged with: word2vec
has answer: http://stackoverflow.com/a/53975516
has comment: http://stackoverflow.com/comment/88251352
has comment: http://stackoverflow.com/comment/88248152
tagged with: google-news
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88248920
score: 2
has comment: http://stackoverflow.com/comment/88249085
downvote count: 0
favorite count: 0
has body: I want to get word embeddings for the words in a corpus. I decide to use pretrained word vectors in GoogleNews by gensim library. But my corpus contains some words that are not in GoogleNews words. for these missing words, I want to use arithmatic mean of n most similar words to it in GoggoleNews words. First I load GoogleNews and check that the word "to" is in it? #Load GoogleNews pretrained word2vec model model=word2vec.KeyedVectors.Load_word2vec_format("GoogleNews-vectors-negative33.bin",binary=True) print(model["to"]) I receive an error: keyError: "word 'to' not in vocabulary" is it possible that such a large dataset doesn't have this word? this is true also for some other common word like "a"! For adding missing words to word2vec model,first I want to get indices of words that are in GoogleNews. for missing words I have used index 0. #obtain index of words word_to_idx=OrderedDict({w:0 for w in corpus_words}) word_to_idx=OrderedDict({w:model.wv.vocab[w].index for w in corpus_words if w in model.wv.vocab}) then I calculate the mean of embedding vectors of most similar words to each missing word. missing_embd={} for key,value in word_to_idx.items(): if value==0: similar_words=model.wv.most_similar(key) similar_embeddings=[model.wv[a[0]] for a in similar_words] missing_embd[key]=mean(similar_embeddings) And then I add these news embeddings to word2vec model by: for word,embd in missing_embd.items(): # model.wv.build_vocab(word,update=True) model.wv.syn0[model.wv.vocab[word].index]=embd There is an un-consistency. When I print missing_embed, it's empty. As if there were not any missing words. But when I check it by this: for w in tokens_lower: if(w in model.wv.vocab)==False: print(w) print("***********") I found a lot of missing words. Now, I have 3 questions: 1- why missing_embed is empty while there are some missing words? 2- Is it possible that GoogleNews doesn't have words like "to"? 3- how can I append new embeddings to word2vec model? I used build_vocab and sy…
has comment: http://stackoverflow.com/comment/88248337
tagged with: python
tagged with: gensim
has answer: http://stackoverflow.com/a/50651825
has comment: http://stackoverflow.com/comment/88249471
has title: add new words to GoogleNews by gensim
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/88248008
has text: Thanks for your answer.. I have come across other workaround which I will post in my answer.
type: AnswerComment
comment on: http://stackoverflow.com/a/50619132
score: 0
type: Comment

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

http://stackoverflow.com/comment/88696527
comment on: http://stackoverflow.com/a/50690130
type: AnswerComment
score: 0
type: Comment
has text: Care to remove the downvote? Or at least explain why you let it stay?

http://stackoverflow.com/comment/88120895
score: 1
type: AnswerComment
type: Comment
has text: Any reason to move away from the `DictReader()` and instead of `i[-2]` use `i['Gender']`?
comment on: http://stackoverflow.com/a/50555044

http://stackoverflow.com/a/50620309
has body: Assuming I understood everything correctly, here is an O(N) two-pass algorithm. Steps: Select lists with zero score. For each element of each zero-score list, find the length of the shortest zero-score list in which the element occurs. Let's call this the length score of the element. For each list, find the minimum of length scores of all elements of the list. If the result is less than the length of the list, the list is discarded. def select_lsts(lsts, scores): # pick out zero score lists z_lsts = [lst for lst, score in zip(lsts, scores) if score == 0] # keep track of the shortest length of any list in which an element occurs len_shortest = dict() for lst in z_lsts: ln = len(lst) for c in lst: len_shortest[c] = min(ln, len_shortest.get(c, float('inf'))) # check if the list is of minimum length for each of its chars for lst in z_lsts: len_lst = len(lst) if any(len_shortest[c] &lt; len_lst for c in lst): continue yield lst
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50618761

http://stackoverflow.com/comment/88126192
type: Comment
type: QuestionComment
has text: Sure, Done now.
score: 0
comment on: http://stackoverflow.com/q/50557484

http://stackoverflow.com/comment/88252164
comment on: http://stackoverflow.com/a/50608136
type: Comment
has text: Perhaps it is slightly different way you instantinate `b`, rather than OP. Quite clean cross reference!
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88299448
has text: on which line ?
type: Comment
comment on: http://stackoverflow.com/a/50643489
score: 0
type: AnswerComment

http://stackoverflow.com/q/50577657
has answer: http://stackoverflow.com/a/50580252
upvote count: 1
has comment: http://stackoverflow.com/comment/88164784
answer count: 1
has comment: http://stackoverflow.com/comment/88164792
favorite count: 0
has comment: http://stackoverflow.com/comment/88164866
type: UnansweredQuestion
has title: Stop a Python Script called in a PHP File when HTML page is exited
has body: I have called a python script within my PHP page using the code below: echo shell_exec("python object_detection_tutorial_cmsc265.py"); The python script generates image files in a loop until a certain condition is met. Example is the code below: while (True): cv2.imwrite('image' + str(loop) + '.png',image); if (not condition): break When the HTML/PHP page is exited in the browser, I can see that the images are still increasing in number, that means the python is still executing. How will I stop the python script upon exiting PHP page?
tagged with: python
tagged with: php
downvote count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/88164456

http://stackoverflow.com/comment/88266636
comment on: http://stackoverflow.com/q/50628266
has text: try ```X_tpredict.to_matrix()``` [docs](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.as_matrix.html)
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50615978
downvote count: 4
upvote count: 0
score: -4
type: Question
has answer: http://stackoverflow.com/a/50616018
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88242215
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88242277
type: UnansweredQuestion
has body: a=1 b=a+1 c=a+b x=0 while c &lt; 5: c=c+1 x=x+1 if c == 5: print ("\n It took this many loops to make C=5: ",x) The above code works as I want but, I need the below code to work. I'm suppose to use If/Else functions but, can only get the While function to run for me. if c &lt; 5: c=c+1 x=x+1 if c == 5: print ("\n It took this many loops to make C=5: ",x) I've tried several different ways but would appreciate any helpful explanation on why it doesn't run.
tagged with: python
has title: Why are "if "and "while" not interchangeable in my python-3.x code below?
has comment: http://stackoverflow.com/comment/88241947

http://stackoverflow.com/comment/88158577
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50574561
score: 0
has text: I added a couple of dups. The `datetime` one deals with accessing a single index array; the other deals with accessing multiple arrays in `MultiIndex`. For reference, note that `pd.DataFrame.ix` has been deprecated.

http://stackoverflow.com/q/50549859
has body: I have a model which requires the training images to be of shape [None, 28, 28, 1] but the MNIST images are [784,]. How do I change the shape of all images in training and test set to the required shape? Thanks in advance
favorite count: 0
has title: Changing shape of MNIST for tensorflow CNN
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/88110560
has comment: http://stackoverflow.com/comment/88110525
downvote count: 1
tagged with: tensorflow
has answer: http://stackoverflow.com/a/50550091
type: Question
accepted answer: http://stackoverflow.com/a/50550091
tagged with: mnist
tagged with: neural-network
upvote count: 3
answer count: 1

http://stackoverflow.com/a/50564035
has body: Use xs: print (dt_test.xs(True, axis=1, level=1)) 1990 1995 2000 Scenario Variable Unit Baseline Methane MtCO2eq 26 46 66 But better is filter first by isin and boolean indexing: df = df[df['Region'].isin(['CHINA','INDIA','INDONESIA','KOREA'])] print (df) 1990 1995 2000 Region Scenario Unit Variable 0 5 10 15 CHINA Baseline MtCO2eq Methane 1 6 11 16 INDIA Baseline MtCO2eq Methane 2 7 12 17 INDONESIA Baseline MtCO2eq Methane 3 8 13 18 KOREA Baseline MtCO2eq Methane And then aggregate sum per groups: dt_test = df.groupby(['Scenario','Variable','Unit']).sum() print (dt_test) 1990 1995 2000 Scenario Variable Unit Baseline Methane MtCO2eq 26 46 66
score: 0
answers question: http://stackoverflow.com/q/50563994
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50563994

http://stackoverflow.com/comment/88330457
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50656259
has text: I fail to see how `a` will contain *anything*, since you don't have a valid Python script.

http://stackoverflow.com/q/50620304
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/50625701
has comment: http://stackoverflow.com/comment/88252563
has comment: http://stackoverflow.com/comment/88254433
has title: Python pandas recursive function polynomial form
has body: I am trying to create a recursive function using Pandas dataframe in python. I read through, and there seems to be a few different methods, either for/if loop or Dataframe.apply methods; or scipy.signal.lfilter. However, lfilter doesn't work for me as my recursive formula can be of a polynomial form. The recursive formula I am looking to do is : x(t) = A * Bid + B * x(t-1)^C + BidQ I looked through some examples, and one possibility is of the form below. import pandas as pd import datetime as dt import numpy as np import scipy.stats as stats import scipy.optimize as optimize from scipy.signal import lfilter @xw.func @xw.ret(expand='table') def py_Recursive(v, lamda_, AscendType): df = pd.DataFrame(v, columns=['Bid', 'Ask', 'BidQ', 'AskQ']) df = df.sort_index(ascending=AscendType) NewBid = lfilter([1], [1,-2], df['Bid'].astype=(float)) df = df.join(NewBid) df = df.sort_index(ascending=True) return df lamda_ is a decay function that potentially will be used in the future and AscendType is either TRUE or FALSE My input data-set for v is as per below v = 763.1 763.3 89 65 762.5 762.7 861 687 772.1 772.3 226 761 770.6 770.8 927 333 777.8 778.0 59 162 786.5 786.7 125 431 784.7 784.9 915 595 776.8 777.0 393 843 777.7 777.9 711 935 771.6 771.8 871 956 770.0 770.2 727 300 768.7 768.9 565 923
upvote count: 1
tagged with: recursion
possible better answer: http://stackoverflow.com/a/50689635
has answer: http://stackoverflow.com/a/50689635
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/50625701
answer count: 2

http://stackoverflow.com/comment/88300571
has text: @Tholle - You get what I'm saying, right? A user could go into the script and just change 'gmail.send' to something else, including just 'https://mail.google.com/', which would give them full access to the email account.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50589582

http://stackoverflow.com/comment/88218857
type: QuestionComment
has text: Who are you getting to upvote your question?
comment on: http://stackoverflow.com/q/50604740
score: 4
type: Comment

http://stackoverflow.com/comment/88126433
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50557762
type: Comment
has text: @Jim421616, Well, basically `outfile.write(line)` does not `strip` for you.. At this stage you haven't told Python to use `line.strip()`. You only use it in your `if` condition earlier.

http://stackoverflow.com/q/50593534
tagged with: python-3.x
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/50595228
tagged with: query-optimization
has answer: http://stackoverflow.com/a/50595234
type: UnansweredQuestion
has body: I created a function that allows to count the number that there is of status and assign it to a variable. def get_types_count_display(self): dispatches = self.route_dispatches.values_list('dispatch_id', flat=True) dispatches = Dispatch.objects.filter(id__in=dispatches) d = { "dispatches_types": list(dispatches.values('status_id')) } pendents = len([1 for e in d["dispatches_types"] if e["status_id"]==1]) delivered = len([1 for e in d["dispatches_types"] if e["status_id"]==2]) partial = len([1 for e in d["dispatches_types"] if e["status_id"]==3]) undelivered = len([1 for e in d["dispatches_types"] if e["status_id"]==4]) return dict(pendents=pendents, delivered=delivered, partial=partial, undelivered=undelivered) where d is my variable that stores the dictionary it contains {'dispatches_types': [{'status_id': 2}, {'status_id': 1}, {'status_id': 1}, {'status_id': 1}, {'status_id': 2}]} or {'dispatches_types': []} this is dynamic the problem I have is that when you go through with for again invoking the query set, the query becomes heavier. How can I optimize this function?
tagged with: django
has title: Optimize queryset with django
type: Question
score: 0
has answer: http://stackoverflow.com/a/50596371
tagged with: django-queryset

http://stackoverflow.com/comment/88185535
score: 0
type: Comment
type: QuestionComment
has text: Did you append the anaconda python installation to the beginning or the end of the PATH variable?
comment on: http://stackoverflow.com/q/50587937

http://stackoverflow.com/comment/88152997
has text: modified the question, added the output expected.
type: Comment
comment on: http://stackoverflow.com/a/50571324
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88383230
type: QuestionComment
comment on: http://stackoverflow.com/q/50686613
has text: Plus, your code as posted has the hanging `+` at the end of each line, but your exception has it at the start, and your code as posted doesn't have all those unnecessary `str` calls, but your exception does. Which means your actual code is even farther from the code you posted, and even more impossible to debug.
score: 1
type: Comment

http://stackoverflow.com/q/50551356
tagged with: parallel-processing
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50552593
linked to: http://stackoverflow.com/q/34821877
accepted answer: http://stackoverflow.com/a/50552593
score: 1
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88113823
type: Question
has comment: http://stackoverflow.com/comment/88113743
answer count: 2
has comment: http://stackoverflow.com/comment/88113632
has body: I want to parallelize a function on a dataframe using Python. I saw tutorials and I found some code.I have adjusted it to my needs. When I execute the map function the program freezes. The code seems to be solid. I wonder what the problem is. import pandas as pd import numpy as np from multiprocessing import cpu_count, Pool attributes1 = pd.read_csv('attributes1.csv') def replace_data(data): for i in range(0, len(data.index)): temp = data.iloc[i, 1] temp = temp.replace('in.', 'inch') data.iloc[i, 1] = temp return data num_partitions = 10 #number of partitions to split dataframe num_cores = cpu_count() #number of cores on your machine def parallelize_dataframe(df, func): df_split = np.array_split(df, num_partitions) pool = Pool(num_cores) df = pd.concat(pool.map(func, df_split)) pool.close() pool.join() return df df1 = parallelize_dataframe(attributes1, replace_data)
has comment: http://stackoverflow.com/comment/88114011
downvote count: 0
has comment: http://stackoverflow.com/comment/88115205
has comment: http://stackoverflow.com/comment/88115682
possible better answer: http://stackoverflow.com/a/50551380
has comment: http://stackoverflow.com/comment/88113924
tagged with: pool
tagged with: spyder
has answer: http://stackoverflow.com/a/50551380
favorite count: 0
has comment: http://stackoverflow.com/comment/88115569
has comment: http://stackoverflow.com/comment/88113935
upvote count: 1
tagged with: python
has title: Multiprocessing in Python using Pool
has comment: http://stackoverflow.com/comment/88115837

http://stackoverflow.com/a/50656231
accepted answer of: http://stackoverflow.com/q/50653454
type: Answer
answers question: http://stackoverflow.com/q/50653454
score: 2
downvote count: 0
has body: As @WarrenWeckesser pointed out correctly in the comments, the two problems are quad returns a tuple, from which you would only need the first member here. The integral you want to compute is scalar, so you cannot pass a 2D array to it. The solutions: index the return of quad: quad( ..., )[0] to take only the first item out vectorize the call to A, such that it gets called with all the scalars of the array X one by one. Note that this is not very efficient, but should be fine with an array of 100x100 elements as presented here. A complete solution would look like import numpy as np from scipy import integrate import matplotlib.pyplot as plt def A(x): return integrate.quad(lambda i: x-i, 0, x)[0] n = 100 x = np.linspace(0, 10, n) y = np.linspace(0, 10, n) X, Y = np.meshgrid(x, y) M = np.vectorize(A)(X) + Y plt.contour(X, Y, M) plt.show()
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/88327535
comment on: http://stackoverflow.com/q/50658442
has text: I'm closing not to attract more duplicate answers.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88205384
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50597816
has text: Is the line `query = "INSERT INTO 'tableA' ......` correct?
score: 0

http://stackoverflow.com/q/50662048
has comment: http://stackoverflow.com/comment/88334375
has comment: http://stackoverflow.com/comment/88334290
tagged with: django
upvote count: 1
has title: Is it possible to call a models field with a string ? Access a class member variable using string?
linked to: http://stackoverflow.com/q/4075190
has comment: http://stackoverflow.com/comment/88334283
has comment: http://stackoverflow.com/comment/88334254
duplicate of: http://stackoverflow.com/q/4075190
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88334270
answer count: 0
downvote count: 0
favorite count: 0
type: Question
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/88334382
has body: Suppose I have a model like this class modelEmployee(models.Model): employee = models.ForeignKey(modelEmployee, on_delete=models.CASCADE,null=True,default=None,blank=True) introduction = models.CharField(max_length=1000, unique=False,default="") imageA = models.ImageField(upload_to='images/', default='images/patient_images/blank.jpeg') I know I can call imageA field like this inst = modelEmployee.objects.get(id=12) inst.imageA.save(content = someContent,name=someName) Now suppose I receive the imageA field dynamically Is there a way for me to call the field imageA like this field = "imageA" inst.[field].save(content = someContent,name=someName) #Access field using string
tagged with: python-3.x

http://stackoverflow.com/q/50606901
has body: I have a directory of images with random ids and a text file which has ids and their corresponding label. I was wondering if there is a way to read the data directly from disk and not loading the entire dataset in ram as a matrix. I know it can be done by using the method of python generators and then follow up with placeholders to feed the data. def generator_(path1,filename): . . yield x,y x=tf.placeholder(tf.float32,shape=[None,w,h,3]) y=tf.placeholder(tf.float32,shape=[None,n_c]) x,y=generator_(path_image,'labels.txt') But what is the better way to do it using tf.data api ?
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50607548
score: 2
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/50607548
tagged with: tensorflow
type: Question
has title: Using tf.data to read data from disk

http://stackoverflow.com/comment/88223815
score: 0
comment on: http://stackoverflow.com/q/50607037
type: Comment
type: QuestionComment
has text: No; file-like objects don't know about *how* they were created.

http://stackoverflow.com/a/50623928
upvote count: 2
type: Answer
score: 2
has body: Thanks to Micka, opencv use BGR, while qt use RGB for rendering. So, the correct code should be: import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import numpy as np import cv2 class MyLabel(QLabel): def __init__(self): super(MyLabel, self).__init__() img = np.zeros((256,256),dtype=np.uint8) img[0:128,0:128] = 255 img[128:255,128:255] = 128 disImg = cv2.applyColorMap(img, cv2.COLORMAP_AUTUMN) b = disImg[:,:,0] g = disImg[:,:,1] r = disImg[:,:,2] img = np.zeros((256,256,3),dtype=np.uint8) img[:,:,0] = r img[:,:,1] = g img[:,:,2] = b disImg = img QImg = QImage(disImg.data, disImg.shape[1], disImg.shape[0], disImg.strides[0], QImage.Format_RGB888) self.qimg = QImg def paintEvent(self, QPaintEvent): super(MyLabel, self).paintEvent(QPaintEvent) pos = QPoint(0, 0) source = QRect(0, 0, 256,256) painter = QPainter(self) painter.drawPixmap(pos, QPixmap.fromImage(self.qimg), source) class Window(QWidget): def __init__(self): super(Window, self).__init__() layout = QHBoxLayout(self) self.resize(300,300) self.label = MyLabel() layout.addWidget(self.label) if __name__ == '__main__': app = QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec_())
downvote count: 0
answers question: http://stackoverflow.com/q/50623735

http://stackoverflow.com/q/50557438
linked to: http://stackoverflow.com/q/18254813
has comment: http://stackoverflow.com/comment/88127715
has comment: http://stackoverflow.com/comment/88127063
upvote count: 0
has body: I've created a multipage program (using Python 2.7 and Tkinter on a Mac), with navigation buttons between the pages. I want to be able to use Scrollbar on some of the pages, but when I put in the Scrollbar code for each page, only the last page with the scrollbar code added is scrollable. The scrollbar works great (I understand how to make it), but it seems that only one page can have a working scrollbar at a time. Why? This exact question (almost) was asked several years ago here (Python Tkinter scrollbar in multiple tabs) but was never answered. I've also tried putting the scrollbar code into the "main window" and the "create new file" class code, but funky things happen. Here's a basic version of what I'm trying to do: from Tkinter import * def quit(): #quits the program master.destroy() class FirstPage(Frame): def __init__(self, *args, **kwargs): Frame.__init__(self, *args, **kwargs) #creating vertical and horizontal scrollbars self.canvas = Canvas(self, background = "#ffffff", highlightcolor = "white") self.canvas.pack(side = "left", fill = "both", anchor = "center", expand = True) self.vscrollbar = Scrollbar(self, orient = "vertical", command = self.canvas.yview) self.vscrollbar.pack(side = "right", fill = "y") self.canvas.configure(yscrollcommand = self.vscrollbar.set) self.hscrollbar = Scrollbar(self, orient = "horizontal", command = self.canvas.xview) self.hscrollbar.pack(side = "bottom", fill = "x") self.canvas.configure(xscrollcommand = self.hscrollbar.set) self.container = Frame(self.canvas, highlightcolor = "white") self.canvas.create_window(0, 0, window = self.container, anchor = "center") self.container.bind("&lt;Configure&gt;", self.onFrameConfigure) self.canvas.bind_all("&lt;MouseWheel&gt;", self.on_vertical) self.canvas.bind_all("&lt;Shift-MouseWheel&gt;", self.on_horizontal) self.label = Label(self.container, text = "Welcome!") self.label.pack(side = "top", fill = "both", expand = False) def onFrameConfigure(self, event): #Reset the scroll region …
accepted answer: http://stackoverflow.com/a/50572734
has title: Using Scrollbar in multiple tabs Python Tkinter
score: -1
answer count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50572734
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88128190
tagged with: tkinter
tagged with: scrollbar
downvote count: 1
type: Question

http://stackoverflow.com/comment/88108099
type: QuestionComment
has text: Can you post your command line and error message. No screen shot please.
comment on: http://stackoverflow.com/q/50548627
score: 1
type: Comment

http://stackoverflow.com/comment/88129138
type: QuestionComment
has text: Who asked you to reassign it to `top_words`?
score: 0
comment on: http://stackoverflow.com/q/50559208
type: Comment

http://stackoverflow.com/a/50634886
has body: I don't think there's any shortcuts here. I would recommend drawing the unzoomed screen as normal, blitting in the zoomed area as a circle, then blitting in the magnifying glass over top. The first and last bits you obviously know how to do already, so let's look at blitting in the zoomed area. To do this, I would take the portion of the image to be zoomed in as a square, and copy it to a new Surface. (Remember that this will be smaller than the resulting area.) Use pygame.transform.smoothscale to expand it to be large enough to cover the entire magnifying glass area Use masking to turn it from a square into a circle. See Pygame - is there any way to only blit or update in a mask for details. Blit the result. Don't worry too much about performance. You're only doing this once per frame.
score: 5
type: AcceptedAnswer
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/88317234
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50630647
answers question: http://stackoverflow.com/q/50630647

http://stackoverflow.com/comment/88303583
type: AnswerComment
score: 0
type: Comment
has text: its works for variable, but not for changes in template file. For example i change text on Time {{ time}} in notepad & save this. I'm not rebooting the server and the site needs to see the changes, but this does not happen
comment on: http://stackoverflow.com/a/50644769

http://stackoverflow.com/a/50691442
has comment: http://stackoverflow.com/comment/88398037
upvote count: 1
has body: You can try to directly send the markdown format string in botbuilder in python. And which is also support in webchat as mentioned at Channel Inspector. I have a test with hypen link and it works fine on my side. def __create_reply_activity(request_activity): return Activity( type=ActivityTypes.message, channel_id=request_activity.channel_id, conversation=request_activity.conversation, recipient=request_activity.from_property, from_property=request_activity.recipient, text='[Click here](https://bing-well.com)', service_url=request_activity.service_url)
answers question: http://stackoverflow.com/q/50684752
accepted answer of: http://stackoverflow.com/q/50684752
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/q/50584596
type: AnsweredQuestion
score: 2
has body: I have a list of words(around 1000 words), I call them negative words. ['CAST','ARTICLES','SANITARY','JAN','CLAUSES','SPECIAL','ENDORSEMENT'] I'll soon be making a dataframe out of this list of words. I also have a dataframe which looks like - FileName PageNo LineNo GOODS_DESC 1 17668620 TM000004 36 CAST ARTICLES IRON SANITARY 59 17668620 TM000014 41 CRATES 60 17668620 TM000014 42 CAST ARTICLES IRON 61 17668620 TM000014 49 JAN ANIMAL AND VEGETABLE 63 17668620 TM000016 49 SETTLING AGENT 65 17668620 TM000016 29 JAN 66 17668620 TM000016 32 CLAUSES SPECIAL CONDITIONS WARRANTIES 67 17668620 TM000016 37 CARGO ISM ENDORSEMENT 69 17668620 TM000017 113 QUANTITY DECLARED IRON CRATES I want to remove the negative words from the dataframe (as fast a possible). and get the refined dataframe. So that the dataframe looks like this - dataframe out of this list of words. I also have a dataframe which looks like - FileName PageNo LineNo GOODS_DESC 1 17668620 TM000004 36 IRON 59 17668620 TM000014 41 CRATES 60 17668620 TM000014 42 IRON 61 17668620 TM000014 49 ANIMAL AND VEGETABLE 63 17668620 TM000016 49 SETTLING AGENT 65 17668620 TM000016 29 NaN 66 17668620 TM000016 32 CONDITIONS WARRANTIES 67 17668620 TM000016 37 CARGO ISM 69 17668620 TM000017 113 QUANTITY DECLARED IRON CRATES Currently my approach is that I'm iterating over the dataframe, taking each row and splitting it and checking wether the splitted word is in negative words list or not.IF its not there then I'm making a new string by joining the words and adding it in the dataframe. for rows in df.itertuples(): a = [] flat_list = [] a.append(rows.GOODS_DESC) flat_list = [item.strip() for sublist in a for item in sublist.split(' ') if item.strip()] flat_list = list(sorted(set(flat_list), key=flat_list.index)) flat_list = [i for i in flat_list if i.lower() not in negative_words_list] if(not flat_list): df.drop(rows.Index,inplace=True) continue s=' '.join(flat_list) df.loc[rows.Index,'GOODS_DESC']=s df['GOODS_DESC'] = df['GOODS_DES…
type: Question
has answer: http://stackoverflow.com/a/50584647
has answer: http://stackoverflow.com/a/50585136
tagged with: dataframe
tagged with: python-3.6
accepted answer: http://stackoverflow.com/a/50585136
has answer: http://stackoverflow.com/a/50585268
tagged with: pandas
downvote count: 0
possible better answer: http://stackoverflow.com/a/50585268
favorite count: 0
upvote count: 2
has title: Removal of substring from all dataframe columns
has answer: http://stackoverflow.com/a/50584763
tagged with: python
answer count: 4

http://stackoverflow.com/q/50682676
tagged with: matplotlib
has body: I want to modify the label of my 3D plot on the z-axis, here is my code: fig = plt.figure() ax = fig.gca(projection='3d') surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm) x.ticklabel_format(style = 'sci', axis = 'z', scilimits = (0, 2)) offset = ax.get_zaxis().get_offset_text() text = offset.get_text() offset.set_visible(False) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z ' + text) If I use get_yaxis() instead of get_zaxis() it works. With get_zaxis() I get the error: AttributeError: 'Axes3DSubplot' object has no attribute 'get_zaxis' How can I access the z-axis in the same manner?
type: Question
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/88614620
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/88375452
has title: acces z axis of Axes3DSubplot
type: UnansweredQuestion
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50683729

http://stackoverflow.com/a/50568585
downvote count: 0
has comment: http://stackoverflow.com/comment/88147119
has body: Use assign by Series created by selecting 1. row of df1: cols = ['x','y','z'] new_cols = ['a','b','c'] df = df2.assign(**pd.Series(df1[cols].iloc[0].values, index=new_cols)) print (df) A B a b c 0 7 8 1 2 3 1 9 6 1 2 3 2 8 5 1 2 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88147139
type: Answer
accepted answer of: http://stackoverflow.com/q/50568559
upvote count: 1
answers question: http://stackoverflow.com/q/50568559
score: 1

http://stackoverflow.com/a/50545206
answers question: http://stackoverflow.com/q/50544907
type: Answer
has body: Simple with ''' to not complicate things: print('''Hello World's"s""''')
score: 0

http://stackoverflow.com/comment/88280605
has text: Exact dupe: https://stackoverflow.com/q/2158395/2988730. The name of the operation you are looking for is "flatten".
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50635234

tls1.2
tags question: http://stackoverflow.com/q/50666608
tags question: http://stackoverflow.com/q/50652680
type: Tag
tags question: http://stackoverflow.com/q/50627305
tag name: tls1.2
tags question: http://stackoverflow.com/q/50546760
tags question: http://stackoverflow.com/q/50663229

http://stackoverflow.com/comment/88382664
comment on: http://stackoverflow.com/a/50677071
score: 2
has text: That probably just disables warn-level error reports rather than actually allowing higher n_jobs values
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50591949
has title: One column to multiple in pandas
has answer: http://stackoverflow.com/a/50592181
type: Question
tagged with: dataframe
score: 0
tagged with: pandas
answer count: 1
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has body: How do I turn one column into multiple ones in a data set, using python? For example, user_id info_name score 1 a 50% 1 b 75% 1 c 100% The goal is to switch the "info_name" column to be multiple columns so that the "user_id" is not duplicated 3 times, and information about a given user is all in one row, like this: user_id a b c 1 50% 75% 100%

http://stackoverflow.com/q/50585569
type: UnansweredQuestion
tagged with: keras
has title: predict_generator and class labels
has body: I am using ImageDataGenerator to generate new augmented images and extract bottleneck features from pretrained model but most of the tutorial I see on keras samples same no of training samples as number of images in directory. train_generator = train_datagen.flow_from_directory( train_path, target_size=image_size, shuffle = "false", class_mode='categorical', batch_size=1) bottleneck_features_train = model.predict_generator( train_generator, 2* nb_train_samples // batch_size) Suppose I want 2 times more images from the above code, how I can get the desired class labels for the features extracted from bottleneck layer which are stored in tuple train_generator. shouldnt the code in training_generator.py at line 422 x, _ = generator_output do something like this =&gt; x, y = generator_output and return tuple [np.concatenate(out) for out in all_outs],y from predict_generator i.e return the corresponding class labels along with the predicted features all_outs since there is no way to get the corresponding labels without running generator twice.
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50586848
type: Question
upvote count: 1
tagged with: python
answer count: 1

http://stackoverflow.com/comment/88402511
comment on: http://stackoverflow.com/q/50696501
type: Comment
score: 1
has text: It would make sense on using multiprocessing only if the work done in `sigma` can be split in multiple "little" jobs. On another hand, if your code has to/can do something else while the `sigma` is executed,you could rewrite your code a little so that it calls "the other parts of code" it self when the execution is completed (implement some kind of "event handler")
type: QuestionComment

http://stackoverflow.com/comment/88211589
score: 0
type: Comment
has text: As i understant this is feature of pymongo library (of the cursor...) not of python at all.
comment on: http://stackoverflow.com/a/50600441
type: AnswerComment

http://stackoverflow.com/a/50571401
answers question: http://stackoverflow.com/q/50571343
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: The thing here is the yield statement. When you use yield inside a function, it will create a generator. Keep in mind that any function with a yield will return a generator when called. Try this: def func(): print("&gt; Why doesn't this line print?") exit() x = func() print(x) Results: Why doesn't this line print? None And then the program exits.

http://stackoverflow.com/q/50596612
has comment: http://stackoverflow.com/comment/88202451
answer count: 1
has comment: http://stackoverflow.com/comment/88202344
accepted answer: http://stackoverflow.com/a/50620875
has title: Writing html form input to text file using python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88202574
tagged with: raspberry-pi3
type: Question
has body: I'm trying to use this code to print a number from a html form to a text document for storage but it doesn't seem to be working @app.route("/result",methods = ['POST', 'GET']) def result(): if request.method == 'POST': timer = request.form['timer_input'] f = open("timer.txt", "w") f.write("Water every {} days".format(timer) templateData = template(text = "timer") return render_template('timer.html', **templateData) Set frequencys (e.g. 2 = every 2 days): does anyone know why it's not working? I've looked at several places for alternatives but they all use cgi or php and I'm not interested in using either
has answer: http://stackoverflow.com/a/50620875
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/88202822
tagged with: python
has comment: http://stackoverflow.com/comment/88202719
score: 0

http://stackoverflow.com/a/50562214
score: 1
accepted answer of: http://stackoverflow.com/q/50555442
upvote count: 1
answers question: http://stackoverflow.com/q/50555442
type: AcceptedAnswer
type: Answer
has body: I believe there are 2 ways. Obtain GtkAdjustments for scrolled window (vertical and horizontal), set it's value to maximum after set_text A bit more complicated example can be found in gtk3-demo app in Text Widget -&gt; Automatic Scrolling section. There are following lines: /* If we want to scroll to the end, including horizontal scrolling, * then we just create a mark with right gravity at the end of the * buffer. It will stay at the end unless explicitly moved with * gtk_text_buffer_move_mark. */ gtk_text_buffer_create_mark (buffer, "end", &amp;iter, FALSE); And then: /* Get "end" mark. It's located at the end of buffer because * of right gravity */ mark = gtk_text_buffer_get_mark (buffer, "end"); gtk_text_buffer_get_iter_at_mark (buffer, &amp;iter, mark); /* and insert some text at its position, the iter will be * revalidated after insertion to point to the end of inserted text */ // Extra code removed /* Now scroll the end mark onscreen. */ gtk_text_view_scroll_mark_onscreen (textview, mark);
downvote count: 0

http://stackoverflow.com/comment/88548702
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50558066
has text: I have updated my chromedriver as @DebanjanB and @yong suggested. It is now version 2.39, but I still get the same error as before. The code from @stanjer answer works, but because the element is being found by css selector, it is just as slow as finding it by xpath. As far as i can tell, the only difference between `find_element_by_id('order_billing_name')` and `find_element_by_xpath("//input[@id='order_billing_name']")` is that in the second, the program is also making sure the element found is an input. Could this have to do with the problem? if so, is there a faster way to search for it?

http://stackoverflow.com/a/50592118
has body: The following works for your example: df[0].str.extract(':\w\.(\d+)(.+)') # 0 1 #0 955563 G&gt;C #1 955597 G&gt;T #2 955619 G&gt;C #3 957640 C&gt;T #4 976059 C&gt;T #5 37090470 C&gt;T #6 133256600 G&gt;A #7 15923 A&gt;G If the last "column" always has the A>A structure, where A is a single letter, then you can be more specific with: df[0].str.extract(':\w\.(\d+)(\w&gt;\w)')
has comment: http://stackoverflow.com/comment/88193961
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/88194138
accepted answer of: http://stackoverflow.com/q/50592013
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88194019
answers question: http://stackoverflow.com/q/50592013
type: Answer

http://stackoverflow.com/a/50631555
downvote count: 0
has comment: http://stackoverflow.com/comment/88311105
has body: Well that depends, if you want to place all the strings entitled "REPLACE_ME" with the same string you can use this. The for loop loops through all the keys in the dictionary and then you can use the keys to select each value in the dictionary. If it is equal to your replacement string it will replace it with the string you want. search_string = "REPLACE_ME" replacement = "SOME STRING" test = {"test1":"REPLACE_ME", "test2":"REPLACE_ME", "test3":"REPLACE_ME", "test4":"REPLACE_ME","test5":{"test6":"REPLACE_ME"}} def replace_nested(test): for key,value in test.items(): if type(value) is dict: replace_nested(value) else: if value==search_string: test[key] = replacement replace_nested(test) print(test)
has comment: http://stackoverflow.com/comment/88273829
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50631393
upvote count: 2
has comment: http://stackoverflow.com/comment/88274195

http://stackoverflow.com/q/50635960
has answer: http://stackoverflow.com/a/50637519
has comment: http://stackoverflow.com/comment/88281894
tagged with: python
has comment: http://stackoverflow.com/comment/88281905
upvote count: 4
answer count: 4
type: AnsweredQuestion
tagged with: python-3.x
score: 2
has comment: http://stackoverflow.com/comment/88281881
type: Question
has title: Iterate through a list, compare values and remove duplicate - Python
has comment: http://stackoverflow.com/comment/88281859
has answer: http://stackoverflow.com/a/50636165
accepted answer: http://stackoverflow.com/a/50636165
possible better answer: http://stackoverflow.com/a/50636040
downvote count: 2
has body: I am curious. How can I correctly iterate through a list, compare two values and delete the duplicate if it exists. Here I created a nested for loop: my_list = [ 1, 2, 3, 4, 5 ] temp = [1, 5, 6] def remove_items_from_list(ordered_list, temp): # Removes all values, found in items_to_remove list, from my_list for j in range(0, len(temp)): for i in range(0, len(ordered_list)): if ordered_list[i] == temp[j]: ordered_list.remove(ordered_list[i]) But when I execute my my code I get an error: File "./lab3f.py", line 15, in remove_items_from_list if ordered_list[i] == items_to_remove[j]: can anyone explain why? This question, wanted to me compare two lists with one another, and these lists have two different lengths. If an item in list a matched a value in list b, we wanted then to delete it from list a.
has answer: http://stackoverflow.com/a/50636040
linked to: http://stackoverflow.com/q/2896752
has answer: http://stackoverflow.com/a/50636053
favorite count: 0

http://stackoverflow.com/q/50544495
type: Question
has answer: http://stackoverflow.com/a/50544752
answer count: 1
score: 0
tagged with: http://stackoverflow.com/tag/pdf
favorite count: 0
accepted answer: http://stackoverflow.com/a/50544752
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/331918
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/2002055
downvote count: 1
has body: I have a lot of PDF files, which are basically scanned documents so every page is one scanned image. I want to perform OCR and extract text from those files. I have tried pytesseract but it does not perform OCR directly on pdf files so as a work around, I want to extract the images from PDF files, save them in directory and then perform OCR using pytesseract on those images directly. Is there any way in python to extract scanned images from pdf files? or is there any way to perform OCR directly on pdf files?
has title: Extracting scanned pages from PDF using python

http://stackoverflow.com/comment/88280078
comment on: http://stackoverflow.com/a/50634655
has text: @abarnert That’s a very good point, and can be easily verified with a quick benchmark. I’ve removed the looping part and instead focused on getting the right answer with using just `str.find` calls. Thank you for the feedback!
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88175589
score: 0
has text: Set the `np.random.seed(i)` at the top of the script. Or else, use `random_state` in everywhere you find it
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50582637

http://stackoverflow.com/comment/89716385
score: 0
type: AnswerComment
has text: Wow, this solution is perfect for my usage. Thanks! (Also, shouldn't it be OK if the `FPS.tick()` call is removed from the event loop?)
type: Comment
comment on: http://stackoverflow.com/a/51370662

http://stackoverflow.com/q/50577552
type: Question
linked to: http://stackoverflow.com/q/50177766
has answer: http://stackoverflow.com/a/50577922
linked to: http://stackoverflow.com/q/43870531
linked to: http://stackoverflow.com/q/33610685
downvote count: 0
answer count: 1
score: 1
has body: When printing out the value of the node "c" in the following example, to me, it seems that there's no difference between print sess.run(c) and print c.eval(). Can I assume that sess.run(c) and c.eval() are equivalent? Or are there any differences? import tensorflow as tf a = tf.Variable(2.0, name="a") b = tf.Variable(3.0, name="b") c = tf.add(a, b, name="add") with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print sess.run(c) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print c.eval()
has title: The difference between sess.run(c) and c.eval() in Tensorflow
favorite count: 0
accepted answer: http://stackoverflow.com/a/50577922
has comment: http://stackoverflow.com/comment/88166103
tagged with: python
linked to: http://stackoverflow.com/q/44129480
type: AnsweredQuestion
upvote count: 1
tagged with: tensorflow

http://stackoverflow.com/comment/88313548
type: Comment
has text: is m an integer or a floating point number. Are they all symmetric like that?
comment on: http://stackoverflow.com/a/50646990
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88206711
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50598524
has text: Maybe my problem is somewhere else, but I get the error: ValueError: could not convert string to float:
score: 0

http://stackoverflow.com/q/50691545
tagged with: stdout
linked to: http://stackoverflow.com/q/27831221
has body: I'm trying to use a with statement to suppress sys.stdout or sys.stderr individually. I found a tutorial that didn't work. I'm using Python 3.6.4 and I think the tutorial is some version of Python 2. I looked it up on SO and found a few but with applications that didn't work or did not apply to this situation. This doesn't apply:Python subprocess supress stdout and stderr Couldn't get any of the with statements to work: Suppress stdout / stderr print from Python functions This is for fortran: Redirecting FORTRAN (called via F2PY) output in Python from contextlib import contextmanager @contextmanager def suppress_console(file=sys.stdout): with open(os.devnull, "w") as devnull: old_file = file file = devnull try: yield finally: file = old_file with suppress_console(): print(1, file=sys.stdout) # 1
linked to: http://stackoverflow.com/q/977840
tagged with: dev-null
has title: How to use a `with` statement to suppress `sys.stdout` or `sys.stderr`?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50691621
tagged with: stderr
has comment: http://stackoverflow.com/comment/88392785
linked to: http://stackoverflow.com/q/5081657
tagged with: suppress
type: Question
has answer: http://stackoverflow.com/a/50691665
answer count: 2
has comment: http://stackoverflow.com/comment/88392826
linked to: http://stackoverflow.com/q/11130156
tagged with: python
possible better answer: http://stackoverflow.com/a/50691665
accepted answer: http://stackoverflow.com/a/50691621
score: 0

http://stackoverflow.com/q/50622804
answer count: 1
has title: How to save the elements of multidimensional list in nested json in python
tagged with: list
has body: I have a multidimensional list which looks like below: [ ['Name1','5','6','7'], ['Name2','3','8','5'], ] As you can see, in the above multidimensional list, we have two lists with two names and their values. This generated by an algorithm which can generate more names like 4 names thus, there might be 4 lists inside the multidimensional list. Based on this I have to save the above info in a json, which looks like below: { "id": "id", "Values": [ { "Name": "Name1", "X": "85", "Y": "78", "Z": "10" }, { "Name": "Name2", "X": "85", "Y": "78", "Z": "10" } ] } So all the name will go inside ['Values']['Name'] followed by the int numbers but I am getting confused as to how to save list items in json as it is not fixed. can anyone help me on this. Thanks
score: 0
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/50622900
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50622900
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/q/50556719
favorite count: 0
tagged with: qsortfilterproxymodel
tagged with: python
accepted answer: http://stackoverflow.com/a/50557097
type: AnsweredQuestion
score: 1
tagged with: pyqt5
upvote count: 1
type: Question
has body: I have a very basic app that displays a tree view and a button that adds items to that tree view, using current selection as a parent. Inserting a first level child works well while inserting the 3d level child fails for some reason (it just is not displayed after inserting is done. I've prepared fully verifiable code that you can test yourself, the test case is the following: Click on any item Click on the "Add row" button Click on the newly created item Click "Add row" button again Expected result: a child item is added Actual result: nothing happens. Here is the code main.py from PyQt5 import QtWidgets import application import sys def main(): app = QtWidgets.QApplication(sys.argv) window = application.Application() window.show() app.exec_() main() application.py from PyQt5 import QtWidgets from PyQt5.QtCore import QSortFilterProxyModel, QModelIndex import tree from TreeModel import TreeModel class Application(QtWidgets.QMainWindow, tree.Ui_MainWindow): data = [ "test1", "test2", "test3" ] def __init__(self): super().__init__() self.setupUi(self) self.proxy_model = QSortFilterProxyModel(self.treeView) self.model = TreeModel(self.treeView) for data in self.data: index = QModelIndex() self.model.insertRows(self.model.rowCount(index), 1, index) self.model.setData(self.model.index(self.model.rowCount(index) - 1, 0, index), data) self.proxy_model.setSourceModel(self.model) self.treeView.setModel(self.proxy_model) self.pushButton.clicked.connect(lambda: self.add_row_click()) def add_row_click(self): index = self.treeView.selectionModel().selectedIndexes()[0] self.proxy_model.insertRows(self.proxy_model.rowCount(index), 1, index) self.proxy_model.setData(self.proxy_model.index(self.proxy_model.rowCount(index) - 1, 0, index), "new_test") TreeItem.py class TreeItem(object): ind_column_name = 0 ind_column_id = 1 ind_column_parent_id = 2 key_name = "name" key_id = "id" key_parent_id = "parent" key_new_id = "new_item_id" def __init__(self, data, parent=None): self.parentItem…
has answer: http://stackoverflow.com/a/50557097
tagged with: pyqt
has title: Inserting rows in QTreeView that uses QSortFilterProxyModel
answer count: 1
downvote count: 0
tagged with: qtreeview

http://stackoverflow.com/comment/88190440
comment on: http://stackoverflow.com/a/50590478
type: AnswerComment
score: 0
type: Comment
has text: @abarnert this question has appeared in C, So i want its python single line statement.

http://stackoverflow.com/comment/88389718
type: QuestionComment
has text: Can you elaborate an example will be greatly appreciated.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50689840

http://stackoverflow.com/q/50543630
score: 1
has body: I have created a Python package... with nothing in it. All it is, is the simple structure from the Python packaging tutorial. /example_pkg /example_pkg __init__.py setup.py LICENSE README.md Where do you put the files you want to create? In the root folder or somewhere else?
accepted answer: http://stackoverflow.com/a/50543672
has title: Where do I put my package contents?
type: Question
has answer: http://stackoverflow.com/a/50544025
possible better answer: http://stackoverflow.com/a/50543898
downvote count: 0
has answer: http://stackoverflow.com/a/50543672
has answer: http://stackoverflow.com/a/50543853
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/50543898
has comment: http://stackoverflow.com/comment/88099178
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/50634932
score: 0
has comment: http://stackoverflow.com/comment/88307116
type: AcceptedAnswer
has body: The file descriptor returned by open is not a pipe. It's generally legal to use regular files with PipeIOStream, but it's not useful on linux. Such file descriptors are always considered readable, and reading from them or writing to them always blocks. So using PipeIOStream like this is no better than simply doing fd.write(item[1]). You've opened the file in write-only mode, but PipeIOStream wraps its file in a read/write wrapper (I'm actually kind of surprised that this ever works, since real pipes are one-way). I think that's where this exception is coming from. If you opened the file in 'ab+' mode, I think it would work. I haven't tried this, though.
type: Answer
accepted answer of: http://stackoverflow.com/q/50630940
answers question: http://stackoverflow.com/q/50630940

http://stackoverflow.com/comment/88153694
comment on: http://stackoverflow.com/q/50569453
has text: The code works, but only pylint tells you there is a problem, right?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50585674
tagged with: multithreading
tagged with: python
has title: python popen Thread object read stdout to variable
duplicate of: http://stackoverflow.com/q/43521473
linked to: http://stackoverflow.com/q/1191374
has comment: http://stackoverflow.com/comment/88183375
has comment: http://stackoverflow.com/comment/88180908
answer count: 0
tagged with: subprocess
tagged with: popen
has comment: http://stackoverflow.com/comment/88181269
score: 1
tagged with: process
linked to: http://stackoverflow.com/q/375427
has comment: http://stackoverflow.com/comment/88180811
type: Question
has comment: http://stackoverflow.com/comment/88180991
has comment: http://stackoverflow.com/comment/88182886
linked to: http://stackoverflow.com/q/43521473
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88185095
favorite count: 0
has comment: http://stackoverflow.com/comment/88181391
has body: How to capture stdout of a popen in threading.Thread. I need to parse the stdout for a success message. I am using the below code block to run a command but kill it after timeout_sec seconds. The examples I saw online suggested using std, err = popen.communicate() but this is not working since communicate is used in Thread. My knowledge in python thread is very basic. Kindly help. def run_command_with_timeout(cmd, timeout_sec): args = shlex.split(str(cmd)) proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) proc_thread = Thread(target=proc.communicate) proc_thread.start() # for line in proc.stdout: # print (line) proc_thread.join(timeout_sec) # while True: # line = proc.stdout.readline() # print line.strip() # if not line: # break if proc_thread.is_alive(): try: proc.kill() except OSError, e: return proc.returncode return 137 return proc.returncode
type: UnansweredQuestion

http://stackoverflow.com/comment/88375521
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50682466
has text: Thus, using `--addTests test_command test_command2` when invoking your script, `args = parser.parse_args()` will give the following parsed args: `Namespace(addTests=['test_command', 'test_command2']`. Then you can access them by using `for command in args.addTests: print command` (or instead of printing you can run them, etc.

http://stackoverflow.com/a/50665321
upvote count: 8
has body: It can be as simple as this, using list comprehension: &gt;&gt;&gt; lst = [x for x in listB for a in listA if a in x] &gt;&gt;&gt; lst ['sentence 2 contains cat', 'sentence 6 contains dog'] Edit: This is essentially the same solution as Ollie's, but runs ~8-10% faster. For two-way comparison, simply replace if a in x with if (a in x) or (x in a) (parentheses added for clarity).
type: Answer
score: 8
downvote count: 0
answers question: http://stackoverflow.com/q/50665271

http://stackoverflow.com/q/50690587
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: tensorflow
type: Question
has title: Tensorflow error message "Incompatible shapes between op input and calculated input gradient.", given by AdagradOptimizer
has body: I realize that somewhere in my code some dimension of one of my tensors is wrong from the main error message ValueError: Incompatible shapes between op input and calculated input gradient. Forward operation: SegmentMean. Input index: 0. Original input shape: (126, 80). Calculated input gradient shape: (126, 80) I also want to know exactly how to interpret the whole error message because I feel it may give me more insight to what exactly is going wrong. Here is the full error message. --------------------------------------------------------------------------- InvalidArgumentError Traceback (most recent call last) /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py in set_shape(self, shape) 534 dim_list, --&gt; 535 unknown_shape) 536 except errors.InvalidArgumentError as e: InvalidArgumentError: Dimension 0 in both shapes must be equal, but are 504 and 126. Shapes are [504,80] and [126,80]. During handling of the above exception, another exception occurred: ValueError Traceback (most recent call last) /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/gradients_impl.py in _GradientsHelper(ys, xs, grad_ys, name, colocate_gradients_with_ops, gate_gradients, aggregation_method, stop_gradients) 661 try: --&gt; 662 in_grad.set_shape(t_in.get_shape()) 663 except ValueError: /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py in set_shape(self, shape) 537 # Convert to ValueError for backwards compatibility. --&gt; 538 raise ValueError(str(e)) 539 ValueError: Dimension 0 in both shapes must be equal, but are 504 and 126. Shapes are [504,80] and [126,80]. During handling of the above exception, another exception occurred: ValueError Traceback (most recent call last) &lt;ipython-input-11-e8feccf3b5a2&gt; in &lt;module&gt;() 57 # that contribute to the tensor it is passed. 58 # See docs on `tf.train.Optimizer.minimize()` for more details. ---&gt; 59 optimizer = tf.train.AdagradOptimizer(1.0).minimize(loss) 60 61 # Compute the…
downvote count: 0
score: 1
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/133942774
type: Comment
comment on: http://stackoverflow.com/a/75805852
type: AnswerComment
score: 0
has text: You're a legend, this is the only thing that worked for me

http://stackoverflow.com/comment/88237483
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50613637
has text: For some reason I cant ping - However I mean the json is not supposed to me valid - Which is not the goal for me. It could be a txt file aswell as I mentioned, I found this piece of code where I just continued since the json file looked easier (Because it automatic

http://stackoverflow.com/q/50647756
has comment: http://stackoverflow.com/comment/88306730
tagged with: text
has comment: http://stackoverflow.com/comment/88306501
tagged with: classification
has comment: http://stackoverflow.com/comment/88306682
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88306808
type: Question
has comment: http://stackoverflow.com/comment/88306782
has comment: http://stackoverflow.com/comment/88306259
score: 0
has comment: http://stackoverflow.com/comment/88306614
tagged with: pandas
has comment: http://stackoverflow.com/comment/88306641
answer count: 1
has comment: http://stackoverflow.com/comment/88306829
has comment: http://stackoverflow.com/comment/88306288
has comment: http://stackoverflow.com/comment/88306151
favorite count: 0
has body: So I have a very large pandas dataframe consisting of transaction data: description amount foo 10 bar 5 baz 9 foo bar 12 foobar 15 bar baz 20 bazbar 19 Expected output is as follows: description amount tag foo 10 foo bar 5 bar baz 9 baz foo bar 12 foo, bar foobar 15 foobar bar baz 20 bar, baz bazbar 19 bazbar My thought process is as follows: Create a huge list of unique words from all rows in df['description'] Then for the new column df['tag'], for each item in list, do a isin and assign the relevant tag. I'm not sure how to create the list of unique words. Plus, I'm not sure this is the correct approach to solve this problem. Appreciate any help!
has title: Text classification in pandas (python)
has answer: http://stackoverflow.com/a/50648425
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88306317
has comment: http://stackoverflow.com/comment/88306253

http://stackoverflow.com/comment/88189063
type: Comment
type: QuestionComment
score: 1
has text: Welcome to Stack Overflow! If you believe that the code works correctly, consider presenting your work (with its unit tests) in a more-complete fashion over at [codereview.se]. You'll likely get some suggestions on making it more efficient, easier to read, and better tested. Before you do that, make sure to read [A guide to Code Review for Stack Overflow users](//codereview.meta.stackexchange.com/a/5778) first, as some things are done differently over there - e.g. question titles should simply say what the code *does*, as the question is always, "How can I improve this?".
comment on: http://stackoverflow.com/q/50589489

http://stackoverflow.com/comment/88245676
type: Comment
type: QuestionComment
has text: Which version of MySQL are you using?
comment on: http://stackoverflow.com/q/50614758
score: 0

http://stackoverflow.com/q/50631577
has comment: http://stackoverflow.com/comment/88273313
has comment: http://stackoverflow.com/comment/88273330
tagged with: python
has answer: http://stackoverflow.com/a/50631835
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88273722
possible better answer: http://stackoverflow.com/a/50632140
has title: How to run python code in the currently activated virtualenv with subprocess?
has answer: http://stackoverflow.com/a/50632140
has body: I have a virtualenv named 'venv' and it is activate: (venv)&gt; and I wrote codes that I'll run it in the virtualenv (main.py): import subprocess result = subprocess.run('python other.py', stdout=subprocess.PIPE) but when I run main.py file: (venv)&gt; python main.py subprocess does not execute the command (python other.py) in the virtualenv i.e venv How to run subprocess command in the current virtualenv session?
has comment: http://stackoverflow.com/comment/88273314
has comment: http://stackoverflow.com/comment/88273696
type: Question
upvote count: 4
answer count: 2
has comment: http://stackoverflow.com/comment/88273192
accepted answer: http://stackoverflow.com/a/50631835
downvote count: 0
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/88273352
score: 4
has comment: http://stackoverflow.com/comment/88273757
has comment: http://stackoverflow.com/comment/88273288
favorite count: 0
tagged with: subprocess

http://stackoverflow.com/comment/88206329
comment on: http://stackoverflow.com/a/50597612
score: 0
type: AnswerComment
type: Comment
has text: @SebastianLoehner already gone through that..i could find only specific graph layouts like scatter plot or other 3D graphs , but not for bar/pie/donut

flask
tags question: http://stackoverflow.com/q/50598161
tags question: http://stackoverflow.com/q/50658118
tags question: http://stackoverflow.com/q/50667582
tags question: http://stackoverflow.com/q/50610342
tags question: http://stackoverflow.com/q/50691085
tags question: http://stackoverflow.com/q/50671251
tags question: http://stackoverflow.com/q/50695051
tags question: http://stackoverflow.com/q/50615247
tags question: http://stackoverflow.com/q/50547341
tags question: http://stackoverflow.com/q/50649510
tags question: http://stackoverflow.com/q/50560897
tags question: http://stackoverflow.com/q/50662832
tags question: http://stackoverflow.com/q/50574293
tags question: http://stackoverflow.com/q/50605738
tags question: http://stackoverflow.com/q/50684711
tags question: http://stackoverflow.com/q/50604860
tags question: http://stackoverflow.com/q/50600886
tags question: http://stackoverflow.com/q/50658705
tags question: http://stackoverflow.com/q/50619065
tags question: http://stackoverflow.com/q/50650500
tags question: http://stackoverflow.com/q/50617088
tags question: http://stackoverflow.com/q/50666582
tags question: http://stackoverflow.com/q/50600940
tags question: http://stackoverflow.com/q/50659044
tags question: http://stackoverflow.com/q/50647042
tags question: http://stackoverflow.com/q/50587076
tags question: http://stackoverflow.com/q/50667409
tags question: http://stackoverflow.com/q/50669231
tags question: http://stackoverflow.com/q/50612106
tags question: http://stackoverflow.com/q/50588658
tags question: http://stackoverflow.com/q/50628302
tags question: http://stackoverflow.com/q/50585496
tags question: http://stackoverflow.com/q/50691099
tags question: http://stackoverflow.com/q/50598405
tags question: http://stackoverflow.com/q/50590904
tags question: http://stackoverflow.com/q/50599276
tags question: http://stackoverflow.com/q/50613119
tags question: http://stackoverflow.com/q/50612866
tags question: http://stackoverflow.com/q/50634615
tags question: http://stackoverflow.com/q/50615812
tags question: http://stackoverflow.com/q/50544703
tags question: http://stackoverflow.com/q/50551097
tags question: http://stackoverflow.com/q/50632723
tags question: http://stackoverflow.com/q/50569205
tags question: http://stackoverflow.com/q/50665837
tags question: http://stackoverflow.com/q/50692249
tags question: http://stackoverflow.com/q/50675914
type: Tag
tags question: http://stackoverflow.com/q/50588346
tags question: http://stackoverflow.com/q/50684396
tags question: http://stackoverflow.com/q/50625452
tags question: http://stackoverflow.com/q/50684393
tags question: http://stackoverflow.com/q/50601567
tags question: http://stackoverflow.com/q/50684868
tags question: http://stackoverflow.com/q/50666852
tags question: http://stackoverflow.com/q/50544753
tags question: http://stackoverflow.com/q/50696587
tags question: http://stackoverflow.com/q/50548962
tags question: http://stackoverflow.com/q/50573718
tags question: http://stackoverflow.com/q/50614257
tags question: http://stackoverflow.com/q/50676656
tags question: http://stackoverflow.com/q/50601029
tags question: http://stackoverflow.com/q/50614437
tags question: http://stackoverflow.com/q/50652254
tags question: http://stackoverflow.com/q/50592736
tags question: http://stackoverflow.com/q/50595069
tags question: http://stackoverflow.com/q/50555668
tags question: http://stackoverflow.com/q/50684662
tags question: http://stackoverflow.com/q/50595269
tags question: http://stackoverflow.com/q/50555370
tags question: http://stackoverflow.com/q/50589906
tags question: http://stackoverflow.com/q/50594198
tags question: http://stackoverflow.com/q/50662377
tags question: http://stackoverflow.com/q/50652680
tags question: http://stackoverflow.com/q/50675518
tags question: http://stackoverflow.com/q/50604718
tags question: http://stackoverflow.com/q/50667537
tags question: http://stackoverflow.com/q/50565259
tags question: http://stackoverflow.com/q/50644215
tags question: http://stackoverflow.com/q/50605918

http://stackoverflow.com/a/50565709
answers question: http://stackoverflow.com/q/50564085
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88158405
has comment: http://stackoverflow.com/comment/88175205
type: Answer
has comment: http://stackoverflow.com/comment/88173068
has comment: http://stackoverflow.com/comment/88173066
has body: You are unnecessarily nesting your loops, and opening the same file thrice. But your real problem is that you inserted get_all; the list of lines, instead of the line. My suggestion: def show_team(): if event == 'Event 1': with open('data/tournamentdatae1.txt', 'r') as f: for i, line in enumerate(f, 1): if i == 1: team_1txt.insert(0.0, line) elif i == 2: team_2txt.insert(0.0, line) team_1txt = Text(root, width=10, height=1) team_1txt.place(x=100, y=210) team_2txt = Text(root, width=10, height=1) team_2txt.place(x=206, y=210)
accepted answer of: http://stackoverflow.com/q/50564085
score: 0

http://stackoverflow.com/comment/88333486
has text: Thanks. I do not have a background in C. This error was really hard for me to see. Do you have a background in C? Do you think that was the main trigger for you to see how to solve the problem?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50661253
type: AnswerComment

http://stackoverflow.com/q/50679664
has comment: http://stackoverflow.com/comment/88368742
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88368719
type: Question
has title: How can i modify a byte array?
tagged with: arrays
answer count: 1
downvote count: 0
score: 4
favorite count: 0
has body: I was reading about bytes and byte array's. I read that byte arrays mutable types! so, when i am trying to modify it i am getting an error saying integer is required Am i missing something here? The following is my code and the error z=bytearray("hello world","utf-8") z[0] ="H" i got the following error TypeError Traceback (most recent call last) in () ----> 1 z[0]="H" TypeError: an integer is required
upvote count: 4
has answer: http://stackoverflow.com/a/50679741
tagged with: python
accepted answer: http://stackoverflow.com/a/50679741

http://stackoverflow.com/q/50669877
has answer: http://stackoverflow.com/a/50670223
has comment: http://stackoverflow.com/comment/88349934
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/88349832
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/30328646
accepted answer: http://stackoverflow.com/a/50670223
has title: How to calculate the mean between multiple rows that matchs by a given id
type: Question
has comment: http://stackoverflow.com/comment/88350081
has comment: http://stackoverflow.com/comment/88349995
duplicate of: http://stackoverflow.com/q/30328646
has body: I want to calculate the mean of mulptiple rows that have one single value where they match and store it in another csv file. The given data is: ID salary days_of_work ... 1 2000 3 ... 1 1890 2 ... 1 2109 4 ... 2 . 2 . 2 . 2 3 3 ... And then obtain in another file, for every ID, one single row that contains the mean of the datas of the other columns like this: ID salary days_of_work ... 1 1999.6667 3 ... 2 ... 3 ... . . . Update: I tried to do this but for a file that has utc_time instead of ID import pandas as pd keep_col = ['utc_time','temperature','pressure','humidity','wind_direction','wind_speed/kph'] pd.read_csv('Gridpoints.csv', names=keep_col).to_csv("GridPoints/test.csv", index=False) f=pd.read_csv("Gridpoints"+".csv") df = f[keep_col] df.groupby(['utc_time']).mean() df.to_csv("GridPoints/test.csv", index=False) So first what I do is getting a column deleted and then on the dataframe obtained, I want to do it for the utc_time column but it doesn't do anything
score: 0
tagged with: pandas
answer count: 1

http://stackoverflow.com/comment/88217903
score: 2
comment on: http://stackoverflow.com/q/50604250
has text: This question would attract more interested readers (and probably a more favorable score) if you rewrote it as a [MCVE] that we can actually test and execute. For starters, we don't have the files you are opening. Can you reproduce the same problem without file access or with short dummy files that you include in your question? Second, there are a couple of lines in the code that don't seem to have much to do with the problem, try to shorten the code until you arrive at the smallest version that produces the problem. Third, comments in the code would be nice such that we can have a clue what
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50587634
favorite count: 0
type: UnansweredQuestion
has body: Former R user, I used to combine extensively ggplot and plot_ly libraries via the ggplotly() function to display data. Newly arrived in Python, I see that the ggplot library is available, but cant find anything on a simple combination with plotly for graphical reactive displays. What I would look for is something like : from ggplot import* import numpy as np import pandas as pd a = pd.DataFrame({'grid': np.arange(-4, 4), 'test_data': np.random.random_integers(0, 10,8)}) p2 = ggplot(a, aes(x = 'grid', y = 'test_data'))+geom_line() p2 ggplotly(p2) Where the last line would launch a classic plotly dynamic viewer with all the great functionalities of mouse graphical interactions, curves selections and so on... Thanks for your help :), Guillaume
tagged with: python
tagged with: ggplot2
tagged with: plotly
has comment: http://stackoverflow.com/comment/88186218
tagged with: ggplotly
score: 9
type: Question
has answer: http://stackoverflow.com/a/61512789
has title: Python ggplot and ggplotly
upvote count: 9
has answer: http://stackoverflow.com/a/59329003
answer count: 2
downvote count: 0

http://stackoverflow.com/q/50546497
has title: wget from Google shopping list
type: Question
tagged with: wget
downvote count: 0
score: 1
has body: I have a thermal printer that runs scripts daily to print my tasks (from a taskwarrior server) and weather. The next step is to try and get it to print my shopping list. There is no API for the shopping list, that I can find anyway, and my wget foo is weak. What I'd like to do is scrape the list from https://shoppinglist.google.com/lists/default and I can process it down to a format suitable for the thermal printer. I have tried variations on the following: wget --user USER --password PASS https://shoppinglist.google.com/lists/default But I keep getting stumped by the google login page. Can anyone make any suggestions for how I could tackle this? My output will then get parsed through a python script to eventually look something like this: - Item 1 - Item 2 - Item 3 - Item 4
favorite count: 0
has comment: http://stackoverflow.com/comment/90030349
tagged with: terminal
answer count: 0
type: UnansweredQuestion
tagged with: thermal-printer
upvote count: 1
tagged with: python

http://stackoverflow.com/a/50592125
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50591612
answers question: http://stackoverflow.com/q/50591612
upvote count: 2
has body: This is how you can get the content of that desired portion. I suppose, you can sort out the rest as per your requirement. import requests from bs4 import BeautifulSoup URL = 'http://www.agriculture.gov.au/pests-diseases-weeds/plant/khapra-beetle#see-if-you-can-identify-the-pest' res = requests.get(URL) soup = BeautifulSoup(res.text, "lxml") container = soup.select_one("#collapsefaq h3[title='expand section']") print(container.get_text(strip=True)) Output: See if you can identify the pest You can access the rest using: container = soup.select_one("#collapsefaq h3[title='expand section']").find_next_sibling() print(container.get_text(strip=True))

http://stackoverflow.com/a/50636681
has body: As noted above, this will not be feasible for any more than the number of letters countable on your two hands. There's just too many possibilities to check. But if you were to try this, here's how the code would look. letters = ['a', 'b', 'c'] def powerset(letters): output = [set()] for x in letters: output.extend([y.union({x}) for y in output]) return output for subset in powerset(letters): for potential_word in map(''.join, itertools.permutations(list(subset))): # Check if potential_word is a word This won't try words with duplicate letters (that would be another layer of insanity), but it will try all possible potential words that could be formed by a subset of the letters you give in any order. [edit] Just realized you requested a recursive solution. Dunno if that's required or not, but the powerset function could be changed to be recursive. I think that would make it uglier and harder to comprehend, though.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50633762

http://stackoverflow.com/q/50668357
has comment: http://stackoverflow.com/comment/88348753
tagged with: plotly
score: 0
type: Question
has title: Plotly chart not corresponding to time (x) data
has body: I'm a novice so this code is probably ugly ! I'm trying to chart the content of a simple dataframe (x=time, y=value) with the following code : import json import requests import pandas as pd import datetime import plotly.offline as py import plotly.graph_objs as go import plotly.figure_factory as ff py.init_notebook_mode(connected=True) starttime = time.time() now = datetime.datetime.now() json_url = 'https://poloniex.com/public?command=returnLoanOrders&amp;currency=MAID' json_backup = 'temp.json' data_store_filename = 'data_store.dat' df_store = pd.DataFrame(columns=["Time", "Average_Rate"]) df_store = pd.read_json(json_backup) while True: #download the data we want j = requests.get(url=json_url) content = json.loads(j.content) #create a dataframe with that data df = pd.DataFrame.from_dict(content['offers']) df = df'rate', 'amount', 'rangeMin', 'rangeMax' #Create a dateframe with the data we intend to store df_rate = pd.DataFrame(columns=["Time", "Average_Rate"]) #converts data type to float so that we can do some math on it df'rate' = df'rate'.astype(float) df'amount' = df'amount'.astype(float) #multiply the rate column by 100 to get the correct rate" df['rate'] *= 100 length = len(df.index) average_rate = df['rate'].sum() / length df_store = df_store.append({ "Time": datetime.datetime.now(), "Average_Rate": average_rate }, ignore_index=True) df_store.to_json(json_backup) backup = pd.read_json(json_backup) trace1 = go.Scatter( x = backup.Time, y = backup.Average_Rate, mode = 'lines', name = 'lines' ) py.iplot([trace1]) time.sleep(30.0 - ((time.time() - starttime) % 30.0)) I'm getting this weird chart that seem to go back in time. I did check my data and time is correct, the chart isn't. Can anyone explain me what is happening and how to avoid it ? Chart with error : Link
tagged with: pandas
has answer: http://stackoverflow.com/a/50669713
answer count: 1
accepted answer: http://stackoverflow.com/a/50669713
has comment: http://stackoverflow.com/comment/88348580
tagged with: python
type: AnsweredQuestion
tagged with: charts

http://stackoverflow.com/a/50670671
has comment: http://stackoverflow.com/comment/88365148
has body: Flask-restless wants the filter passed in the query string-- not as part of the data. That's why it's deleting all your data. It's not picking up the filter at all. Once that's fixed, you've got an additional problem in your filter itself. You're sending this as your filter: [ {'name': 'id', 'op': 'equals', 'val': 1}, {'name': 'id', 'op': 'equals', 'val': 2} ] A Flask-restless query considers something a match only if all of the filters are a match. In other words, it joins them all with an and: delete from message where id = 1 and id = 2 You'll either need to tell flask-restless that you want an 'or' [ { "or": [ {"name": "id", "op": "equals", "val": 1}, {"name": "id", "op": "equals", "val": 2} ] } ] Or change your filter operator to an 'in': [ {"name": "id", "op": "in", "val": [1, 2] } ] Try changing up your angular code to (note the change from data to params): $http({ method : 'DELETE', headers: {'X-CSRFToken' : csrf }, url : '/api/tbl_messages', params: { q : JSON.stringify({filters:[{or: create_filters}]}) } }) Or-- maybe a bit easier to follow-- change your operator to an 'in' and you can get rid of the forEach: $http({ method : 'DELETE', headers: {'X-CSRFToken' : csrf }, url : '/api/tbl_messages', params: { q : JSON.stringify({filters:[{name:'id', op:'in', val: $scope.deleteMessage}]}) } })
downvote count: 0
upvote count: 3
type: AcceptedAnswer
type: Answer
score: 3
accepted answer of: http://stackoverflow.com/q/50667409
answers question: http://stackoverflow.com/q/50667409

http://stackoverflow.com/comment/88169218
type: AnswerComment
has text: @PetPan if using option 1, use `defaultdict`. If it is still too slow, try my pandas option.
comment on: http://stackoverflow.com/a/50579722
type: Comment
score: 1

http://stackoverflow.com/a/50646879
type: Answer
has comment: http://stackoverflow.com/comment/88304469
has comment: http://stackoverflow.com/comment/88304259
score: 0
has body: You should use dictionnaries def function(grade) dict = {'A':4, 'B':3, 'C':2, 'D':1, 'F':0} if grade[1] == '+': return dict[grade[0]]+0.3 elif grade[1] == '-': return dict[grade[0]] - 0.3 Then add or substract 0.3 depending on the sign
answers question: http://stackoverflow.com/q/50646663
has comment: http://stackoverflow.com/comment/88304281

http://stackoverflow.com/a/50686741
has comment: http://stackoverflow.com/comment/103296383
upvote count: 19
downvote count: 0
has body: For multi-label classification, I think it is correct to use sigmoid as the activation and binary_crossentropy as the loss. If the output is sparse multi-label, meaning a few positive labels and a majority are negative labels, the Keras accuracy metric will be overflatted by the correctly predicted negative labels. If I remember correctly, Keras does not choose the label with the highest probability. Instead, for binary classification, the threshold is 50%. So the prediction would be [0, 0, 0, 0, 0, 1]. And if the actual labels were [0, 0, 0, 0, 0, 0], the accuracy would be 5/6. You can test this hypothesis by creating a model that always predicts negative label and look at the accuracy. If that's indeed the case, you may try a different metric such as top_k_categorical_accuracy. Another remote possibility I can think of is your training data. Are the labels y somehow "leaked" into x? Just a wild guess.
score: 19
type: Answer
has comment: http://stackoverflow.com/comment/103296364
answers question: http://stackoverflow.com/q/50686217

http://stackoverflow.com/q/50567008
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/88144749
favorite count: 0
has comment: http://stackoverflow.com/comment/88144332
has comment: http://stackoverflow.com/comment/88144745
has comment: http://stackoverflow.com/comment/88144767
tagged with: python
type: AnsweredQuestion
has body: I am using logistic regression for prediction. My predictions are 0's and 1's. After training my model on given data and also when training on important features i.e X_important_train see screenshot. I am getting score around 70% but when I use roc_auc_score(X,y) or roc_auc_score(X_important_train, y_train) I am getting value error: ValueError: multiclass-multioutput format is not supported Code: # Load libraries from sklearn.linear_model import LogisticRegression from sklearn import datasets from sklearn.preprocessing import StandardScaler from sklearn.metrics import roc_auc_score # Standarize features scaler = StandardScaler() X_std = scaler.fit_transform(X) # Train the model using the training sets and check score model.fit(X, y) model.score(X, y) model.fit(X_important_train, y_train) model.score(X_important_train, y_train) roc_auc_score(X_important_train, y_train) Screenshot:
has comment: http://stackoverflow.com/comment/88144887
has answer: http://stackoverflow.com/a/50567441
tagged with: logistic-regression
type: Question
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/88144681
has title: ValueError: multiclass-multioutput format is not supported using sklearn roc_auc_score function
tagged with: pandas
has comment: http://stackoverflow.com/comment/88144287
accepted answer: http://stackoverflow.com/a/50567441
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/88136020
has text: Thanks you for your answer, but I get this error: a = dict["name"] #To save the previous value TypeError: 'type' object is not subscriptable
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50562759
type: Comment

http://stackoverflow.com/comment/88400105
type: AnswerComment
comment on: http://stackoverflow.com/a/50691946
type: Comment
score: 2
has text: It processes `sample weight` in the same way it processes `X` and `y`. It is just another input array.

http://stackoverflow.com/a/50569630
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Ok, so it turned out that some migrations were being skipped (?) when calling python manage.py makemigrations so I had to specify which app that I wanted to make migrations for. Calling python manage.py makemigrations grams (my target app name) fixed the problem.
accepted answer of: http://stackoverflow.com/q/50544714
answers question: http://stackoverflow.com/q/50544714
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/103332859

http://stackoverflow.com/q/50558284
tagged with: python
has comment: http://stackoverflow.com/comment/88128479
has answer: http://stackoverflow.com/a/51397997
type: Question
has comment: http://stackoverflow.com/comment/88128436
has body: I am new to Keras. I want to build a CNN network with Keras. It is fine until I want to add a softmax dense layer. The error is TypeError: softmax() got an unexpected keyword argument 'axis'. I searched Keras and tried to fix it: from keras.layers import Softmax output_layer = Dense(units=n_classes, activation=Softmax(axis=-1), kernel_initializer='uniform') However, it still gives error plus the warning: UserWarning: Do not pass a layer instance (such as Softmax) as the activation argument of another layer. Instead, advanced activation layers should be used just like any other layer in a model. What is the correct method of applying softmax? Thank you very much. cnn = Sequential() kernelSize = (3, 3) ip_activation = 'relu' ip_conv_0 = Conv2D(filters=32, kernel_size=kernelSize, input_shape=im_shape, activation=ip_activation) cnn.add(ip_conv_0) ip_conv_0_1 = Conv2D(filters=64, kernel_size=kernelSize, activation=ip_activation) cnn.add(ip_conv_0_1) pool_0 = MaxPool2D(pool_size=(2, 2), strides=(2, 2), padding="same") cnn.add(pool_0) drop_layer_0 = Dropout(0.2) cnn.add(drop_layer_0) flat_layer_0 = Flatten() cnn.add(Flatten()) h_dense_0 = Dense(units=128, activation=ip_activation, kernel_initializer='uniform') cnn.add(h_dense_0) h_dense_1 = Dense(units=64, activation=ip_activation, kernel_initializer='uniform') cnn.add(h_dense_1) op_activation = 'softmax' output_layer = Dense(units=n_classes, activation=op_activation, kernel_initializer='uniform') cnn.add(output_layer)#&lt;---------error TypeError: softmax() got an unexpected keyword argument 'axis'
answer count: 1
tagged with: keras
has title: Softmatx activation in Keras
score: 0
type: UnansweredQuestion

http://stackoverflow.com/q/50652847
has comment: http://stackoverflow.com/comment/88316514
tagged with: sorting
favorite count: 0
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/50652880
possible better answer: http://stackoverflow.com/a/50652864
has answer: http://stackoverflow.com/a/50652902
has answer: http://stackoverflow.com/a/50652864
tagged with: python-3.x
upvote count: 3
has body: I have a list [25, 35, 54, 70, 68, 158, 78, 11, 18, 12] I want to sort this list by fixing the first element i.e: if I fix 35 the sorted list should look like [35, 54, 68, 70, 78, 158, 11, 12, 18, 25] If I fix 158 as the first element the sorted list should look like [158, 11, 12, 18, 25, 35, 54, 68, 70, 78] basically I want to fix the first element and the rest should be in sorted order, if there is a number that is lesser than the first element is found it should not go before first element. Is there a builtin function available for this in Python?
accepted answer: http://stackoverflow.com/a/50652902
type: AnsweredQuestion
score: 3
has title: Custom sort a list by fixing the first element
has answer: http://stackoverflow.com/a/50652891
type: Question
has answer: http://stackoverflow.com/a/50653167
downvote count: 0

http://stackoverflow.com/q/50668927
score: 0
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88349664
tagged with: python
has comment: http://stackoverflow.com/comment/88347695
has title: Error encountered while parsing a webpage in python
tagged with: python-requests
has comment: http://stackoverflow.com/comment/88347708
tagged with: urllib
type: Question
has body: I have a python script that takes a url as input and opens the url via urllib and parses a webpage. But I'm getting below error : Traceback (most recent call last): File "C:\Users\Arjun Gaur\Desktop\MyPython\arjurl.py", line 1, in &lt;module&gt; import urllib.request, urllib.parse, urllib.error File "C:\Users\Arjun Gaur\Desktop\MyPython\urllib.py", line 1, in &lt;module&gt; import urllib.request ModuleNotFoundError: No module named 'urllib.request'; 'urllib' is not a package below is the file arjsoup.py import urllib.request import urllib.parse import urllib.error import BeautifulSoup import ssl ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = print('Enter Link : ') urlstr = urllib.request.urlopen(url,context=ctx).read() soup = BeautifulSoup(urlstr,'html-parser') tags = soup('a') for tag in tags : print(tag.get('href',None))
has comment: http://stackoverflow.com/comment/88347869
has comment: http://stackoverflow.com/comment/88347592
tagged with: python-2.7

http://stackoverflow.com/comment/88327931
score: 0
comment on: http://stackoverflow.com/q/50658725
type: QuestionComment
type: Comment
has text: Take a look at this [Cross Validated post](https://stats.stackexchange.com/questions/138549/correct-arguments-for-svm-function-in-r). From what I can tell from a [number of posts](https://stackoverflow.com/questions/49281642/estimate-sigma-for-rbf-kernel-svm) I've found scattered about, `sigma = 1/gamma`.

http://stackoverflow.com/a/50552867
type: Answer
answers question: http://stackoverflow.com/q/50552803
score: 0
has body: primaryDict = {'list_a':['apple', 'orange'], 'list_b':['car', 'bus']} for listKey in primaryDict: primaryDict[i] = [{word:0} for word in primaryDict[listKey]] print(primaryDict) Output: {'list_a':[{'apple':0}, {'orange':0}], 'list_b':[{'car':0}, {'bus':0}]} Hope this helps!

http://stackoverflow.com/comment/88177134
score: 0
has text: ops, didn't run it and didn't remember how `np.empty` works. Fixed it
comment on: http://stackoverflow.com/a/50568615
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88274283
has text: 2 returns, only the first one will be returned, try `return response, data` and use the function accordingly, it will return a tuple now
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50632026

http://stackoverflow.com/comment/88253127
type: Comment
type: QuestionComment
has text: If you say `print` gives *\320\227\320*, then the correct literal for your string would be `"\\320\\227\\320"`, correct?
comment on: http://stackoverflow.com/q/50621340
score: 0

http://stackoverflow.com/comment/88327305
has text: @ElliottBrossard I have also tried using a DATETIME column and it fails as unable to parse the time-offset string.
type: AnswerComment
comment on: http://stackoverflow.com/a/50658417
score: 0
type: Comment

package
tags question: http://stackoverflow.com/q/50570312
tags question: http://stackoverflow.com/q/50580443
tag name: package
tags question: http://stackoverflow.com/q/50554467
tags question: http://stackoverflow.com/q/50585246
type: Tag
tags question: http://stackoverflow.com/q/50672238
tags question: http://stackoverflow.com/q/50542608
tags question: http://stackoverflow.com/q/50678754
tags question: http://stackoverflow.com/q/50647391

http://stackoverflow.com/a/50610360
has comment: http://stackoverflow.com/comment/88231799
downvote count: 0
answers question: http://stackoverflow.com/q/50610112
has comment: http://stackoverflow.com/comment/88232247
type: Answer
has body: Your generator is only calling random.uniform once. I think you want: def gen(useRandom, lowerBound, upperBound, stepSize = 1): for steppedVal in np.arange(lowerBound, upperBound, stepSize): if useRandom: randomVal = random.uniform(lowerBound, upperBound) yield randomVal else: yield steppedVal Now, your output becomes: (4.229914739995998, 10) (4.229914739995998, 15) (4.229914739995998, 20) (4.229914739995998, 25) (5.52362641577289, 10) (5.52362641577289, 15) (5.52362641577289, 20) (5.52362641577289, 25) (4.507985392309242, 10) (4.507985392309242, 15) (4.507985392309242, 20) (4.507985392309242, 25) which shows you get three different random values, corresponding to the three times the first instance of the generator runs. Note, also, you may want to look at random.randrange, which essentially returns a random integer from range(lowerBound, upperBound, stepSize). If you replace random.uniform(lowerBound, upperBound) with random.randrange(lowerBound, upperBound, stepSize) in the generator function, you get the output: (5, 10) (5, 15) (5, 20) (5, 25) (3, 10) (3, 15) (3, 20) (3, 25) (3, 10) (3, 15) (3, 20) (3, 25) This time, the generator picked a random number from the set [3,4,5] on each iteration. Note that this doesn't necessarily yield unique numbers on each iteration! You can use random.shuffle if that's what you're looking for.
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/88231280
has comment: http://stackoverflow.com/comment/88231521

http://stackoverflow.com/comment/88284177
type: Comment
type: QuestionComment
has text: LabelEncoder produces a Ordinal encoding. Also the documentation of "encode categorical integer features using a one-hot aka one-of-K scheme" in LabelEncoder is for the description of OneHotEncoder in the see-also section, and does not apply to LabelEncoder.
comment on: http://stackoverflow.com/q/50579544
score: 0

http://stackoverflow.com/a/50667547
answers question: http://stackoverflow.com/q/50667406
has comment: http://stackoverflow.com/comment/88345485
type: Answer
has comment: http://stackoverflow.com/comment/88345751
downvote count: 0
has comment: http://stackoverflow.com/comment/88346274
score: 13
upvote count: 13
has body: For Python 2 consider using the StringIO module instead of io. Code: from StringIO import StringIO Test Code: from StringIO import StringIO output = StringIO() output.write(u'First line.\n') print u'Second line.' print &gt;&gt;output, u'Second line.' contents = output.getvalue() print contents output.close() Results: Second line. First line. Second line.

http://stackoverflow.com/comment/88380793
type: QuestionComment
comment on: http://stackoverflow.com/q/50679145
has text: that pattern doesn't mean anything in python [`re`](https://docs.python.org/3/library/re.html). have a look in the docs, show us what you got and you'll get some help
score: 0
type: Comment

http://stackoverflow.com/comment/88347066
comment on: http://stackoverflow.com/q/50667903
type: QuestionComment
has text: @erip-Thanks for your answer very sure about how to interpret but was looking for same functionality as in R -[https://www.rdocumentation.org/packages/stats/versions/3.5.0/topics/t.test]
type: Comment
score: 0

http://stackoverflow.com/comment/88137661
score: 0
comment on: http://stackoverflow.com/q/50563462
type: QuestionComment
type: Comment
has text: What do you expect from `if not driver.find_element_by_link_text('»')`? If there is no such element, you will get `NoSuchElementException`. `break` (I suppose that provided code is a part of loop) will never be executed. Also note that I've already share the [solution](https://stackoverflow.com/questions/50529563/how-to-get-attribute-value-selenium-python/50530329#50530329) - leave comment under the answer if you need some clarifications instead of submiting new question regarding the same issue...

http://stackoverflow.com/comment/88138972
comment on: http://stackoverflow.com/q/50564348
score: 0
type: QuestionComment
type: Comment
has text: When you assign `tempRow = rows[0]`, that doesn't make a copy of the dict in `rows[0]`. When you modify `tempRow`, you modify `rows[0]` as well. Use `tempRow = rows[0].copy()` instead.

http://stackoverflow.com/comment/88175047
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50582560
has text: I fear you would say that. The problem is im not exactly sure where to start making this minimal example. I will try to see if i can pinpoint the problem. This is of course more problematic for me since i don't speak C.

http://stackoverflow.com/a/50688908
type: AcceptedAnswer
has body: You need: import matplotlib.dates as mdates list_dates = ['2018-04-23 00:02:01', '2018-04-23 00:05:03', '2018-04-23 00:08:05', '2018-04-23 00:12:01'] df = pd.DataFrame({ 'date':list_dates, 'col':[10,20,30,40] }) df['date'] = pd.to_datetime(df['date']) fig = plt.figure() ax = fig.add_subplot(111) ax.plot_date(df['date'], df['col']) myFmt = mdates.DateFormatter('%H:%M:%S') ax.xaxis.set_major_formatter(myFmt) Output:
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50688595
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50688595

http://stackoverflow.com/q/50633359
score: 2
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/50634954
tagged with: tornado
upvote count: 2
answer count: 1
tagged with: websocket
has comment: http://stackoverflow.com/comment/88278841
has body: I am new to Python and the problem I'm trying to solve is to have an on-going websocket connection that can take in requests, wait some time while doing calcs, return results when ready while not blocking other requests that come from other users/clients/connections. I have achieved this and it works rather nicely but wanted to check if this is the right solution. In this particular snippet they key bit is actions performed upon open: I spin off another thread with sleep. import tornado.web import tornado.websocket import tornado.httpserver import tornado.ioloop import time import json from tornado import gen from concurrent.futures import ThreadPoolExecutor from tornado.options import define, options, parse_command_line define("port", default=8888, type=int) thread_pool = ThreadPoolExecutor(2) class WebSocketHandler(tornado.websocket.WebSocketHandler): # Make this an asynchronous coroutine @gen.coroutine def on_message_coroutine(self, message): self.write_message('Message:', message) def worker_A(websocket, x): time.sleep(1) print('TICK', x) pass return x print('scheduling and yielding') for x in range(0, 30): test = yield thread_pool.submit(worker_A, self, x) self.write_message(json.dumps(test)) print('done yielding') def open(self, *args): print("New connection") tornado.ioloop.IOLoop.current().spawn_callback(self.on_message_coroutine, 'New Msg') def check_origin(self, origin): return True def on_message(self, message): print("New message {}".format(message)) self.write_message("You sent me this, sending it back in upper: " + message.upper()) def on_close(self): print("Connection closed") app = tornado.web.Application([ (r'/ws/', WebSocketHandler), ]) if __name__ == '__main__': app.listen(options.port) tornado.ioloop.IOLoop.instance().start() Output on front-end's console below. "New message" bit is when I click the buttons while websocket is continuously returning other output (TICKS): app.component.ts:17 Response from websocket: 11 app.component.ts:17 Response …
has title: Tornado WebSockets non-blocking requests using threading. Am I doing it right?
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50651108
favorite count: 0
has title: Pandas gives different results for different machines
type: UnansweredQuestion
has body: When I upgraded from numpy 1.9 to 1.10 I started to see that the following regression model gives different results on different machines with the same hardware configuration: fitted_model = pd.ols(y=lhs_unpickled, x=rhs_unpickled, intercept=False) print fitted_model.beta lhs_unpickled and rhs_unpickled look like this: &gt; lhs_unpickled[1:5] 2008-04-24 00:18:00+00:00 -0.465517 2008-04-24 00:33:00+00:00 -0.519584 2008-04-24 00:48:00+00:00 -0.607410 2008-04-24 01:03:00+00:00 -0.705983 Freq: 15T, Name: AI_Index, dtype: float64 &gt; rhs_unpickled[1:5] CPM XQH FOD EX 2008-04-24 00:18:00+00:00 -0.301556 0.148582 0.079320 -0.707586 2008-04-24 00:33:00+00:00 -0.274421 0.071747 0.130182 -0.659409 2008-04-24 00:48:00+00:00 -0.273960 -0.001447 0.148643 -0.703215 2008-04-24 01:03:00+00:00 -0.238426 -0.008732 0.130801 -0.698489 Is there something specific about this pd.ols() function which results in this inconsistent behavior when using numpy 1.10?
tagged with: python
has comment: http://stackoverflow.com/comment/88313907
answer count: 0
has comment: http://stackoverflow.com/comment/88315720
has comment: http://stackoverflow.com/comment/88315233
type: Question
tagged with: stat
score: 4
upvote count: 4
tagged with: numpy
tagged with: pandas
has comment: http://stackoverflow.com/comment/88313804
downvote count: 0
has comment: http://stackoverflow.com/comment/88314676

http://stackoverflow.com/a/50562759
has comment: http://stackoverflow.com/comment/88136433
upvote count: 2
has body: D = {'lastExecution': '1-1-1970', 'wachtwoord': 'wachtwoord', 'name': {'laatsteUpdate': '1-1-1970', 'puntenAantal': '0'}} a = D['name'] #To save the previous value D['new key'] = a del D['name']
has comment: http://stackoverflow.com/comment/88136033
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88173838
has comment: http://stackoverflow.com/comment/88136256
has comment: http://stackoverflow.com/comment/88136020
answers question: http://stackoverflow.com/q/50562688
has comment: http://stackoverflow.com/comment/88136281

http://stackoverflow.com/comment/88348586
comment on: http://stackoverflow.com/a/50669187
type: AnswerComment
score: 0
has text: Well if you have all the combinations of teams and ids you can create dict from that and save yourself from typing
type: Comment

http://stackoverflow.com/q/50645645
score: 0
has comment: http://stackoverflow.com/comment/88301992
has answer: http://stackoverflow.com/a/50646093
answer count: 1
has title: Webscraping from a script
has comment: http://stackoverflow.com/comment/88306787
has comment: http://stackoverflow.com/comment/88302113
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
has body: I'm trying to extract the language proportion spoken at companies, using python's BeautifulSoup. Yet, the information seems to come from a script, not from HTML, and I'm having some trouble. For instance, from the following page, when I try webpage ="https://www.zippia.com/amazon-com-careers-487/" page = requests.get(webpage) soup = BeautifulSoup(page.content, 'lxml') for links in soup.find_all('div', {'class':'companyEducationDegrees'}): raw_text = links.get_text() lines = raw_text.split('\n') print(lines) print('-------------------') I don't get any result while the ideal result should be Spanish 61.1%, French 9,7%, etc
has comment: http://stackoverflow.com/comment/88302096
type: Question

http://stackoverflow.com/q/50569760
has title: Regex Issue with Python re
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50570091
score: 1
tagged with: re2
has body: Trying to use the python re package to look for filenames with a certain pattern. Got a wee test script which just has all values hardcoded in but this isn't the normal use: #!/usr/bin/env python try: import re2 as re except ImportError: import re filepath1 = "C:\Users\Administrator\AppData\Local\Temp\77ce4ba2a605e22b8699eef874d075fb585d259ed6cade2e503e6dbf58020aa0.exe:Zone.Identifier" filepath2 = "C:\Users\Administrator\AppData\Local\Temp\svchost.exe:Zone.Identifier" re_pattern = re.compile("C\:\\\\Users\\\\[^\\\\]*\\\\AppData\\\\Local\\\\Temp\\\\[^.]*\.exe\:Zone\.Identifier") print "1: " + str(re_pattern.search(filepath1)) print "2: " + str(re_pattern.search(filepath2)) For some reason this returns None for 1 and a match for 2, but as far as I can work out they should both be matching. Probably just a stupid mistake but if someone can spot it that would be awesome. Basically the pattern should match any .exe with a Zone ID in the %TEMP% directory, regardless of username
answer count: 2
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/50570091
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/50570090
has comment: http://stackoverflow.com/comment/88149781
possible better answer: http://stackoverflow.com/a/50570090
upvote count: 1

http://stackoverflow.com/comment/88347377
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50611456
has text: Hypothesis looks interesting, but (as you say) it is somewhat unrelated to the particulars of this question. Still might look into it, thanks for the pointer!

http://stackoverflow.com/q/50683540
type: Question
tagged with: dcgan
tagged with: loss
has body: I am trying to train DCGAN on the "Labeled Faces in the Wild" dataset with image shape (64,64,3). After training for 1000 or more epochs it is generating just noise. The code is as follows: class GAN(): img_rows = 64 img_cols = 64 channels = 3 optimizer_G = Adam(0.0002, 0.5) optimizer_D = Adam(0.0002, 0.5) def __init__(self): # Initialize self.img_rows = img_rows self.img_cols = img_cols self.channels = channels self.img_shape = (self.img_rows, self.img_cols, self.channels) self.latent_dim = 100 # Build the discriminator self.discriminator = self.build_discriminator() # Build the generator self.generator = self.build_generator() # The generator takes noise as input and generates imgs z = Input(shape=(100,)) img = self.generator(z) # For the combined model we will only train the generator self.discriminator.trainable = False # The discriminator takes generated images as input and determines validity validity = self.discriminator(img) # The combined model (stacked generator and discriminator) # Trains the generator to fool the discriminator self.combined = Model(inputs=z, outputs=validity) self.combined.compile(loss='binary_crossentropy', optimizer=optimizer_G) def build_generator(self): input_shape = (self.img_rows, self.img_cols, self.channels) mom=0.8 generator = Sequential() generator.add(Dense(units= 512*4*4, kernel_initializer='glorot_uniform', input_dim=100)) generator.add(Reshape(target_shape=(4, 4, 512))) generator.add(BatchNormalization(momentum=0.5)) generator.add(Activation('relu')) generator.add(Conv2DTranspose(filters=256, kernel_size=(5, 5), strides=(2, 2), padding='same', data_format='channels_last', kernel_initializer='glorot_uniform')) generator.add(BatchNormalization(momentum=mom)) generator.add(Activation('relu')) generator.add(Conv2DTranspose(filters=128, kernel_size=(5, 5), strides=(2, 2), padding='same', data_format='channels_last', kernel_initializer='glorot_uniform')) generator.add(BatchNormalization(momentum=mom)) generator.add(Activation('re…
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/90661434
answer count: 1
downvote count: 0
has title: DCGAN generating just noise
favorite count: 0
tagged with: noise
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90514048
has comment: http://stackoverflow.com/comment/90680159
has answer: http://stackoverflow.com/a/55054278
score: 1

http://stackoverflow.com/q/50674321
type: UnansweredQuestion
tagged with: pandas
answer count: 0
downvote count: 0
linked to: http://stackoverflow.com/q/4182603
score: 1
has comment: http://stackoverflow.com/comment/88394410
has body: I'm having a problem with uploading python pandas df to bigquery using the df.to_gbq function.The issue arises from non latin (and non ascii) chars in the df. when I try to upload the df I get this error: 'latin-1' codec can't encode characters in position 126-129: Body ('עמית') is not valid Latin-1. Use body.encode('utf-8') if you want to send it encoded in UTF-8. even if the df encoding is utf-8, suggesting that the function converts to latin-1 prior to uploading to BQ and therefore can't handle any non -latin chars. I couldn't find any argument of the function that will allow me to change the encoding. I also tried to upload the same data from csv file and a utf-8 csv could be uploaded directly, but not when I first uploaded the data to pandas DF (using read_csv func) and then to BQ. Any suggestions how to correctly upload this df to BQ ? Any workarounds (I just need it uploaded, not necessarily using pandas to_gbq)? thanks
favorite count: 0
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/88361395
has comment: http://stackoverflow.com/comment/88367298
upvote count: 1
tagged with: google-bigquery
has title: python pandas to bigquery encoding issues
has comment: http://stackoverflow.com/comment/88391773

http://stackoverflow.com/a/50686847
answers question: http://stackoverflow.com/q/50686771
has body: That's not how you run pip... You run it from the system shell like this &gt; pip install gTTS or &gt; python -m pip install gTTS If you want to run it from inside a script, or a python shell you do it like this import pip def install(package): pip.main(['install', package]) # Example if __name__ == '__main__': install('gTTS')
has comment: http://stackoverflow.com/comment/88423620
type: Answer
has comment: http://stackoverflow.com/comment/88385823
downvote count: 0
score: 2
upvote count: 2

http://stackoverflow.com/comment/88138256
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50563964
type: QuestionComment
has text: When asking a question, you will get much better answers if you provide code. Paste code, not image. Please check [How to create a Minimal, Complete, and Verifiable](https://stackoverflow.com/help/mcve)

http://stackoverflow.com/comment/88355998
score: 0
type: Comment
type: QuestionComment
has text: @cricket_007 Sorry I am fairly new to this site. I'll take that into account next time.
comment on: http://stackoverflow.com/q/50673065

http://stackoverflow.com/a/50672715
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88355982
has comment: http://stackoverflow.com/comment/88356012
type: Answer
has comment: http://stackoverflow.com/comment/88355766
accepted answer of: http://stackoverflow.com/q/50672603
has body: Here's a quick solution that will populate a single object with the column names you're looking for: import csv o = {} cols = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o'] with open('data_peng.txt', 'r') as csvin: csvin = csv.reader(csvin) for row in csvin: for idx, col in enumerate(cols): o.setdefault(col, []).append(row[idx]) print o['c']
has comment: http://stackoverflow.com/comment/88357612
answers question: http://stackoverflow.com/q/50672603
score: 1
upvote count: 1

http://stackoverflow.com/comment/88190031
comment on: http://stackoverflow.com/q/50589552
has text: I think you might be right, I'm looking into how to mock/patch existing usage of `SomeClass` with one that simply patch one default input parameter.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/88358169
type: Comment
has text: Yeah, that's why I am confused. Why does it say my portfolio.settings only have 1 entry in ALLOWED_HOSTS, but I obviously have 3.
type: AnswerComment
comment on: http://stackoverflow.com/a/50674132
score: 0

http://stackoverflow.com/a/50617036
answers question: http://stackoverflow.com/q/50616631
has comment: http://stackoverflow.com/comment/88246273
has comment: http://stackoverflow.com/comment/88244522
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50616631
has comment: http://stackoverflow.com/comment/88243923
has comment: http://stackoverflow.com/comment/88246550
has body: As soon as you click on submit button , I am assuming (which is highly likely) that redirection occurs. after click on submit button , your will be redirected to a new Page which will have some contents, right? What you have to do here : element = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((Locator, "value"))).text and you already know the value , which will be expected value. Now you can assert these two value. UPDATE : As you have mentioned, that a table appears , now what you can do here is : wait for visibility of table and get the heading of table using .text and assert the value.
has comment: http://stackoverflow.com/comment/88243857
has comment: http://stackoverflow.com/comment/88244212
type: AcceptedAnswer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88245960
type: Answer
has comment: http://stackoverflow.com/comment/88247589

http://stackoverflow.com/comment/94158684
score: 0
comment on: http://stackoverflow.com/q/50618271
has text: I have the same issue, wonder why no one has answered.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88221039
comment on: http://stackoverflow.com/q/50605558
has text: Yup it would work if i had a file reader, but it's a csv reader so i can't apply the seek attribute...
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50543362
score: 0
has body: I'd iterate over the list and find the two largest elements. Then, if the largest element is at least twice as large as the second largest, you can return its index. def dominantIndex(nums): # Assumption - nums has a length of at least 2. # Bootsrap the rist two indexes if nums[0] &gt; nums[1]: max_ind = 0 next_ind = 1 else: max_ind = 1 next_ind = 0 # Go over the rest for i in range(2, len(nums)): if nums[i] &gt; nums[max_ind]: next_ind = max_ind max_ind = i elif nums[i] &gt; nums[next_ind]: next_ind = i if nums[max_ind] &gt;= nums[next_ind] * 2: retrun max_ind return -1
answers question: http://stackoverflow.com/q/50543265
type: Answer

http://stackoverflow.com/comment/88231149
type: AnswerComment
comment on: http://stackoverflow.com/a/50593396
score: 0
type: Comment
has text: You need to call `bin_combs_iter` recursively, not `bin_combs`, or you'll use lots of memory for large inputs.

http://stackoverflow.com/comment/88153900
score: 0
comment on: http://stackoverflow.com/q/50543232
has text: you are setting `enable_utc = True` after `timezone = 'Europe/Minsk'` which resets it to use UTC instead (you were setting it to run at 16:04 localtime, right?)
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50558091
has comment: http://stackoverflow.com/comment/88214507
score: 0
answers question: http://stackoverflow.com/q/50557004
has body: almost any time series data could be modeled by HMM. transition matrix should be estimated from the data using well known Baum-Welch algorithm.Simple tutorial from Wikipedia should give u a hints.
type: Answer

http://stackoverflow.com/comment/88305503
comment on: http://stackoverflow.com/q/50647260
has text: Just need to match two lists, then idealy terminate after matching two list
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50620935
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88251987
upvote count: 1
has comment: http://stackoverflow.com/comment/88253113
score: 1
has comment: http://stackoverflow.com/comment/88253091
has body: Use: df = (pd.DataFrame([dict.fromkeys(range(a, b + 1), 1) for a, b in zip(df[0], df[1])]) .reindex(columns=range(1, 25), fill_value=0) .fillna(0) .astype(int)) print (df) 1 2 3 4 5 6 7 8 9 ... 16 17 18 19 20 21 22 23 24 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 1 0 0 1 1 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 1 1 0 0 ... 0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 ... 1 0 0 0 0 0 0 0 0 [5 rows x 24 columns]
answers question: http://stackoverflow.com/q/50620755

http://stackoverflow.com/comment/88153890
type: QuestionComment
type: Comment
score: 0
has text: I recommend you execute it from the CMD directly and indicate the error message, your problem is very common and can be easily solved if you provide the error message.
comment on: http://stackoverflow.com/q/50557450

http://stackoverflow.com/a/50652487
type: Answer
accepted answer of: http://stackoverflow.com/q/50652046
score: 1
upvote count: 1
has body: You want unstack(): https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html It will move one of the index levels to be a column in the DataFrame. Something like this: df.unstack('Date')
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50652046

http://stackoverflow.com/comment/88325022
type: QuestionComment
comment on: http://stackoverflow.com/q/50657425
score: 0
has text: Tensorboard shouldnt need a gpu. Tensorboard's main role is to parse events pb files and display them on the web. There is not any heavy computing and the GPU shouldnt be needed? How are you installing tensorflow?
type: Comment

http://stackoverflow.com/q/50672941
has body: I am taking a course on Udemy and I came across this error when running python manage.py migrate The error is: TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime' Here is my code: from django.conf import settings from django.db import models # Create your models here. class Tweet(models.Model): # user user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = models.CharField(max_length=140) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.content) My traceback: File "manage.py", line 15, in &lt;module&gt; execute_from_command_line(sys.argv) File "/Users/isaac/Dev/tweetme/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/isaac/Dev/tweetme/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/isaac/Dev/tweetme/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/Users/isaac/Dev/tweetme/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/Users/isaac/Dev/tweetme/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 200, in handle fake_initial=fake_initial, File "/Users/isaac/Dev/tweetme/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/isaac/Dev/tweetme/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Users/isaac/Dev/tweetme/lib/python3.6/site-packages/django/db/migrations/ex…
favorite count: 0
has comment: http://stackoverflow.com/comment/88356187
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88356152
answer count: 0
type: UnansweredQuestion
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/88356224
type: Question
score: 1
tagged with: django-models
has comment: http://stackoverflow.com/comment/88356245
downvote count: 0
has title: TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime' when running python manage.py migrate

http://stackoverflow.com/q/50621438
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50622409
has body: Some widgets in wxPython has a method like "GetSelections()" which returns a list of indexes of selected items. Having this list of index I can get a list of items. This way, for example: &gt;&gt;&gt; list_of_items = ['zero', 'one', 'two', 'three', 'four', 'five'] &gt;&gt;&gt; list_of_indexes = [1,3,5] &gt;&gt;&gt; [list_of_items[e] for e in list_of_indexes] ['one', 'three', 'five'] So the question is: is there a shortcut for last string? Something like: list_of_items.getitems(list_of_indexes) Thanks!
tagged with: python
has title: Looking for function to shorten the list
type: AnsweredQuestion
tagged with: list
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/50622409
type: Question
tagged with: indexing
answer count: 1
tagged with: wxpython
downvote count: 0

http://stackoverflow.com/q/50651841
has body: I need to search for around 57K entries within a catalog containing thousands of backup files, 8 Gb in total . I tried grep -f on a modern server but that overwhelmed the memory made the machine unresponsive . A normal grep for a single entry takes around 50 seconds. My next idea is to try to grep, for exemple, 100 or maybe 1000 entries at a time, but i doubt that would be fast. Does anyone have an idea or an example of how to do this in an efficient and fast way? I am most comfortable with bash and Python.
has comment: http://stackoverflow.com/comment/88314726
tagged with: search
score: 0
tagged with: bash
has title: Search huge amount of entries in giant catalog of text files, python/bash
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88319142
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/88314661
tagged with: performance

numpy
tags question: http://stackoverflow.com/q/50679177
tags question: http://stackoverflow.com/q/50676331
tags question: http://stackoverflow.com/q/50567706
tags question: http://stackoverflow.com/q/50684013
tags question: http://stackoverflow.com/q/50662077
tags question: http://stackoverflow.com/q/50542815
tags question: http://stackoverflow.com/q/50570813
tags question: http://stackoverflow.com/q/50692026
tags question: http://stackoverflow.com/q/50655175
tags question: http://stackoverflow.com/q/50554272
tags question: http://stackoverflow.com/q/50687234
tags question: http://stackoverflow.com/q/50579027
tags question: http://stackoverflow.com/q/50614545
tags question: http://stackoverflow.com/q/50580459
tags question: http://stackoverflow.com/q/50640254
tags question: http://stackoverflow.com/q/50582179
tags question: http://stackoverflow.com/q/50649944
tags question: http://stackoverflow.com/q/50684255
tags question: http://stackoverflow.com/q/50573677
tags question: http://stackoverflow.com/q/50686319
tags question: http://stackoverflow.com/q/50649236
tags question: http://stackoverflow.com/q/50547249
tags question: http://stackoverflow.com/q/50589019
tags question: http://stackoverflow.com/q/50676948
tags question: http://stackoverflow.com/q/50611772
tags question: http://stackoverflow.com/q/50668651
tags question: http://stackoverflow.com/q/50655906
tags question: http://stackoverflow.com/q/50558798
tags question: http://stackoverflow.com/q/50628500
tags question: http://stackoverflow.com/q/50571299
tags question: http://stackoverflow.com/q/50627218
tags question: http://stackoverflow.com/q/50697171
tags question: http://stackoverflow.com/q/50580391
tags question: http://stackoverflow.com/q/50630101
tags question: http://stackoverflow.com/q/50610728
tags question: http://stackoverflow.com/q/50586926
tags question: http://stackoverflow.com/q/50542864
tags question: http://stackoverflow.com/q/50689040
tags question: http://stackoverflow.com/q/50676698
tags question: http://stackoverflow.com/q/50675705
tags question: http://stackoverflow.com/q/50582782
tags question: http://stackoverflow.com/q/50661967
tags question: http://stackoverflow.com/q/50569070
tags question: http://stackoverflow.com/q/50693921
tags question: http://stackoverflow.com/q/50553645
tags question: http://stackoverflow.com/q/50653773
tags question: http://stackoverflow.com/q/50593424
tags question: http://stackoverflow.com/q/50615463
tags question: http://stackoverflow.com/q/50572894
tags question: http://stackoverflow.com/q/50552896
tags question: http://stackoverflow.com/q/50643760
tags question: http://stackoverflow.com/q/50641824
tags question: http://stackoverflow.com/q/50570067
tags question: http://stackoverflow.com/q/50668290
tags question: http://stackoverflow.com/q/50593483
tags question: http://stackoverflow.com/q/50670263
tags question: http://stackoverflow.com/q/50680783
tags question: http://stackoverflow.com/q/50696357
tags question: http://stackoverflow.com/q/50654432
tags question: http://stackoverflow.com/q/50692478
tags question: http://stackoverflow.com/q/50653035
tags question: http://stackoverflow.com/q/50595150
tags question: http://stackoverflow.com/q/50664425
tags question: http://stackoverflow.com/q/50644832
tags question: http://stackoverflow.com/q/50658111
tags question: http://stackoverflow.com/q/50604298
tags question: http://stackoverflow.com/q/50627658
tags question: http://stackoverflow.com/q/50553211
tags question: http://stackoverflow.com/q/50565322
tags question: http://stackoverflow.com/q/50668453
tags question: http://stackoverflow.com/q/50686742
tags question: http://stackoverflow.com/q/50560896
tags question: http://stackoverflow.com/q/50571381
tags question: http://stackoverflow.com/q/50685406
tags question: http://stackoverflow.com/q/50644639
tags question: http://stackoverflow.com/q/50602160
tags question: http://stackoverflow.com/q/50671172
tags question: http://stackoverflow.com/q/50575540
tags question: http://stackoverflow.com/q/50673243
tags question: http://stackoverflow.com/q/50632435

http://stackoverflow.com/comment/88142421
type: AnswerComment
comment on: http://stackoverflow.com/a/50564463
score: 0
type: Comment
has text: Does Python write to the on-disk file when `write` is called, or only when `close` is called? If the latter (which I believe is the case), it won't really be memory efficient...

http://stackoverflow.com/q/50660617
score: 0
accepted answer: http://stackoverflow.com/a/50664779
answer count: 1
has comment: http://stackoverflow.com/comment/88332493
has body: I am trying to take a file that is in UTF-16 format and then syslog it out to a syslog server in UTF-8 format. i am pretty new to python and programming. Everything is working except that it's not sending it out as UTF-8 in the syslog. Code import logging import logging.handlers import tailer import os import codecs logger = logging.getLogger('myLogger') logger.setLevel(logging.INFO) #add handler to the logger handler = logging.handlers.SysLogHandler(address=('x.x.x.x', 514)) #add formatter to the handler formatter = logging.Formatter('') handler.formatter = formatter logger.addHandler(handler) while True: for line in tailer.follow(open('z:\\ERRORLOG')): logger.info(str.decode('utf-8'), line) i also tried the below at the end while True: for line in tailer.follow(open('z:\\ERRORLOG')): logger.info(str(line, 'utf-8'))
has answer: http://stackoverflow.com/a/50664779
tagged with: decoding
tagged with: python
type: AnsweredQuestion
has title: cant figure out how to read from utf-16 file and syslog it out to utf-8
has comment: http://stackoverflow.com/comment/88331305
type: Question
has comment: http://stackoverflow.com/comment/88331280
has comment: http://stackoverflow.com/comment/88331302
has comment: http://stackoverflow.com/comment/88331307

http://stackoverflow.com/comment/88299689
comment on: http://stackoverflow.com/q/50644652
has text: you're absolutely right.. thank you for the reminder!
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50605634
has comment: http://stackoverflow.com/comment/88221956
has comment: http://stackoverflow.com/comment/88223186
has body: I would personally do this. Considering your example data.csv... id,q1,q2,q3 1,5,3,1 2,3,4,1 3,2,3,1 My solution would do... import pandas as pd df = pd.read_csv('test_csv.csv') print df id q1 q2 q3 0 1 5 3 1 1 2 3 4 1 2 3 2 3 1 my_rates = [1, 2, 3, 4, 5] df['q2'] = df['q2'].apply(lambda x:my_rates[-x]) print df id q1 q2 q3 0 1 5 3 1 1 2 3 2 1 2 3 2 3 1 Benchmark With larger datasets, results change drastically. import pandas as pd import timeit df = pd.read_csv('test_csv.csv') df = pd.concat([df] * 1000, ignore_index=True) def imcoins(df): my_rates = [1, 2, 3, 4, 5] df['Q2'] = df['Q2'].apply(lambda x:my_rates[-x]) return df def joe(df): df['Q2'] = df['Q2'].map({1:5, 2:4, 3:3, 4:2, 5:1}) return df def jez(df): df.Q2 = 6 - df.Q2 return df def jez_2(df): df.Q2 = df.Q2.rsub(6) return df def jez_3(df): df.Q2 = 6 - df.Q2.values return df nb = 10000 t1 = timeit.timeit(stmt='imcoins(df)', setup='from __main__ import imcoins, df', number=nb) t2 = timeit.timeit(stmt='joe(df)', setup='from __main__ import joe, df', number=nb) t3 = timeit.timeit(stmt='jez(df)', setup='from __main__ import jez, df', number=nb) t4 = timeit.timeit(stmt='jez_2(df)', setup='from __main__ import jez_2, df', number=nb) t5 = timeit.timeit(stmt='jez_3(df)', setup='from __main__ import jez_3, df', number=nb) print 'IMCoins : {}\njoe : {}\njezrael_1 : {}\njezrael_2 : {}\tjezrael_3 : {}'.format(t1, t2, t3, t4, t5) # Python 2.7 IMCoins : 3.85911526513 joe : 1.26151379163 jezrael_1 : 0.487986194544 jezrael_2 : 0.613230951967 jezrael_3 : 0.287318529541 # Python 3.6 IMCoins : 2.0433933256597467 joe : 1.3545644831475654 jezrael_1 : 0.482208606992109 jezrael_2 : 0.5195013265458606 jezrael_3 : 0.27176954323496627
has comment: http://stackoverflow.com/comment/88223353
type: Answer
answers question: http://stackoverflow.com/q/50605424
has comment: http://stackoverflow.com/comment/88222957
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88222004
has comment: http://stackoverflow.com/comment/88222204
has comment: http://stackoverflow.com/comment/88221652
has comment: http://stackoverflow.com/comment/88223494
has comment: http://stackoverflow.com/comment/88222784
upvote count: 2
has comment: http://stackoverflow.com/comment/88223215

network-programming
tags question: http://stackoverflow.com/q/50606523
tags question: http://stackoverflow.com/q/50688439
tags question: http://stackoverflow.com/q/50605094
tags question: http://stackoverflow.com/q/50563465
type: Tag
tags question: http://stackoverflow.com/q/50588881
tag name: network-programming
tags question: http://stackoverflow.com/q/50675434
tags question: http://stackoverflow.com/q/50655080
tags question: http://stackoverflow.com/q/50660301
tags question: http://stackoverflow.com/q/50653590
tags question: http://stackoverflow.com/q/50559375
tags question: http://stackoverflow.com/q/50658016
tags question: http://stackoverflow.com/q/50695188

http://stackoverflow.com/comment/88167600
type: AnswerComment
score: 0
type: Comment
has text: I am sorry I was just copy/pasting. My output is still 111x11. The comments were commented, so I dont have any error, it just the output is not the same as yours. It seems in my case the mul is done rowwise not columnwise.
comment on: http://stackoverflow.com/a/50578649

pandas
tags question: http://stackoverflow.com/q/50638314
tags question: http://stackoverflow.com/q/50640070
tags question: http://stackoverflow.com/q/50591123
tags question: http://stackoverflow.com/q/50698349
tags question: http://stackoverflow.com/q/50611273
tags question: http://stackoverflow.com/q/50599387
tags question: http://stackoverflow.com/q/50659245
tags question: http://stackoverflow.com/q/50684104
tags question: http://stackoverflow.com/q/50691053
tags question: http://stackoverflow.com/q/50695778
tags question: http://stackoverflow.com/q/50679812
tags question: http://stackoverflow.com/q/50570813
tags question: http://stackoverflow.com/q/50617557
tags question: http://stackoverflow.com/q/50566870
tags question: http://stackoverflow.com/q/50673501
tags question: http://stackoverflow.com/q/50603725
tags question: http://stackoverflow.com/q/50572348
tags question: http://stackoverflow.com/q/50616978
tags question: http://stackoverflow.com/q/50625699
tags question: http://stackoverflow.com/q/50626358
tags question: http://stackoverflow.com/q/50667003
tags question: http://stackoverflow.com/q/50675844
tags question: http://stackoverflow.com/q/50628422
tags question: http://stackoverflow.com/q/50678599
tags question: http://stackoverflow.com/q/50672212
tags question: http://stackoverflow.com/q/50632960
tags question: http://stackoverflow.com/q/50681183
tags question: http://stackoverflow.com/q/50625893
tags question: http://stackoverflow.com/q/50642777
tags question: http://stackoverflow.com/q/50560993
tags question: http://stackoverflow.com/q/50688997
tags question: http://stackoverflow.com/q/50567381
tags question: http://stackoverflow.com/q/50640167
tags question: http://stackoverflow.com/q/50648212
tags question: http://stackoverflow.com/q/50544855
tags question: http://stackoverflow.com/q/50684663
tags question: http://stackoverflow.com/q/50616513
tags question: http://stackoverflow.com/q/50569465
tags question: http://stackoverflow.com/q/50614545
tags question: http://stackoverflow.com/q/50593341
tags question: http://stackoverflow.com/q/50659967
tags question: http://stackoverflow.com/q/50601979
tags question: http://stackoverflow.com/q/50558458
tags question: http://stackoverflow.com/q/50618565
tags question: http://stackoverflow.com/q/50624412
tags question: http://stackoverflow.com/q/50635073
tags question: http://stackoverflow.com/q/50600091
tags question: http://stackoverflow.com/q/50684255
tags question: http://stackoverflow.com/q/50657228
tags question: http://stackoverflow.com/q/50651193
tags question: http://stackoverflow.com/q/50652463
tags question: http://stackoverflow.com/q/50607759
tags question: http://stackoverflow.com/q/50623430
tags question: http://stackoverflow.com/q/50646878
tags question: http://stackoverflow.com/q/50543178
tags question: http://stackoverflow.com/q/50614310
tags question: http://stackoverflow.com/q/50690947
tags question: http://stackoverflow.com/q/50569171
tags question: http://stackoverflow.com/q/50570062
tags question: http://stackoverflow.com/q/50645445
tags question: http://stackoverflow.com/q/50638076
tags question: http://stackoverflow.com/q/50668357
tags question: http://stackoverflow.com/q/50679939
tags question: http://stackoverflow.com/q/50644011
tags question: http://stackoverflow.com/q/50554937
tags question: http://stackoverflow.com/q/50563362
tags question: http://stackoverflow.com/q/50602488
tags question: http://stackoverflow.com/q/50622990
tags question: http://stackoverflow.com/q/50586548
tags question: http://stackoverflow.com/q/50587922
tags question: http://stackoverflow.com/q/50621641
tags question: http://stackoverflow.com/q/50586248
tags question: http://stackoverflow.com/q/50620755
tags question: http://stackoverflow.com/q/50586862
tags question: http://stackoverflow.com/q/50545038
tags question: http://stackoverflow.com/q/50596383
tags question: http://stackoverflow.com/q/50685450
tags question: http://stackoverflow.com/q/50638073
tags question: http://stackoverflow.com/q/50652473
tags question: http://stackoverflow.com/q/50654661

http://stackoverflow.com/comment/88272232
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50631050
has text: I opened an older jupyter notebook created on this local machine. When I executed the cell to import pandas I got an error that read ImportError: cannot import name 'is_list_like'
score: 0

http://stackoverflow.com/q/50661642
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88333506
has answer: http://stackoverflow.com/a/50661742
tagged with: python
type: AnsweredQuestion
has title: Python3 beautifulsoup module 'NoneType' Error
has comment: http://stackoverflow.com/comment/88333426
score: 1
has answer: http://stackoverflow.com/a/50661702
accepted answer: http://stackoverflow.com/a/50661702
tagged with: web-scraping
tagged with: urllib
type: Question
has comment: http://stackoverflow.com/comment/88333445
possible better answer: http://stackoverflow.com/a/50661742
answer count: 2
upvote count: 1
downvote count: 0
has body: I'm new to beautifulsoup module and I have a problem. My code is simple. Before all, the site I'm trying to scrape from is this and I am trying to scrape the price. (The big number two (2) with more of it) My code: import urllib from bs4 import BeautifulSoup quote_page = 'https://www.bloomberg.com/quote/SPX:IND' page = urllib.request.urlopen(quote_page) soup = BeautifulSoup(page, 'html.parser') price_box = soup.find('div', attr = {'class': 'price'}) price = price_box.text print(price) The error I get: price = price_box.text AttributeError: 'NoneType' object has no attribute 'text'
favorite count: 0
tagged with: beautifulsoup

http://stackoverflow.com/q/50612883
has title: Going one element back BeautifulSoup
upvote count: 3
has comment: http://stackoverflow.com/comment/88235952
type: Question
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50613246
has comment: http://stackoverflow.com/comment/88235789
tagged with: beautifulsoup
has body: I am trying to check if an element has another element containing a specific attribute (Such as id=xxxxx). This is roughly the structure: > > >> > > I am able to find all yyyy. Is there a way I can traverse back and check if before the element with attribute id=yyyy there is an element with id=xxxx? If not, what is another solution I could adapt do do this?
tagged with: python
has comment: http://stackoverflow.com/comment/88236062
favorite count: 0
has comment: http://stackoverflow.com/comment/88235826
type: UnansweredQuestion
score: 3

http://stackoverflow.com/comment/88113484
type: AnswerComment
score: 0
type: Comment
has text: Hey @MRocklin True, it is same row as before but why it happened?
comment on: http://stackoverflow.com/a/50549189

http://stackoverflow.com/comment/88118397
comment on: http://stackoverflow.com/q/50548012
type: QuestionComment
has text: @figbeam try now
score: 0
type: Comment

http://stackoverflow.com/a/50597940
has comment: http://stackoverflow.com/comment/88205077
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50597807
has comment: http://stackoverflow.com/comment/88205326
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50597807
has comment: http://stackoverflow.com/comment/88205174
type: AcceptedAnswer
upvote count: 2
has body: It's common practice to render same template if form is not valid, to see error messages on the web page, so instead of return HttpResponse(profilePicForm.errors) you shoud do something like this: if profilePicForm.is_valid(): return HttpResponse(" Valid ") profilePic = ProfilePictures() query = UserInfo.objects.filter(id=id) for user in query: profilePic.user = user break profilePic.profile_pic = profilePicForm.cleaned_data['profile_pic'] profilePic.save() return redirect('newsfeed:profile') else: return render(request, 'template.html', {'profilePicForm': profilePicForm}) Also for file uploading you should add to the form enctype="multipart/form-data": {% csrf_token %} {{ profilePicForm.as_p }} Upload

http://stackoverflow.com/comment/88188510
type: QuestionComment
has text: You should call the `super()` to check the inherited validation, which will validate the `required=True`.
comment on: http://stackoverflow.com/q/50589589
score: 0
type: Comment

http://stackoverflow.com/q/50619818
upvote count: 1
type: UnansweredQuestion
tagged with: neural-network
answer count: 0
downvote count: 0
score: 1
favorite count: 0
has title: tuning neural network parameter
has body: I'm testing a Self Organizing Map neural network algorithm to perform a model regression. I performed a basic test in Python, with the somoclu toolbox (very efficient in computation time). I use a x² function as a test function. Then, I tried to create a SOM with 50x50 points. I have plotted a series of curves where you can see the original points vs SOM. The interpolation is not satisfaying for me because if I'm not learning enough, there are outliers, and if I'm learning too much, it is fitting with original points. What I would like is to have points between points of my square curve. I understand that in this case outliers are not "stupid" because they try to connect points. But it can't be used in state as a model regression. Can you explain to me where I'm wrong in my tuning parameters? Or how to remove outliers? my code: import numpy as np import matplotlib.pyplot as plt import somoclu import pandas as pd data = pd.read_csv('10_samples.txt', sep='\t', header = 0) data = data.as_matrix() epoch_size = np.linspace(2,100,99) for j in epoch_size: som = somoclu.Somoclu(n_columns=50, n_rows=50, data=data, kerneltype = 0, initialization = 'pca') som.train(epochs=int(j)) a=som.codebook dim=a.shape som_ncodebook = [[]] for i in range(dim[2]): param = a[:,:,i] param = param.reshape(1,dim[0]*dim[1]) # raboute ligne à ligne param = param.reshape(dim[0]*dim[1],1) # transforme en colonne if i == 0 : som_ncodebook = param else: som_ncodebook=np.append(som_ncodebook,param,axis=1) codebookplot = som_ncodebook plt.plot(codebookplot[:,0],codebookplot[:,1],'ob') plt.plot(data[:,0],data[:,1],'.r') plt.title('codebook epoch = '+str(j)) plt.savefig('test_'+str(int(j))+'.png') plt.close()
type: Question
tagged with: python
tagged with: regression

http://stackoverflow.com/comment/88266743
comment on: http://stackoverflow.com/q/50619294
type: Comment
type: QuestionComment
has text: That is failing because you need to supply the `path_lower`, not `name` when calling `files_list_folder`, etc.
score: 0

http://stackoverflow.com/a/50628572
type: Answer
has comment: http://stackoverflow.com/comment/88267150
upvote count: 3
answers question: http://stackoverflow.com/q/50628266
has body: quick fix might be to remove NaN. Try messages.dropna()
score: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50628266

http://stackoverflow.com/q/50660972
has title: Having problems with if and else in list comprehensions. I need to make the list value something if the list is empty
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/50661068
type: Question
has comment: http://stackoverflow.com/comment/88332044
has body: I have this: name_list = [x for x in list] if not name_list: name_list = "n/a" I want to make it in one line. I want this: name_list = ["n/a" if not x else x.text for x in list] The problem I'm having if that I don't know what to put in the first x of the above code. How do I check if the list is empty and make the value "n/a" in one line?
has answer: http://stackoverflow.com/a/50660995
has comment: http://stackoverflow.com/comment/88331980
answer count: 3
has comment: http://stackoverflow.com/comment/88332072
favorite count: 0
has answer: http://stackoverflow.com/a/50661068
possible better answer: http://stackoverflow.com/a/50660997
has comment: http://stackoverflow.com/comment/88332005
upvote count: 2
has answer: http://stackoverflow.com/a/50660997
tagged with: python
downvote count: 1

http://stackoverflow.com/comment/88315547
has text: Your dataset function looks correct, although I would recommend adding `.repeat` as the images in CIFAR-10 are a lot more diverse than MNIST.
comment on: http://stackoverflow.com/q/50562538
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50702671
has body: If you wish to keep the same deployment endpoint url and credentials when you replace a model, I believe you will need to use the REST API directly (docs): Update This is now available in the python library:
has comment: http://stackoverflow.com/comment/88509421
answers question: http://stackoverflow.com/q/50695427
type: Answer
has comment: http://stackoverflow.com/comment/88665361
has comment: http://stackoverflow.com/comment/88517126
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50695427

http://stackoverflow.com/comment/88381639
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50675708
has text: Sure, I’m just offering a work around, However, if you hit a similar problem when using invoke_endpoint, you might have an issue with the code.

http://stackoverflow.com/q/50681184
favorite count: 0
has body: Trying to find search word in a bunch of text document in a folder using that approach: dirname = '/Users/user/Documents/dat/' search_terms = ['kek'] for f in os.listdir(dirname): text = open(os.path.join(dirname,f)).readlines() if any(term in text for term in search_terms): print (f) For some reason, don't know why, it gives me the name of first file in directory no matter consists it this search term or not. What should be done differently to proper do this task? Thanks!
tagged with: python
tagged with: parsing
tagged with: text
has title: Searching for the files which have search terms in python
upvote count: 1
has answer: http://stackoverflow.com/a/50681292
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88371812
possible better answer: http://stackoverflow.com/a/50681332
type: Question
tagged with: search
has answer: http://stackoverflow.com/a/50681332
answer count: 2
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/50681292
has comment: http://stackoverflow.com/comment/88371835

http://stackoverflow.com/comment/88383310
type: QuestionComment
comment on: http://stackoverflow.com/q/50686655
score: 1
has text: `len(w) => 3` is invalid syntax
type: Comment

http://stackoverflow.com/comment/88145349
score: 0
type: Comment
type: QuestionComment
has text: Maybe different levels of debug symbols? Try copying each `.so` to a separate location and run `strip` on them. Do the sizes match then?
comment on: http://stackoverflow.com/q/50565322

http://stackoverflow.com/q/50678117
possible better answer: http://stackoverflow.com/a/50678301
tagged with: python
type: AnsweredQuestion
type: Question
has title: Create df from list (fill up to nth number value into one columns then continue..) in pandas
has answer: http://stackoverflow.com/a/50678301
has body: Would like to create the the df from a list that first 5 value should be in column a, then the next 5 value in another column etc, anyone have any idea? Below is the code. Thank you. print (test_1) ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', 1279', '1228', '1299', '1162', '1285', '1079', '1197', '1250', '1249', '1385', '1216', '1201', '1320', '1228', '1241', '1232', '1200', '1213', '1224', '1070','1224', '1070'...] df = pd.DataFrame(np.array(test_1).reshape(22,5), columns = list("abcde")) print (df) a b c d e 0 01 02 03 04 05 0 06 07 08 09 10 1 1279 1228 1299 1162 1285 3 1079 1197 1250 1249 1385 Desired output: print (df) a b c d e 0 01 1279 ... ... ... 1 02 1228 ... ... ... 2 03 1299 ... ... ... 3 04 1162 ... ... ... 4 05 1285 ... ... ... 5 06 1079 ... ... ... 6 07 1197 ... ... ... 7 08 1250 ... ... ... 8 09 1249 ... ... ... 9 10 1385 ... ... ...
score: 0
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/88391086
has answer: http://stackoverflow.com/a/50678383
has comment: http://stackoverflow.com/comment/88366135
has answer: http://stackoverflow.com/a/50678289
accepted answer: http://stackoverflow.com/a/50678289

http://stackoverflow.com/q/50573765
tagged with: split
has answer: http://stackoverflow.com/a/50573865
answer count: 2
downvote count: 4
upvote count: 0
score: -4
possible better answer: http://stackoverflow.com/a/50573865
has comment: http://stackoverflow.com/comment/88157099
linked to: http://stackoverflow.com/q/35613990
accepted answer: http://stackoverflow.com/a/50573894
favorite count: 0
has comment: http://stackoverflow.com/comment/88157150
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88157165
tagged with: python
has body: my code: readfile = open("{}".format(file), "r") lines = readfile.read().lower().split() elements = """,.:;|!@#$%^&amp;*"\()`_+=[]{}&lt;&gt;?/~""" for char in elements: lines = lines.replace(char, '') this works and removes the special characters. but I need help with striping "-" and " ' " so for example " saftey-dance " would be okay but not " -hi- " but " i'll " is okay but not " 'hi " i need to strip only the beginning and ending its not a string it is a list. how do I do this?
type: AnsweredQuestion
tagged with: strip
linked to: http://stackoverflow.com/q/1276764
has title: strip and split how to strip the list
type: Question
has answer: http://stackoverflow.com/a/50573894

http://stackoverflow.com/a/50569248
answers question: http://stackoverflow.com/q/50559000
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50559000
has body: You can try using matplotlib. You can read image to numpy array by using mpimg.imread (documentation) from matplotlib, then you can use subplots (documentation) and for creating two columns for figures and finally imshow (documetation) to display images. import matplotlib.pyplot as plt import matplotlib.image as mpimg from matplotlib import rcParams %matplotlib inline # figure size in inches optional rcParams['figure.figsize'] = 11 ,8 # read images img_A = mpimg.imread('\path\to\img_A.png') img_B = mpimg.imread('\path\to\img_B.png') # display images fig, ax = plt.subplots(1,2) ax[0].imshow(img_A) ax[1].imshow(img_B)
has comment: http://stackoverflow.com/comment/98570575
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/126285463
has comment: http://stackoverflow.com/comment/116459170
score: 24
upvote count: 25

http://stackoverflow.com/comment/88398642
comment on: http://stackoverflow.com/a/50650550
has text: Thanks! I'll look into it!
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/50564217
type: Answer
has comment: http://stackoverflow.com/comment/88147631
answers question: http://stackoverflow.com/q/50559105
has body: Video files will often, or even generally, be too big to fit in your main memory so you will be unlikely to be able to just keep the entire video there. It also worth noting that your OS itself may decide to move data between fast memory, slower memory, disk etc as it manages multiple processes but that is likely not important in this discussion. It will depend on your use case but a typical video scenario might be: receive video frame from camera or source stream do some processing on the video frame - e.g. transcode it, detect an object, add text or images etc store or send the updated frame someplace go back to first step In a flow like this, there is obviously advantage in keeping the frame in memory while working on it, but once done then it is generally not an advantage any more so its fine to move it to disk, or send it to its destination. If you use cases requires you to work on groups of frames, as some encoding algorithms do, then it may make sense to keep the group of frames in memory until you are finished with them and then write them to disk. I think the best answer for you will depend on your exact use case, but whatever that it is it is unlikely that keeping the entire video in memory would be necessary or even possible.
downvote count: 0
has comment: http://stackoverflow.com/comment/88150126
score: 1
has comment: http://stackoverflow.com/comment/88170579
has comment: http://stackoverflow.com/comment/88153913
upvote count: 1

http://stackoverflow.com/comment/88149455
type: Comment
has text: @Aran-Fey: [Different questions may be closed as dupes if understanding the answer to one answers the other](https://meta.stackexchange.com/questions/217401/does-the-new-guidance-on-duplicate-questions-suggest-closing-a-question-as-dupli).
comment on: http://stackoverflow.com/q/50569419
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88337927
type: Comment
type: QuestionComment
has text: Just use `^` and `$` anchors as shown [HERE](https://regex101.com/r/UJ3SzB/1)
score: 0
comment on: http://stackoverflow.com/q/50663898

trace
tag name: trace
tags question: http://stackoverflow.com/q/50598438
type: Tag
tags question: http://stackoverflow.com/q/50558849

python-multiprocessing
tags question: http://stackoverflow.com/q/50572875
tags question: http://stackoverflow.com/q/50607956
tags question: http://stackoverflow.com/q/50633961
tags question: http://stackoverflow.com/q/50547948
tags question: http://stackoverflow.com/q/50617292
tags question: http://stackoverflow.com/q/50593550
type: Tag
tags question: http://stackoverflow.com/q/50602137
tags question: http://stackoverflow.com/q/50571191
tags question: http://stackoverflow.com/q/50675504
tag name: python-multiprocessing
tags question: http://stackoverflow.com/q/50620422
tags question: http://stackoverflow.com/q/50660633

http://stackoverflow.com/q/50668588
score: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/88347060
has title: pymysql-ProgrammingError(1064, "You have an error in your SQL syntax;
upvote count: 1
type: Question
tagged with: pymysql
has body: I am running this on pymysql and it appears to have a syntax problem although on workbench if i repace %s with a random value it works fine.What am I doing wrong?Also the full error row is this ProgrammingError(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '3226'') \n GROUP BY a2.actor_id=''3226'',a1.actor_id \n HAVING count(DISTINC' at line 9") sql_query='''SELECT a1.actor_id as i8opoios1 FROM actor as a1 INNER JOIN actor as a2 on a1.actor_id != a2.actor_id INNER JOIN role as r1 on a1.actor_id = r1.actor_id INNER JOIN movie as m1 on m1.movie_id = r1.movie_id INNER JOIN movie_has_genre as mg1 on mg1.movie_id = m1.movie_id INNER JOIN role as r2 on a2.actor_id = r2.actor_id INNER JOIN movie as m2 on m2.movie_id = r2.movie_id INNER JOIN movie_has_genre as mg2 on mg2.movie_id = m2.movie_id WHERE (a2.actor_id='%s') GROUP BY a2.actor_id='%s',a1.actor_id HAVING count(DISTINCT mg1.genre_id) + count(DISTINCT mg2.genre_id)&gt;=7 AND SUM(mg1.genre_id = mg2.genre_id) = 0''' cur.execute(sql_query,(actorId,actorId)) results=cur.fetchall()
downvote count: 0

http://stackoverflow.com/a/50585235
has comment: http://stackoverflow.com/comment/88180421
answers question: http://stackoverflow.com/q/50583219
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88180364
has body: Looks like your DB is already migrated till the migration 0002. Run python manage.py migrate --fake sites 0002 - see if this fixes the problem.
has comment: http://stackoverflow.com/comment/88180060
has comment: http://stackoverflow.com/comment/88180267
has comment: http://stackoverflow.com/comment/88179823
type: Answer
has comment: http://stackoverflow.com/comment/88180028
score: 5
upvote count: 5
accepted answer of: http://stackoverflow.com/q/50583219

firefox
tags question: http://stackoverflow.com/q/50563408
tag name: firefox
type: Tag
tags question: http://stackoverflow.com/q/50679623
tags question: http://stackoverflow.com/q/50662674

class
tags question: http://stackoverflow.com/q/50599045
tags question: http://stackoverflow.com/q/50622587
tags question: http://stackoverflow.com/q/50622609
tags question: http://stackoverflow.com/q/50595897
tags question: http://stackoverflow.com/q/50587901
tags question: http://stackoverflow.com/q/50682674
tags question: http://stackoverflow.com/q/50662737
tags question: http://stackoverflow.com/q/50633643
tags question: http://stackoverflow.com/q/50600750
tags question: http://stackoverflow.com/q/50546057
tags question: http://stackoverflow.com/q/50666335
tags question: http://stackoverflow.com/q/50612475
tags question: http://stackoverflow.com/q/50550905
tags question: http://stackoverflow.com/q/50553486
tags question: http://stackoverflow.com/q/50656874
tags question: http://stackoverflow.com/q/50610516
tags question: http://stackoverflow.com/q/50645781
type: Tag
tags question: http://stackoverflow.com/q/50652332
tags question: http://stackoverflow.com/q/50667244
tag name: class
tags question: http://stackoverflow.com/q/50650133
tags question: http://stackoverflow.com/q/50675248
tags question: http://stackoverflow.com/q/50688881
tags question: http://stackoverflow.com/q/50650459
tags question: http://stackoverflow.com/q/50643212
tags question: http://stackoverflow.com/q/50547298
tags question: http://stackoverflow.com/q/50548341
tags question: http://stackoverflow.com/q/50682427
tags question: http://stackoverflow.com/q/50661734
tags question: http://stackoverflow.com/q/50541979
tags question: http://stackoverflow.com/q/50639137
tags question: http://stackoverflow.com/q/50664568
tags question: http://stackoverflow.com/q/50555252
tags question: http://stackoverflow.com/q/50656058
tags question: http://stackoverflow.com/q/50548843
tags question: http://stackoverflow.com/q/50616162
tags question: http://stackoverflow.com/q/50542331
tags question: http://stackoverflow.com/q/50657695

http://stackoverflow.com/a/50623772
answers question: http://stackoverflow.com/q/50623552
type: Answer
upvote count: 1
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50623552
score: 1
has body: A quick solution by hand. If you care about performance you should probably stick with itertools. def all_combs(xs): res = [] buf = [[]] lst = [[x] for x in xs] for _ in xs: buf = [r + l for r in buf for l in lst] res.extend(buf) return res

http://stackoverflow.com/comment/88223092
score: 0
type: Comment
has text: That's weird if you don't get the same plots, how different are they ? And about the "smoothness", it refers to the differentiability of your function. In your case, your function does not look like differentiable when we plot the differential.That's why I suggest you to interpolate you function with a real parabola.
type: AnswerComment
comment on: http://stackoverflow.com/a/50606124

http://stackoverflow.com/q/50631670
linked to: http://stackoverflow.com/q/49620538
has comment: http://stackoverflow.com/comment/88273369
has title: How to combine two dataframes vertically with only some columns in common using Pandas?
type: UnansweredQuestion
tagged with: python
tagged with: merge
answer count: 0
score: 0
duplicate of: http://stackoverflow.com/q/49620538
type: Question
has comment: http://stackoverflow.com/comment/88273417
tagged with: dataframe
has body: Let's say I have two data frame and I want to combine them (more like concatenating than merging since I am not joining on any columns). Here is a made-up example: Here is table 1: player_name points rebounds assists player1 27.0 9.0 9.0 player2 31.0 4.0 5.0 player3 15.0 10.0 1.0 Here is table 2: player_name points height weight player4 17.0 6'0" 200 player5 21.0 6'2" 230 player6 26.0 6'5" 270 Here is the resulting table: player_name points rebounds assists height weight player1 27.0 9.0 9.0 Null Null player2 31.0 4.0 5.0 Null Null player3 15.0 10.0 1.0 Null Null player4 17.0 Null Null 6'0" 200 player5 21.0 Null Null 6'2" 230 player6 26.0 Null Null 6'5" 270 Basically, both tables do not have the same columns, and that is okay. I want to retain all the columns from each of the tables (combining the ones in common, such as points in this case), and fill in Null values for the ones not in common. How can I do this simply in Python/Pandas? This is slightly different than a simple df join or concatenate, from my understanding.
has comment: http://stackoverflow.com/comment/88273458
tagged with: concatenation
tagged with: pandas

http://stackoverflow.com/a/50662846
answers question: http://stackoverflow.com/q/50662571
has body: You can use a process pool to create a dynamic number of processes, and represent your tasks as properly separated jobs to distribute work: from multiprocessing import Pool # each entry of `job_list` contains all the information # required to perform a single task. job_list = [ { "account": { "username": "john", "password": "qwerty" }, "query": "How can I help you?" } # , ... ] # function executed for each element of `job_list` def run_job(job): print("account user name: {}".format(job["account"]["username"])) print("query: {}".format(job["query"])) # answer query here using account with Pool(processes=4) as pool: pool.map(run_job, job_list)
type: Answer
score: 2
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50662571
type: AcceptedAnswer

http://stackoverflow.com/comment/88165806
type: Comment
has text: Glad [my answer](https://stackoverflow.com/a/50562186/3832970) worked for you. Please also consider upvoting if my answer proved helpful to you (see [How to upvote on Stack Overflow?](http://meta.stackexchange.com/questions/173399/how-to-upvote-on-stack-overflow)).
comment on: http://stackoverflow.com/q/50559609
score: 0
type: QuestionComment

http://stackoverflow.com/a/50622079
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50621680
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50621680
type: AcceptedAnswer
type: Answer
has body: That is because making slice by padded_train_x[0:1] you get 2d array: a = np.linspace(1024).reshape(64,-1) b = a[0] c = a[0:1] b array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) b[0] 0 c array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]]) c[0] array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])

http://stackoverflow.com/q/50595980
type: UnansweredQuestion
type: Question
score: 1
linked to: http://stackoverflow.com/q/36001966
has comment: http://stackoverflow.com/comment/88201424
upvote count: 1
has body: I'm trying to upgrade the version of python on my Mac using homebrew. I do brew install python3 and I see that it installs python 3.6.5. However, when I do python3 --version I get -bash: /Library/Frameworks/Python.framework/Versions/3.4/bin/python3: No such file or directory. Not sure how I'm suppose to resolve this. Someone posted something similar (Unable to Run Python 3 After Homebrew Installation) but the solution is to download another version of python from the website, but I don't think this solves the fundamental issue of this lingering version. Any idea how I can resolve this?
has comment: http://stackoverflow.com/comment/88201198
favorite count: 0
linked to: http://stackoverflow.com/q/45649473
tagged with: python
tagged with: macos
has title: Old version of python 3.4 not allowing python 3.6.5 to work
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88201494
tagged with: installation
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/88201565
tagged with: homebrew

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

http://stackoverflow.com/comment/88253643
score: 0
has text: You should include the assignment of the string, to show what the actual string is. And the value you expect.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50621340

http://stackoverflow.com/comment/88309142
has text: @Aran-Fey: imagine an event handler system, and the OP wants to register those methods in a class as event callbacks.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50649020
score: 1

http://stackoverflow.com/comment/88269289
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50557094
has text: Don't get discouraged that your first question was downvoted. Learning to ask clear questions that provide enough without too much info is a skill you'll develop. To help improve this question, you should mention and tag sklearn. I submitted an edit it but I think it was lost in an edit you made. If my answer helped you past this issue (ignoring other issues that you may have also hit) please select and upvote it.
score: 0

http://stackoverflow.com/comment/88146908
score: 0
has text: My software is up to date and I tried running the program with the firewall down and it didn't seem to fix the issue
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50568060

http://stackoverflow.com/a/50609751
has comment: http://stackoverflow.com/comment/88247406
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88231925
has body: All you need is a row comparison. Then based on the match it appends to a different file. Also The try/except checks if the file exists, if not writes the header. This is the simplest way to achieve the results you are looking for. You could also do a comparison if the file does exist to ensure the header is formatted in the manner of your choosing, but this answer already goes way beyond the scope of the original question. import csv csv_file = 'file/path/file_name' values = ['preschool', 'secondary school'] def csv_header(x): with open(x + '.csv', 'ab') as myfile: myfile.write("%s %s %s %s \n" % ('id', 'type', 'state', 'location')) myfile.close() def csv_writer(y, value): for row in y: if value in row: with open(value + '.csv', 'ab') as myfile: spamwriter = csv.writer(myfile) spamwriter.writerow(row) myfile.close() def csv_reader(z): with open(z + '.csv', 'rb') as spam: spamreader = csv.reader(spam, delimiter=',', quotechar='|') csv_writer(spamreader, value) for value in values: try: csv_reader(value) csv_reader(csv_file) except: csv_header(value) csv_reader(csv_file) https://docs.python.org/2/library/csv.html
has comment: http://stackoverflow.com/comment/88247591
has comment: http://stackoverflow.com/comment/88300468
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50609656
has comment: http://stackoverflow.com/comment/88302361
has comment: http://stackoverflow.com/comment/88232873
has comment: http://stackoverflow.com/comment/88232392
accepted answer of: http://stackoverflow.com/q/50609656
has comment: http://stackoverflow.com/comment/88342978
has comment: http://stackoverflow.com/comment/88379362
has comment: http://stackoverflow.com/comment/88232934
has comment: http://stackoverflow.com/comment/88302496

http://stackoverflow.com/comment/88164576
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50577520
has text: Use [something like this](https://pypi.org/project/ics/) probably.
type: Comment

http://stackoverflow.com/comment/88189434
type: Comment
type: QuestionComment
has text: I din't know about it
comment on: http://stackoverflow.com/q/50589333
score: 0

http://stackoverflow.com/q/50580480
tagged with: anaconda
has body: so i installed anaconda graphical installer but when i searched for anaconda-navigator on my anaconda prompt it did not open instead it showed this message 'C:\Users\RAM\Anaconda3\Scripts\activate.bat' is not recognized as an internal or external command, operable program or batch file. I do not know what does this mean please help me fix this problem
type: Question
has title: anaconda navigator not opening with error active.bat
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50715827
accepted answer: http://stackoverflow.com/a/50715827
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/50564888
type: Answer
answers question: http://stackoverflow.com/q/50564591
score: 0
has body: As everyone already mentionned, you can't do this out of the box. Now if you need both ways to get the value(s) - one from the full key and another from a "partial" key, a solution might be to maintain a key[0]=&gt;[keys...] mapping in parallel, ie: L = {(10, 1): 5, (10, 0): 6, (20, 0): 7} index = defaultdict(list) for key in L: index[key[0]].append(key) Then you can get the list of "complete" keys for a partial one keys = index.get(10) values = [L[k] for k in keys] Of course this means you have to make sure you keep your index up to date so you would need to wrap this all in a class to make sure all updates to L are reflected in index.

http://stackoverflow.com/comment/88322735
has text: @BcK sorry if it seems indecent, thanks for the advice. I will follow your advice from now :)
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50644275

http://stackoverflow.com/comment/88168058
type: QuestionComment
has text: what did you try? you could play with bar plots carefully setting the `bottom` parameter to properly stack them
score: 0
comment on: http://stackoverflow.com/q/50575659
type: Comment

http://stackoverflow.com/comment/88212552
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50601461
has text: There I assume you'd be delegating the `main` function to be run by each worker (which you haven't provided in your code). The above just assumes a list of lines derived from your content, and a function `worker_function` that you define that operates on a single row of content and does whatever you need it to (you could adapt the body of your `main` function to go here). What are your original jobs doing?
score: 0

http://stackoverflow.com/q/50547614
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88106688
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50547693
downvote count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/88105966
has title: Pandas : How to replace values in a range with a string?
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50547693
possible better answer: http://stackoverflow.com/a/50547648
has answer: http://stackoverflow.com/a/50547648
tagged with: python
has body: I'm trying to replace values in a certain range with some other value. I have a dictionary containing a char as key and the upper range as a value like the following - replace_dict = { 'A': 10, 'B': 21, 'C': 34, 'D': 49, 'E': 66, 'F': 85, 'G': 107, 'H': 132, 'I': 160, 'J': 192, 'K': 229, 'L': 271, 'M': 319, 'N': 395, 'O': 495, 'P': 595, 'Q': 795, 'R': 1100 } I need to replace the values with the corresponding keys that fall in a range. For example: Values in the range of 1-10 will be replaced by 'A', Values in the range of 11-21 will be replaced by 'B' Values in the range of 22-34 will be replaced by 'C' Values in the range of 35-50 will be replaced by 'D' Values in the range of 51-66 will be replaced by 'E' I've written the following code: k=1 for i, j in replace_dict.items(): data.loc[data['my_col'].between(k,j)] = i k=j+1 This code shows TypeError: '&gt;=' not supported between instances of 'str' and 'int'. However, the line data.loc[data['my_col'].between(1,10)] = 'A' works fine. What is a good solution for this problem?

http://stackoverflow.com/comment/88357038
type: QuestionComment
comment on: http://stackoverflow.com/q/50673381
has text: Shouldn't it be just `file_input.send_keys("C:\\installAgent.log")` instead of `driver.file_input.send_keys("C:\\installAgent.log")`?
type: Comment
score: 1

http://stackoverflow.com/comment/88231688
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50610170
has text: **The cmd shows this error:** Traceback (most recent call last): File "test.py", line 60, in <module> while len(driver.find_element_by_class_name('movies-list--large-item')): TypeError: object of type 'WebElement' has no len()

http://stackoverflow.com/comment/126005560
comment on: http://stackoverflow.com/q/50664196
has text: @Amogh is it working as I wanted to use it
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88349934
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50669877
score: 0
has text: I'm trying to do this but the problem is that I have utc_time for the ID and it doesn't work

http://stackoverflow.com/comment/88296375
type: Comment
type: QuestionComment
has text: What is your expected output?
comment on: http://stackoverflow.com/q/50643141
score: 0

http://stackoverflow.com/a/50606109
downvote count: 0
type: Answer
score: 7
upvote count: 7
has body: By using pd.cut pd.cut(df.stack(),[-1,1,10,50,np.inf],labels=list('NLMH')).unstack() Out[309]: A B C A N L M B N H L C L M N
answers question: http://stackoverflow.com/q/50605498

http://stackoverflow.com/comment/88209506
has text: See [Testing for an empty iterator ActiveState's recipe](https://github.com/ActiveState/code/tree/master/recipes/Python/413614_Testing_for_an_empty_iterator)
comment on: http://stackoverflow.com/q/50599850
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88222355
score: 0
type: Comment
type: QuestionComment
has text: When `if type(e)=type([]):` is true, you *never check if the result is higher*.
comment on: http://stackoverflow.com/q/50606302

http://stackoverflow.com/comment/88192975
type: QuestionComment
comment on: http://stackoverflow.com/q/50591822
has text: ... crashes .... With what message? Stacktrace?
score: 0
type: Comment

http://stackoverflow.com/q/50693072
answer count: 1
tagged with: xlsxwriter
has comment: http://stackoverflow.com/comment/88395668
has answer: http://stackoverflow.com/a/50694216
downvote count: 4
score: -3
has title: Can't write an xslx file, it says there is an attributeerror
has body: [Hi, I wrote some codes like below, but I have a problem with final part. I already installed xlsxwrtier several times with "pip install xlsxwriter", so I have the recent version. But still I'm struggling with "Workbook" thing. How can I fix this? Could any give me an advice please?] import xlrd import xlsxwriter def writeToExcel(wantToSave,name): numberOfRows = len(wantToSave) workbook = xlsxwriter.WorkBook(name +' .xlsx') worksheet = workbook.add_worksheet() for i in range(numberOfRows): worksheet.write(i,0, str(wantToSave[i])) workbook.close() def excelReader(datafile, sheet_num): workbook = xlrd.open_workbook(datafile) sheet = workbook.sheet_by_index(sheet_num) data = [[sheet.cell_value(r,col) for col in range(sheet.ncols)] for r in range(sheet.nrows)] return data data = excelReader("list1.xlsx", 0) data.remove(data[0]) data sentences = [] for i in range(len(data)): context_item = '[["' list_num = 'list '+str(int(data[i][0])) Item_No = str(int(data[i][1])) context_item += list_num+'", '+Item_No+'],'+' "DashedSentence", {s:["' sentence = data[i][5] if sentence[-1] == " ": sentence = sentence[:-1] context_item += sentence+'"]},' target_item = ' "DashedSentence", {s:["' sentence = data[i][6] if sentence[-1] == " ": sentence = sentence[:-1] target_item += sentence+'"]}, '+'"Question", {q:"' sentence = data[i][7] if sentence[-1] == " ": sentence = sentence[:-1] target_item += sentence+'"}],' sentences.append(context_item+target_item) writeToExcel(sentences, 'ibex_list1') AttributeError Traceback (most recent call last) &lt;ipython-input-15-3fda3a6a33ea&gt; in &lt;module&gt;() ----&gt; 1 writeToExcel(sentences, 'ibex_list1') &lt;ipython-input-7-0d092c570855&gt; in writeToExcel(wantToSave, name) 1 def writeToExcel(wantToSave,name): 2 numberOfRows = len(wantToSave) ----&gt; 3 workbook = xlsxwriter.WorkBook(name +' .xlsx') 4 worksheet = workbook.add_worksheet() 5 for i in range(numberOfRows): AttributeError: module 'xlsxwriter' has no attribute 'WorkBook'
tagged with: http://stackoverflow.com/tag/xlsx
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50694216
favorite count: 0
type: Question
upvote count: 1
tagged with: python

http://stackoverflow.com/q/50543209
has comment: http://stackoverflow.com/comment/88098662
has answer: http://stackoverflow.com/a/50543293
has title: Even when place is occupied, code passes through and runs the next line.. Tic Tac Toe
accepted answer: http://stackoverflow.com/a/50543293
score: -1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88098237
upvote count: 2
tagged with: python
has body: I used my logic for this game. However I feel the code is very lengthy, can anyone help me shorten the code and help me understanding how? should I create function? Also, when the place is occupied, it should show the message "Place is already taken" which is happening only first time, second time when I enter the same number, it passes through. code is below: board = [" " for i in range(9)] def print_board(): row1="|{}|{}|{}|".format(board[0],board[1],board[2]) row2="|{}|{}|{}|".format(board[3],board[4],board[5]) row3="|{}|{}|{}|".format(board[6],board[7],board[8]) print() print(row1) print(row2) print(row3) print() while True: print_board() choice=int(input("enter your choice, player 1").strip()) if board[choice-1]==" ": board[choice-1]= "X" print_board() else: print("space is taken, try again") choice=int(input("enter your choice, player 1").strip()) if board[choice-1]==" ": board[choice-1]= "X" print_board() choice=int(input("enter your choice, player 2").strip()) if board[choice-1]==" ": board[choice-1]= "0" else: print("space is taken") choice=int(input("enter your choice, player 2").strip()) if board[choice-1]==" ": board[choice-1]= "X" print_board()
type: AnsweredQuestion
downvote count: 3
type: Question

http://stackoverflow.com/comment/88208751
type: QuestionComment
has text: Observation: `while counter < deg:`: at the end of it `kkk` will only have one element: `deg`. I highly doubt that's intended (you should place `kkk = []` before the loop). Also: assuming that its purpose is only to generate that list: it could be replaced by: `kkk = list(range(1, deg + 1))` (as your code is now the list should start with 1 and end with `deg`).
comment on: http://stackoverflow.com/q/50599655
score: 0
type: Comment

http://stackoverflow.com/comment/88353752
type: AnswerComment
has text: Yeah, the python parquet drivers don't have the ability to read only a few rows of a partition (fastparquet could in principle, but I'd be the one to do it, and I have no such plans; pyarrow perhaps could be persuaded with minor changes, I'm not sure)
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50660317

http://stackoverflow.com/comment/88435378
comment on: http://stackoverflow.com/q/50581356
score: 0
type: Comment
type: QuestionComment
has text: I have solved that thanks

http://stackoverflow.com/a/50620516
upvote count: 9
accepted answer of: http://stackoverflow.com/q/50620166
score: 9
answers question: http://stackoverflow.com/q/50620166
has body: Suppose I have a python file test.py with the contents print "hello" To schedule it to run every 30 minutes, use crontab -e Then edit to add */30 * * * * python /path-to-file/test.py To check if cron ran succesfully grep CRON /var/log/syslog Here, you will see in logs, lines like May 31 14:25:01 shivam-PC CRON[17805]: (shivam) CMD (python /home/shivam/test.py) Note: print statement might not show in logs, so use */30 * * * * python /path-to-file/test.py &gt;&gt; /path-to-file/out.txt and then check out.txt for print logs. An alternate solution would be to use Celery.
has comment: http://stackoverflow.com/comment/88292466
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/114860761
type: Answer

http://stackoverflow.com/comment/88391772
score: 1
comment on: http://stackoverflow.com/q/50690966
has text: What have you tried? What didn't work? Please post your code.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50684013
has body: I am trying to combine a few relatively simple conditions into an np.where clause, but am having trouble getting the syntax down for the logic. My current dataframe looks like the df below, with four columns. I would like to add two columns, named the below, with the following conditions: The desired output is below - the df df_so_v2 Days since activity *Find most recent prior row with same ID, then subtract dates column *If no most recent value, return NA Chg. Avg. Value Condition 1: If Count = 0, NA Condition 2: If Count !=0, find most recent prior row with BOTH the same ID and Count!=0, then find the difference in Avg. Value column. However, I am building off simple np.where queries like the below and do not know how to combine the multiple conditions needed in this case. df['CASH'] = np.where(df['CASH'] != 0, df['CASH'] + commission , df['CASH']) Thank you very much for your help on this. df_dict={'DateOf': ['2017-08-07','2017-08-07','2017-08-07','2017-08-04','2017-08-04','2017-08-04' , '2017-08-03','2017-08-03','2017-08-03','2017-08-02','2017-08-02','2017-08-02','2017-08-01','2017-08-01','2017-08-01'], 'ID': ['553','559','914','553','559','914','553','559','914','553','559','914','553','559','914'], 'Count': [0, 4, 5, 0, 11, 10, 3, 9, 0,1,0,2,4,4,0], 'Avg. Value': [0,3.5,2.2,0,4.2,3.3,5.3,5,0,3,0,2,4.4,6.4,0]} df_so=pd.DataFrame(df_dict) df_dict_v2={'DateOf': ['2017-08-07','2017-08-07','2017-08-07','2017-08-04','2017-08-04','2017-08-04' , '2017-08-03','2017-08-03','2017-08-03','2017-08-02','2017-08-02','2017-08-02','2017-08-01','2017-08-01','2017-08-01'], 'ID': ['553','559','914','553','559','914','553','559','914','553','559','914','553','559','914'], 'Count': [0, 4, 5, 0, 11, 10, 3, 9, 0,1,0,2,4,4,0], 'Avg. Value': [0,3.5,2.2,0,4.2,3.3,5.3,5,0,3,0,2,4.4,6.4,0], 'Days_since_activity': [4,3,1,1,1,2,1,2,1,1,1,1,'NA','NA','NA'], 'Chg. Avg Value': ['NA',-0.7,-1.1,'NA',-0.8,1.3,2.3,-1.4,'NA',-1.4,'NA','NA','NA','NA','NA'] } df_so_v2=pd.DataFrame(df_dict_v2)
tagged with: python
has title: Pandas DF Multiple Conditionals using np.where
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88377781
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88377842
score: 0
has comment: http://stackoverflow.com/comment/88377748
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/88378283
has comment: http://stackoverflow.com/comment/88379889
has comment: http://stackoverflow.com/comment/88378908
has answer: http://stackoverflow.com/a/50685367
type: UnansweredQuestion

http://stackoverflow.com/q/50594442
has answer: http://stackoverflow.com/a/57533923
favorite count: 0
answer count: 5
possible better answer: http://stackoverflow.com/a/50594469
tagged with: python
has answer: http://stackoverflow.com/a/50594469
has body: I have a python script to send emails. I utilize this to send alerts to my email and phone. But for some reason the emails are not received when sending to a gmail account. The big difference that I see between my code and other examples is I cannot use the smtp.gmail.com. Here's my email/text function: import smtplib sender = 'xxxx@company.com' smtpObj = smtplib.SMTP('smtp.company.com') def text_func ( subject,text_message ): text_receivers = ['##########@vtext.com', 'xxxxxxxx@company.com', 'xxxxxxxx@gmail.com' ] text_message = """Subject: %s %s """ % (subject, text_message) smtpObj.sendmail(sender, text_receivers, text_message) The above code works for sending an sms to my phone and my work email but not to gmail. I checked and made sure the email doesn't show up in a spam folder. Google seems to be blocking it completely. Any ideas?
tagged with: gmail
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50614506
has title: Python Can't Send Emails to Gmail
has answer: http://stackoverflow.com/a/50629843
type: Question
tagged with: smtplib
has answer: http://stackoverflow.com/a/50594531
score: 4
upvote count: 4
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/50629843
tagged with: email
downvote count: 0

http://stackoverflow.com/comment/88189066
has text: I can't be certain, I don't see anything obvious, but I think it's got to do with rounding to pixel coords.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50589701
score: 0

http://stackoverflow.com/q/50549742
has comment: http://stackoverflow.com/comment/88110479
type: Question
upvote count: 2
has title: how to take specific data from a log file using python
has comment: http://stackoverflow.com/comment/88110411
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/88110402
answer count: 1
has body: I am beginner to python and I have a log file which contains MBX_AUTHENTICATION_FAILED where I already took the information of username, timestamp and IP address. My question is how can I take a username who has changed password for 10 times from log file, because the condition is whenever a user changes password for 10 times, we need the detail of the user such as username, timestamp and IP address. This is my log file: 20170119 193739188+0900 elim1td001p imapserv 52324 75559 132341478487808 Note;UserDataException(504/1) MBX_AUTHENTICATION_FAILED:{protocolType=[imap], userName=[teasst_emailrei_6000], password=[XXXXX]}:AuthenticateAndGetMailboxService\3aPOST:Authenticating Failed.::user=test_emaili_3000:cmd=1 LOGIN teasst_emailrei_6000 &lt;password&gt;:fromhost=129.0.0.1:sid=b34f10a-fd04-11e7-b246-7f629ba04def This is my python code import re from csv import writer import datetime log_file = '/Users/kiya/Desktop/ip.txt' output_file = '/Users/kiya/Desktop/output.csv' name_to_check = 'MBX_AUTHENTICATION_FAILED' with open(log_file,encoding="utf-8") as infile: for line in infile: if name_to_check in line: username = re.search(r'(?&lt;=userName=\[)(.*)(?=\],)', line) username = username.group() date = re.search(r'(?P&lt;date&gt;\d{8})\s+(?P&lt;time&gt;\d{9})\+(?P&lt;zone&gt;\d{4})', line) date = datetime.datetime.strptime(date.group('date'), "%Y%m%d").strftime("%Y-%m-%d") print(date) time = re.search(r'(?P&lt;date&gt;\d{8})\s+(?P&lt;time&gt;\d{9})\+(?P&lt;zone&gt;\d{4})', line) time = datetime.datetime.strptime(time.group('time'), "%H%M%S%f").strftime("%H:%M:%S") print(time) ip = re.search(r'(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])',line) ip = ip.group() with open(output_file, 'w') as outfile: csv_writer = writer(outfile) csv_writer.writerow(["Username","Date","Time","Ip"]) csv_writer.writerow([username,date,time,ip])
has answer: http://stackoverflow.com/a/50549801
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88110387
score: 2
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88110329

http://stackoverflow.com/comment/88419110
type: AnswerComment
has text: @RienekevanNoort See my updated answer. I removed parts of your code because the functions are missing. However, this works on my machine producing two plots as expected.
comment on: http://stackoverflow.com/a/50696297
type: Comment
score: 0

http://stackoverflow.com/comment/88135044
has text: It is `len(iterable) / (len(processes) * 4 )`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50561455

http://stackoverflow.com/a/53130687
score: 1
downvote count: 0
has body: I had the same problem. Installing it over PyCharm IDE solved the problem for me. I am using Windows as an OS. Installing packages over PyCharm works in general better for me than over Windows cmd.
upvote count: 1
answers question: http://stackoverflow.com/q/50634832
type: Answer

http://stackoverflow.com/q/50634986
tagged with: keras
has answer: http://stackoverflow.com/a/50641469
possible better answer: http://stackoverflow.com/a/70315382
type: Question
has title: complete Keras Lambda confusion
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50641469
favorite count: 0
has body: I was trying to define a Lambda layer Keras, as follows: First, a function which computes the wavelet transform of an image and then gloms it together: from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D from keras.layers import Activation, Dropout, Flatten, Dense from keras.layers import BatchNormalization from keras.layers import Lambda from keras import regularizers from keras import backend as K import pywt import numpy as np from keras.engine.topology import Layer def mkwtarray(image): channels = K.image_data_format() if channels is 'channels_first': axbase = 1 else: axbase = 0 print(axbase) print(image.shape) (a,( b, c, d ))= pywt.dwt2(image, 'db1', axes=(axbase, axbase+1)) ab = np.concatenate((a, b), axis=axbase) cd = np.concatenate((c, d), axis=axbase) abcd = np.concatenate((ab, cd), axis=axbase+1) return abcd def wtoutshape(input_shape): return input_shape train_data_dir = 'train' validation_data_dir = 'validation' nb_train_samples = 21558 nb_validation_samples = 3446 epochs = 30 batch_size = 32 if K.image_data_format() == 'channels_first': input_shape = (3, img_width, img_height) else: input_shape = (img_width, img_height, 3) model = Sequential() model.add(Lambda(mkwtarray, input_shape=input_shape, output_shape = wtoutshape)) &lt;more random layers&gt; Much to my amazement, as I was defining the model (meaning, evaluated the lines above), it errored out, claiming: ValueError: Input array has fewer dimensions than the specified axes Also, the 'print' statements, which printed the expected values 0 and (?, 150, 150, 3) fired, which means that the function was actually evaluated at definition time, not when the model was actually running. I am obviously missing something about Keras' Lambda functionality - any enlightenment would be appreciated. UPDATE The exact same problem presents itself if you define a layer in the "general" way (via a class, where the lambda is now in …
answer count: 2
has comment: http://stackoverflow.com/comment/88280267
upvote count: 1
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/88283014
has comment: http://stackoverflow.com/comment/88283433
downvote count: 1
has answer: http://stackoverflow.com/a/70315382

http://stackoverflow.com/a/50571968
has comment: http://stackoverflow.com/comment/88153633
score: 2
accepted answer of: http://stackoverflow.com/q/50571888
upvote count: 2
has body: The queryset attribute should be lower case at all. all your views contain querySet replace them by queryset lower case Or you can provide the model attribute model = ModelName See more In the Official Documentation
answers question: http://stackoverflow.com/q/50571888
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/88326030
comment on: http://stackoverflow.com/q/50648920
has text: What instance type? Did you install the GPU drivers?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50569801
has comment: http://stackoverflow.com/comment/88150386
tagged with: python
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/88149433
has comment: http://stackoverflow.com/comment/88157515
type: Question
has comment: http://stackoverflow.com/comment/88149470
has comment: http://stackoverflow.com/comment/88149535
has comment: http://stackoverflow.com/comment/88154457
tagged with: pandas
has body: Have two dataframes: How to merge df1 with df2 so that we get the following result is obtained based on X: Ticker Type Date ====== ==== ==== OEX Index 2018-06-01 XEO Index 2018-06-01 SPX Index 2018-06-01 SPX Index 2018-06-08 SPX Index 2018-06-22 ...and so on... df1: Ticker Type Std_Week EOW ====== ==== ======== === 12 OEX Index X NaN 13 XEO Index X NaN 14 SPX Index NaN X 15 XSP Index NaN X df2: Std_Week EOW ======== === 0 2018-06-01 00:00:00 2018-06-01 00:00:00 1 NaN 2018-06-08 00:00:00 2 NaN 2018-06-22 00:00:00 3 NaN 2018-06-29 00:00:00 4 NaN 2018-07-06 00:00:00
type: UnansweredQuestion
has title: Conditional merge of dataframes

http://stackoverflow.com/a/54554121
has comment: http://stackoverflow.com/comment/112394215
upvote count: 4
type: Answer
answers question: http://stackoverflow.com/q/50671565
downvote count: 1
has body: I had the same issue and it was because I forgot to set the environment variable %MALLET_HOME% import os from gensim.models.wrappers import LdaMallet os.environ['MALLET_HOME'] = 'C:/.../mallet-2.0.8/'
score: 3
has comment: http://stackoverflow.com/comment/122463473

http://stackoverflow.com/comment/94161758
has text: maybe this will help? https://stackoverflow.com/questions/27150518/creating-jpg-png-from-ppt-pptx-file-in-django
score: 0
comment on: http://stackoverflow.com/q/50672300
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50608129
tagged with: gmail
type: Question
score: 0
has comment: http://stackoverflow.com/comment/88226494
has comment: http://stackoverflow.com/comment/88226777
has body: The following script works perfectly fine from my Win 10 box using Python 3.6: import smtplib,subprocess def send_email(user, pwd, recipient, subject, body): FROM = user TO = recipient if isinstance(recipient, list) else [recipient] SUBJECT = subject TEXT = body # Prepare actual message message = """From: %s\nTo: %s\nSubject: %s\n\n%s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) try: server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.login(user, pwd) server.sendmail(FROM, TO, message) server.close() print ('successfully sent the mail') except Exception as e: print(e) print ("failed to send mail") send_email("user@gmail.com", "pass", "dst@email.com", "some subject", "some body") However, it fails with a "Please log in via your web browser and\n5.7.14 then try again" when I try to run it from a Ubuntu 16.04 box and Python 3.5.2. I should mention that "allow unsecure apps" is enabled on my gmail account (didnt work from the Win box without it).
has title: Python gmail-smtp script works from win\3.6, not linux\3.5.2
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/88214247
type: Comment
has text: `scrapy crawl stringpage -o dict.csv` command. @MaximilianPeters
score: 0
comment on: http://stackoverflow.com/q/50602414
type: QuestionComment

http://stackoverflow.com/comment/88243531
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50615283
type: AnswerComment
has text: This, incredibly, worked - thank you very much! Can you explain what's going on in the final step - specifically, the section within the for loop?

http://stackoverflow.com/comment/88306520
has text: Will that work if my indices are numeric and my data is pandas?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50612523

http://stackoverflow.com/a/50615283
has body: This is one solution using csv.DictReader and collections.defaultdict. You can define a specific nested dictionary structure. Then iterate once over your input file, adding items for each dictionary resulting from DictReader. Using a similar method you can also opt for a dictionary with tuple keys. This will be more efficient for lookups but make iteration more cumbersome. from collections import defaultdict import csv d = defaultdict(lambda: defaultdict(lambda: defaultdict(list))) with open('file.csv', 'r') as fin: reader = csv.DictReader(fin, quotechar="'", skipinitialspace=True) for i in reader: d[i['sample']][i['date']][i['depth']].append([i['analyte'], float(i['result'])]) Result print(d) defaultdict({'ABC': defaultdict({'01/01/2018': defaultdict(list, {'3': [['LEAD', 0.22], ['MERCURY', 0.97]], '5': [['LEAD', 0.19], ['MERCURY', 0.34]]}), '02/01/2018': defaultdict(list, {'3': [['LEAD', 0.25], ['MERCURY', 0.95]], '5': [['LEAD', 0.18], ['MERCURY', 0.11]]})}), 'DEF': defaultdict({'01/01/2018': defaultdict(list, {'3': [['LEAD', 0.07], ....
type: Answer
accepted answer of: http://stackoverflow.com/q/50615059
answers question: http://stackoverflow.com/q/50615059
score: 0
has comment: http://stackoverflow.com/comment/88243531
type: AcceptedAnswer

http://stackoverflow.com/q/50601935
favorite count: 0
upvote count: 2
has body: I'm debugging my python application using VSCode. I have a main python file from where I start the debugger. I'm able to put breakpoints in this file, but if I want to put breakpoints in other files which are called by the main file, I get them as 'Unverified breakpoint' and the debugger ignores them. How can I change my launch.json so that I'm able to put breakpoints on all the files in my project? Here's my current launch.json: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Current File", "type": "python", "request": "launch", "program": "${file}" }, { "name": "Python: Attach", "type": "python", "request": "attach", "localRoot": "${workspaceFolder}", "remoteRoot": "${workspaceFolder}", "port": 3000, "secret": "my_secret", "host": "localhost" }, { "name": "Python: Terminal (integrated)", "type": "python", "request": "launch", "program": "${file}", "console": "integratedTerminal" }, { "name": "Python: Terminal (external)", "type": "python", "request": "launch", "program": "${file}", "console": "externalTerminal" }, { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "runserver", "--noreload", "--nothreading" ], "debugOptions": [ "RedirectOutput", "Django" ] }, { "name": "Python: Flask (0.11.x or later)", "type": "python", "request": "launch", "module": "flask", "env": { "FLASK_APP": "${workspaceFolder}/app.py" }, "args": [ "run", "--no-debugger", "--no-reload" ] }, { "name": "Python: Module", "type": "python", "request": "launch", "module": "nf.session.session" }, { "name": "Python: Pyramid", "type": "python", "request": "launch", "args": [ "${workspaceFolder}/development.ini" ], "debugOptions": [ "RedirectOutput", "Pyramid" ] }, { "name": "Python: Watson", "type": "python", "request": "launch", "pro…
tagged with: python
tagged with: vscode-debugger
accepted answer: http://stackoverflow.com/a/50836626
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/58287013
has answer: http://stackoverflow.com/a/58287013
type: Question
tagged with: visual-studio-code
has comment: http://stackoverflow.com/comment/88234437
answer count: 2
tagged with: breakpoints
has answer: http://stackoverflow.com/a/50836626
has title: VSCode python 'Unverified breakpoint' during debugging?
has comment: http://stackoverflow.com/comment/102938805
downvote count: 0

http://stackoverflow.com/comment/88233980
comment on: http://stackoverflow.com/a/50611194
type: AnswerComment
score: 0
has text: I'm not sure. You may need to ask a separate question.
type: Comment

http://stackoverflow.com/q/50664601
has body: I'm writing a code to understand inheritance and here is what I did so far. class Master: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name self.full_name = first_name + last_name self.email_id = (first_name + last_name + '@vit.com').lower() class Student(Master): def __init__(self, first_name, last_name, reg_num): super().__init__(first_name, last_name) self.reg_num = reg_num def __str__(self): return self.first_name + " " + self.last_name class Proctor(Master): def __init__(self, first_name, last_name, students=None): super().__init__(first_name, last_name) if students is None: self.students = [] else: self.students = students stud_1 = Student('kishan', 'B', '16BEI0067') proctor_1 = Proctor('Mani', 'Mozhi', [stud_1]) print(proctor_1.students) When the last print statement excutes, instead of getting the details of stud_1, I get [&lt;__main__.student object at 0x7f362206a908>] What is going wrong?
tagged with: inheritance
has answer: http://stackoverflow.com/a/50664655
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/88339251
has answer: http://stackoverflow.com/a/50664681
tagged with: python-3.x
has title: List not printing in python
has comment: http://stackoverflow.com/comment/88339327
tagged with: python
linked to: http://stackoverflow.com/q/1984162
has answer: http://stackoverflow.com/a/50664656
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88339570
has comment: http://stackoverflow.com/comment/88339544
type: Question

http://stackoverflow.com/comment/88251008
type: Comment
type: QuestionComment
has text: the correct result should be same as the above dictionary
score: 0
comment on: http://stackoverflow.com/q/50620529

http://stackoverflow.com/a/64558207
has body: The hierarchical clustering method is based on dendrogram to determine the optimal number of clusters. Plot the dendrogram using a code similar to the following: # General imports import numpy as np import matplotlib.pyplot as plt import pandas as pd # Special imports from scipy.cluster.hierarchy import dendrogram, linkage # Load data, fill in appropriately X = [] # How to cluster the data, single is minimal distance between clusters linked = linkage(X, 'single') # Plot dendrogram plt.figure(figsize=(10, 7)) dendrogram(linked, orientation='top', labels=labelList, distance_sort='descending', show_leaf_counts=True) plt.show() In the dendrogram locate the largest vertical difference between nodes, and in the middle pass an horizontal line. The number of vertical lines intersecting it is the optimal number of clusters (when affinity is calculated using the method set in linkage). See example here: https://stackabuse.com/hierarchical-clustering-with-python-and-scikit-learn/ How to automatically read a dendrogram and extract that number is something I would also like to know. Added in edit: There is a way to do so using SK Learn package. See the following example: #========================================================================== # Hierarchical Clustering - Automatic determination of number of clusters #========================================================================== # General imports import pandas as pd import numpy as np import matplotlib.pyplot as plt import pandas as pd from os import path # Special imports from scipy.cluster.hierarchy import dendrogram, linkage import scipy.cluster.hierarchy as shc from sklearn.cluster import AgglomerativeClustering # %matplotlib inline print("============================================================") print(" Hierarchical Clustering demo - num of clusters ") print("============================================================") print(" ") folder = path.dirname(path.realpath(__file__)) # set current folder # Load…
type: Answer
has comment: http://stackoverflow.com/comment/136273718
downvote count: 0
score: 7
upvote count: 7
answers question: http://stackoverflow.com/q/50695226

http://stackoverflow.com/q/50589489
has comment: http://stackoverflow.com/comment/88188390
has comment: http://stackoverflow.com/comment/88188379
has comment: http://stackoverflow.com/comment/88188480
answer count: 2
favorite count: 0
tagged with: python-3.x
has body: So for this internship I am doing, I need to use the integral of (x^(9/2))/((1-x)^2) as part of an equation I am graphing. However, the variable that I am graphing along the x axis appears in both limits of integration. Since I am a complete and total novice at python, my code is atrocious, but I ended up copy+pasting the indefinite integral twice, plugging in the limits of integration, and subtracting. How can I make the code better? import numpy as np import matplotlib.pyplot as plt from scipy import integrate x = np.arange(0,2.5,0.00001) zs = 8 zr = 6 rbub = 5 sig = 2.5 XHI = 0.5 sigma = 10**-sig L = 10**-3 zb = zs - (((1 + zs)/8)**(3/2)) * (0.0275) * (rbub/10) a = (1+zr)/((1+zs)*(x+1)) b = (1+zb)/((1+zs)*(x+1)) def f(x): ans = 0.000140092 ans = ans * ((1+zs)**(3/2)) ans = ans * ((x+1)**(3/2)) ans = ans * XHI return ans * ((9/2)*(np.log(1-np.sqrt(b)) - np.log(np.sqrt(b)+1)) + (1/35 * (1/(b-1)) * (10*(b**(9/2)) + 18*(b**(7/2)) + 42*(b**(5/2)) + 210*(b**(3/2)) - 315*(b**(1/2))) - ((9/2)*(np.log(1-np.sqrt(a)) - np.log(np.sqrt(a)+1)) + (1/35 * (1/(a-1)) * (10*(a**(9/2)) + 18*(a**(7/2)) + 42*(a**(5/2)) + 210*(a**(3/2)) - 315*(a**(1/2)))))))
has comment: http://stackoverflow.com/comment/88189063
has comment: http://stackoverflow.com/comment/88189707
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88189858
tagged with: code-readability
has comment: http://stackoverflow.com/comment/88188337
has comment: http://stackoverflow.com/comment/88188401
tagged with: integration
downvote count: 1
type: Question
has title: Python3: How do I make this equation readable?
tagged with: readability
has comment: http://stackoverflow.com/comment/88188697
has answer: http://stackoverflow.com/a/50590127
has answer: http://stackoverflow.com/a/50589594
upvote count: 0
score: -1

http://stackoverflow.com/q/50652658
upvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50652669
has title: Keywords not comprised in module's symbol table
favorite count: 0
has answer: http://stackoverflow.com/a/50652669
tagged with: python
type: AnsweredQuestion
has body: I have such a drafts.py module: import subprocess print(globals()) Run it and get In [77]: subprocess.getoutput('python drafts.py') Out[77]: "{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': &lt;_frozen_importlib_external.SourceFileLoader object at 0x102c5a0b8&gt;, '__spec__': None, '__annotations__': {}, '__builtins__': &lt;module 'builtins' (built-in)&gt;, '__file__': 'drafts.py', '__cached__': None, 'subprocess': &lt;module 'subprocess' from '/Users/me/anaconda3/lib/python3.6/subprocess.py'&gt;}" I could read from the result that builtins and imported module included in its symbol table, However, the keywords are not involved in the symbol table. If not comprised in module's symbol table, how could I employ them unlimited?
downvote count: 1
type: Question
score: -1

python-collections
type: Tag
tag name: python-collections
tags question: http://stackoverflow.com/q/50579035

http://stackoverflow.com/q/50671297
tagged with: for-loop
has comment: http://stackoverflow.com/comment/88352413
downvote count: 0
has comment: http://stackoverflow.com/comment/88391028
has answer: http://stackoverflow.com/a/50671440
has title: for loops in Python - how to modify i inside the loop
favorite count: 0
has comment: http://stackoverflow.com/comment/88386339
upvote count: 8
answer count: 5
has answer: http://stackoverflow.com/a/50690796
tagged with: python
has answer: http://stackoverflow.com/a/50671346
accepted answer: http://stackoverflow.com/a/50671440
has comment: http://stackoverflow.com/comment/88384834
has comment: http://stackoverflow.com/comment/88386223
has answer: http://stackoverflow.com/a/50671414
has comment: http://stackoverflow.com/comment/88371317
has comment: http://stackoverflow.com/comment/88386503
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50671346
score: 8
has answer: http://stackoverflow.com/a/50690613
has comment: http://stackoverflow.com/comment/88352828
type: Question
has body: This code was written in Python 3.6 in Jupyter Notebooks. In other languages, I am pretty sure I built loops that looked like this: endRw=5 lenDF=100 # 1160 for i in range(0, lenDF): print("i: ", i) endIndx = i + endRw if endIndx &gt; lenDF: endIndx = lenDF print("Range to use: ", i, ":", endIndx) # this line is a mockup for an index that is built and used # in the real code to do something to a pandas DF i = endIndx print("i at end of loop", i) In testing though, i does not get reset to endIndx and so the loop does not build the intended index values. I was able to solve this problem and get what I was looking for by building a while loop like this: endRw=5 lenDF=97 # 1160 i = 0 while i &lt; lenDF: print("i: ", i) endIndx = i + endRw if endIndx &gt; lenDF: endIndx = lenDF print("Range to use: ", i, ":", endIndx) # this line is a mockup for an index that is built and used # in the real code to do something to a pandas DF i = endIndx print("i at end of loop: ", i) Question: is there a way to modify the i from inside the for loop in python? Is there a way to do what I did with the while loop using a for loop in Python? Solved the problem with while but just curious about this.

http://stackoverflow.com/q/50568374
has answer: http://stackoverflow.com/a/50568487
has answer: http://stackoverflow.com/a/50568547
type: Question
score: 0
has body: # Get N from the command line import sys N = int(sys.argv[1]) for N in range(1,4): N *= 4 print(N) So, 4! is 4*3*2*1 = 24. My output is only 16 and it wants me to output 24
possible better answer: http://stackoverflow.com/a/50568487
has answer: http://stackoverflow.com/a/50568509
tagged with: python
answer count: 4
has title: how to do a factorial for loop and get final output
has answer: http://stackoverflow.com/a/50568546
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50568546

http://stackoverflow.com/comment/88244944
has text: Glad it solved your issue. Please also "accept" the answer if you are happy with my solution
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50615563

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

http://stackoverflow.com/q/50694594
tagged with: odoo-10
tagged with: python
has body: Model:- from odoo import models, fields, api courses = [ ('mca', "MCA"), ('bca', "BCA"), ('bsc', "B.Sc"), ('msc', "M.Sc"), ('btech', "B.Tech"), ('mtech', "M.Tech"), ] class openacademy(models.Model): _name = 'openacademy.student' name = fields.Char(string="Student Name") roll = fields.Integer(string="Roll Number") course = fields.Selection(courses, string="Course") Groups:- Open Academy 10 Student Basic access Teacher Complete Access Model Access Rule (ir.model.access.csv):- id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink ACL_st,oa.ACL_st,model_openacademy_student,group_student,1,0,0,0 ACL_te,oa.ACL_te,model_openacademy_student,group_teacher,1,1,1,1 ACL_ng,oa.ACL_ng,model_openacademy_student,,1,1,1,1 Now if a student group user logs into the application then he is able to write/delete records but it has read permission only. I want that if logged in user don't belongs to any group then he can perform any operation and thats why I added this rule :- ACL_ng,oa.ACL_ng,model_openacademy_student,,1,1,1,1
has answer: http://stackoverflow.com/a/50696384
has title: Odoo model access rule is not working as expected
score: 1
upvote count: 1
type: AnsweredQuestion
tagged with: odoo
accepted answer: http://stackoverflow.com/a/50696384
type: Question
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/88179317
type: QuestionComment
has text: Full stack trace will be helpful
score: 2
type: Comment
comment on: http://stackoverflow.com/q/50581684

http://stackoverflow.com/q/50639576
tagged with: aws-lambda
tagged with: python
type: AnsweredQuestion
has body: I have lambda function to create new AMI and attach to current auto scale group. This function complete works when I create a test custom test case and pass the payload. Issue occurs when I trigger this from SNS: import json import boto3 import time import sys asObj = boto3.client('autoscaling') ec2Obj = boto3.client('ec2') def lambda_handler(event, context): targetASG = event[‘Records’][0][‘Sns’][‘Message’] ASG = asObj.describe_auto_scaling_groups(AutoScalingGroupNames=[event['targetASG']]) sourceInstanceId = ASG.get('AutoScalingGroups')[0]['Instances'][0]['InstanceId'] Date=time.strftime("%d%m%y") Time=time.strftime("%H%M%S") amiName = "Automated_%s_%s" % (Date, Time) configName = "Automated_%s_%s" % (Date, Time) CreateNewImage = ec2Obj.create_image( InstanceId = sourceInstanceId, Name = amiName, Description = 'Automatically Created Image from Lambda Service', NoReboot = True) Image = [] Image.append(CreateNewImage) def getCreatedID(Image): for i in Image: ID = i['ImageId'] return ID AMINewID = getCreatedID(Image) CreateNewConfig = asObj.create_launch_configuration( LaunchConfigurationName = configName, ImageId = AMINewID, InstanceId = sourceInstanceId) updateASG = asObj.update_auto_scaling_group( AutoScalingGroupName = event['targetASG'], LaunchConfigurationName = configName) return 'A new AMI has been Created `%s` Updated ASG `%s` with new launch configuration `%s` which includes AMI `%s`.' % (amiName,event['targetASG'], configName, AMINewID) To trigger my lambda function I use AWS SNS topic and I publish a msg following message, message type: raw { "targetASG": "pre-production-xxx" } But I get this error: 'targetASG': KeyError Traceback (most recent call last): File "/var/task/lambda_function.py", line 13, in lambda_handler ASG = asObj.describe_auto_scaling_groups(AutoScalingGroupNames=[event['targetASG']]) KeyError: 'targetASG' How can I resolve this?
has title: AWS Lambda key error
type: Question
tagged with: boto3
tagged with: amazon-web-services
score: 0
has answer: http://stackoverflow.com/a/50642067
answer count: 1
accepted answer: http://stackoverflow.com/a/50642067

http://stackoverflow.com/q/50554937
has comment: http://stackoverflow.com/comment/88123920
score: 3
has comment: http://stackoverflow.com/comment/88160499
downvote count: 0
has comment: http://stackoverflow.com/comment/88123452
type: Question
upvote count: 3
has title: Folium markers with Pandas data. Why do no markers show up?
tagged with: pandas
has body: I am attempting to plot gun violence incidents in the U.S. from the kaggle data set on U.S. gun violence 2013-2018. With some research I found that folium is a good option for me. However, after many attempts and much googling, I cannot in any way get the markers to show up on the map (except for the initial one, and one more which persistently shows up further north than the initial one - I have no clue whether it represents an actual incident or it is some sort of bug). The data set is a pandas df, and I made a subset it of it only including the longitude, latitude, incident_id and n_killed variables for this part of the process. Admittedly there are 250k incidents, so any and all plotting would take lots of time - but I am willing to wait if it works. I'm open to suggestion for other packages that are perhaps more suitable for this process. Here is my code as I have tried it thus far: folium_map = folium.Map(location=[40.00, -73.00], zoom_start=13, tiles="CartoDB dark_matter") marker = folium.CircleMarker(location=[40.738, -73.98]) marker.add_to(folium_map) for index, row in gunviolence_try.iterrows(): if row['n_killed'] &gt;2: color="#E37222" else: color="#0A8A9F" folium.CircleMarker(location=(row["latitude"], row["longitude"]), color = color, fill=True).add_to(folium_map) folium_map Any and all pointers for how to go about this are really appreciated!
tagged with: geospatial
tagged with: folium
favorite count: 0
has comment: http://stackoverflow.com/comment/88122175
has comment: http://stackoverflow.com/comment/88124144
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88144684
tagged with: python
has comment: http://stackoverflow.com/comment/88124420
has comment: http://stackoverflow.com/comment/88124310

button
tags question: http://stackoverflow.com/q/50572710
tags question: http://stackoverflow.com/q/50686096
type: Tag
tags question: http://stackoverflow.com/q/50557450
tags question: http://stackoverflow.com/q/50668894
tags question: http://stackoverflow.com/q/50557594
tag name: button

http://stackoverflow.com/q/50663334
type: Question
has comment: http://stackoverflow.com/comment/88336730
has comment: http://stackoverflow.com/comment/88336795
has comment: http://stackoverflow.com/comment/88336791
tagged with: series
has body: I am looking to compare two dataframe end1 and tt1, what I want to do is to see when if an event in tt1 influences an event in end1 at roughly the same time When I am trying to create a simple loop to look for events at roughly the same time , I get the error message : ValueError: Can only compare identically-labeled Series objects end1['end_date'] = pd.to_datetime(end1['end_date'], format = '%Y/%m/%d %H:%M') tt1['Minstart'] = pd.to_datetime(tt1['Minstart'], format = '%Y/%m/%d %H:%M') tt1['Maxstart'] = pd.to_datetime(tt1['Maxstart'], format = '%Y/%m/%d %H:%M') for index, row in end1.iterrows(): if end1['end_date'] &gt; tt1['Minstart']: if end1['end_date'] &lt; tt1['Maxstart']: d = end1.count(end1.end_date) print(d) both are : pandas.core.series.Series Thank you
score: 0
upvote count: 1
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/88336741
tagged with: valueerror
favorite count: 0
tagged with: python-3.x
tagged with: datetime
has answer: http://stackoverflow.com/a/50673135
accepted answer: http://stackoverflow.com/a/50673135
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88336787
has comment: http://stackoverflow.com/comment/88336725
has title: Date time : ValueError: Can only compare identically-labeled Series objects - Python
has comment: http://stackoverflow.com/comment/88337503

http://stackoverflow.com/a/50689973
has comment: http://stackoverflow.com/comment/88389685
type: Answer
has comment: http://stackoverflow.com/comment/88947801
accepted answer of: http://stackoverflow.com/q/50689935
answers question: http://stackoverflow.com/q/50689935
has body: Assuming that there are no deviations from the format of your input string, a dictionary comprehension and re.findall() should work: d = {k: float(v) for (v,k) in re.findall(r"(\d+) (\w+)", s)} Example: import re s = "I have 10 bla, 50 blo, 10 blu" d = {k: float(v) for (v,k) in re.findall(r"(\d+) (\w+)", s)} print(d) # {'bla': 10.0, 'blo': 50.0, 'blu': 10.0} s = "I have 50 blo, 5 blu" d = {k: float(v) for (v,k) in re.findall(r"(\d+) (\w+)", s)} print(d) # {'blo': 50.0, 'blu': 5.0}
upvote count: 1
has comment: http://stackoverflow.com/comment/88389724
type: AcceptedAnswer
downvote count: 1
score: 0

http://stackoverflow.com/comment/88297394
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50643610
score: 0
has text: there been a cookies issue or internet problem

http://stackoverflow.com/q/50572997
has comment: http://stackoverflow.com/comment/88273258
has title: Python Server Socket: check if it exists
tagged with: python
has comment: http://stackoverflow.com/comment/88155941
has comment: http://stackoverflow.com/comment/88273010
has comment: http://stackoverflow.com/comment/88211559
tagged with: serversocket
answer count: 0
has comment: http://stackoverflow.com/comment/88272777
type: Question
has comment: http://stackoverflow.com/comment/88211707
has body: A microcontroller program opens a server socket waiting for connections. Then enters a 'forever' loop listening for connections and treating them. What if the server socket gets lost somehow? I look for a method to check if the server socket is available and if not: restart it. If this is not the normal way to treat sockets please let me know a better way. Sorry for the abstract form - I actually found no suitable code. while( True ): # until Reset or power down if( not server_socket_active() ): # (1) looking for such a function open_server_socket() start_listening() if( client_connect ): handle_client_data() I have a working connection with Server Sockets and Client Sockets connecting to it. It uses a polling loop with socket.socket() So no code is needed except for a sequence/method/function performing (1). Thank you for any advice. Or coud it be done with socket.socket() ?
score: 0
has comment: http://stackoverflow.com/comment/88212321
tagged with: python-3.x
type: UnansweredQuestion
tagged with: sockets

http://stackoverflow.com/comment/88145876
has text: your function returns a function... you have to call it: `str(doubler(val))` for instance
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50567951
type: QuestionComment

http://stackoverflow.com/comment/88401936
type: Comment
comment on: http://stackoverflow.com/a/50686804
has text: Hi, @Neb, thanks for your answer. You're quite right, these are two distinct cases. I'll check which one it is. Regarding your answers to both cases though, I've implemented the same network in Keras and it performs well with the data I have so I thought there may be a syntactic error in my code.
score: 0
type: AnswerComment

http://stackoverflow.com/a/50667660
has body: You basically just need to replace the max with sorted: L = [[1,2],[4,3]] # step 1: add indices to each list element L_with_indices = ((n,i,j) for i, L2 in enumerate(L) for j, n in enumerate(L2)) # step 2: sort by value sorted_L = sorted(L_with_indices, reverse=True) # step 3: remove the value and keep the indices result = [tup[1:] for tup in sorted_L] # result: [(1, 0), (1, 1), (0, 1), (0, 0)]
answers question: http://stackoverflow.com/q/50667587
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50667587
score: 3
upvote count: 3

http://stackoverflow.com/comment/88542230
has text: @coldspeed My second favorite thing about this question is this benchmarking code. Perhaps add that to a tag wiki so that a wider audience can reuse it?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50559079

http://stackoverflow.com/comment/88221264
type: QuestionComment
has text: Your question is hard to understand. It seems that Range is defined in core.py, not in construct.
score: 1
comment on: http://stackoverflow.com/q/50605894
type: Comment

http://stackoverflow.com/comment/88193737
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50591442
score: 0
has text: @CrisLuengo are the images in mnist dataset not a 2d matrix ?

http://stackoverflow.com/comment/109858833
type: AnswerComment
score: 0
has text: you have to be on osx to do that
type: Comment
comment on: http://stackoverflow.com/a/55326428

http://stackoverflow.com/q/50593337
answer count: 3
tagged with: apache-spark
accepted answer: http://stackoverflow.com/a/50597191
favorite count: 0
has comment: http://stackoverflow.com/comment/88196786
has answer: http://stackoverflow.com/a/50597191
tagged with: python
possible better answer: http://stackoverflow.com/a/62471013
type: AnsweredQuestion
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/75508586
type: Question
has comment: http://stackoverflow.com/comment/88196509
has comment: http://stackoverflow.com/comment/88197168
has comment: http://stackoverflow.com/comment/88196369
has title: How to Set Pyspark Dataframe Headers to another Row?
tagged with: pyspark
has body: I have a dataframe that looks like this: # +----+------+---------+ # |col1| col2 | col3 | # +----+------+---------+ # | id| name | val | # | 1 | a01 | X | # | 2 | a02 | Y | # +---+-------+---------+ I need to create a new dataframe from it, using row[1] as the new column headers and ignoring or dropping the col1, col2, etc. row. The new table should look like this: # +----+------+---------+ # | id | name | val | # +----+------+---------+ # | 1 | a01 | X | # | 2 | a02 | Y | # +---+-------+---------+ The columns can be variable, so I can't use the names to set them explicitly in the new dataframe. This is not using pandas df's.
has answer: http://stackoverflow.com/a/62471013
upvote count: 2

http://stackoverflow.com/q/50602157
tagged with: datetime
has comment: http://stackoverflow.com/comment/88213358
tagged with: python
accepted answer: http://stackoverflow.com/a/50602386
has body: I have this large data frame and I need to when certain resource are available for the first time. Let me explain it from my code. df1 = df[df['Resource_ID'] == 1348] df1 = df1'Format', 'Range_Start', 'Number' df1["Range_Start"] = df1["Range_Start"].str[:7] df1 = df1.groupby(['Format', 'Range_Start'], as_index=True).last() pd.options.display.float_format = '{:,.0f}'.format df1 = df1.unstack() df1.columns = df1.columns.droplevel() df2 = df1[1:4].sum(axis=0) df2.name = 'sum' df2 = df1.append(df2) df3 = df2.T'entry', 'sum'.copy() df3.index = pd.to_datetime(df3.index) Now print(df3.first('1D')) gives the following output: Format entry sum Range_Start 2011-07-01 97 72 I can now see that Resource_ID 1348 first occurs on 2011-07-01, how do I extract only the Year from this information? This is my sample input csv data: Access_Stat_ID,Resource_ID,Range_Start,Range_End,Name,Format,Number,Matched_URL 1,15,"2009-03-01 00:00:00","2009-03-31 23:59:59","Mar 2009","entry",3,"" 203,13,"2009-04-01 00:00:00","2009-04-30 23:59:59","Apr 2009","entry",18,"" 204,13,"2009-04-01 00:00:00","2009-04-30 23:59:59","Apr 2009","pdf",7,""
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88213501
has answer: http://stackoverflow.com/a/50602386
type: Question
tagged with: dataframe
score: 0
tagged with: pandas
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
has title: Pandas extract the first year from dataframe

http://stackoverflow.com/comment/88120489
type: QuestionComment
score: 1
has text: What exactly is meant by "make its own variable in python"? Do you mean can a class create variables with values specific to each instances?
comment on: http://stackoverflow.com/q/50554821
type: Comment

http://stackoverflow.com/comment/88251287
score: 1
has text: There are various uses, such making a wrapper from a decorator look the same as the wrapped function, e.g. using `functools.wraps`. But there's a lot of concepts there that would need to be unpacked carefully for a beginner. For now, don't worry about it.
comment on: http://stackoverflow.com/q/50620594
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50681651
upvote count: 7
type: AcceptedAnswer
has body: crosstab + div Using pandas.crosstab: res = pd.crosstab(df['Kind'], df['Status']) res'Pct False', 'Pct True' = res.div(res.sum(axis=1), axis=0) print(res) Status False True Pct False Pct True Kind 1 0 1 0.000000 1.000000 2 2 1 0.666667 0.333333 3 0 1 0.000000 1.000000 In my opinion, this is the most natural way to display your data. Combining counts with percentages in a single series is not recommended. crosstab + crosstab normalize Alternatively, you can join a couple of crosstab results, one normalized, the other not. res = pd.crosstab(df['Kind'], df['Status'])\ .join(pd.crosstab(df['Kind'], df['Status'], normalize='index'), rsuffix='_pct') print(res) Status False True False_pct True_pct Kind 1 0 1 0.000000 1.000000 2 2 1 0.666667 0.333333 3 0 1 0.000000 1.000000 crosstab normalize only If you are looking only for percentages, you can just use the normalize argument: res = pd.crosstab(df['Kind'], df['Status'], normalize='index') print(res) Status False True Kind 1 0.000000 1.000000 2 0.666667 0.333333 3 0.000000 1.000000
type: Answer
downvote count: 0
score: 7
accepted answer of: http://stackoverflow.com/q/50681409
answers question: http://stackoverflow.com/q/50681409

http://stackoverflow.com/comment/88127424
has text: What's your question, your question is not clear
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50558262

http://stackoverflow.com/q/50680327
has answer: http://stackoverflow.com/a/50680519
has title: find my mouse position. help me
type: Question
answer count: 1
score: 0
tagged with: python
linked to: http://stackoverflow.com/q/22108738
has comment: http://stackoverflow.com/comment/88370290
has comment: http://stackoverflow.com/comment/88370662
has body: I have two questions about making mouse position. I don't know why this code is not working. This code presents current mouse position, but the problem is print('\b' * len(positionStr), end='', flush=True). It is not working. The book said it removes the old position of the mouse, but it did not work. import pyautogui print('Press Ctrl-C to quit') try: while True: x, y = pyautogui.position() positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4) print(positionStr, end='') print('\b' * len(positionStr), end='', flush=True) except KeyboardInterrupt: print('\n') Screenshot Second, why doesn't it work in pycharm? I just can try that in the python idle.
type: UnansweredQuestion
tagged with: mouse

tensorflow-lite
tags question: http://stackoverflow.com/q/50632152
tag name: tensorflow-lite
tags question: http://stackoverflow.com/q/50581883
type: Tag

http://stackoverflow.com/comment/88229359
comment on: http://stackoverflow.com/a/50609438
type: AnswerComment
score: 0
type: Comment
has text: Thanks again for you detailed comments. Yes, I now understand even better that my app will remember because of the session cookie. However, to be precise, I have also sent a GET request to the `/v2/logout?federated` and nothing changed (perhaps I am missing something here). Therefore, for concluding, do I have to do anything by sending a http request to `Auth0` or only I have to do something (clearing etc) with my session on `Flask` for making the log-in window to appear again?

http://stackoverflow.com/q/50638548
accepted answer: http://stackoverflow.com/a/51527195
has body: I'm working on a custom module and i need to add field to res.partner model. I've add some field to this model but since 1 week, when i try to add a new one i got this error : ERROR: column res_partner.my_field does not exist Other field works good but not this one : my_field = fields.Boolean(default=False) I really don't unterstand why i have this issue. I've try to add 'contacts' dependencies to my module, it have work on my local version but not on my online verison If somone has any idea it could be really nice Thanks for your help Edit res.partner classe from odoo import api, fields, models class ResPartner(models.Model): _inherit = 'res.partner' badge_ids = fields.One2many('mymodule.badge','client_i sub_ids = fields.One2many('mymodule.subs','client_id') #field that doesn't work my_field = fields.Boolean(default=False) Manifest dependencies 'depends': ['base', 'sale', 'website', 'calendar','contacts', 'point_of_sale', 'base_automation'],
tagged with: python
answer count: 4
type: AnsweredQuestion
tagged with: odoo-11
possible better answer: http://stackoverflow.com/a/50644250
has answer: http://stackoverflow.com/a/58671048
has answer: http://stackoverflow.com/a/50644250
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/88291479
downvote count: 0
has answer: http://stackoverflow.com/a/51527195
score: 4
has comment: http://stackoverflow.com/comment/88411988
has title: Error column doesn't exist on custom module Odoo
has answer: http://stackoverflow.com/a/54683421
favorite count: 0
has comment: http://stackoverflow.com/comment/88412612

http://stackoverflow.com/comment/88232567
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50611275
has text: It'll be much easier to help if you share the code that you already made.
score: 0

http://stackoverflow.com/q/50576975
tagged with: python-2.7
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/50583367
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/50583367
type: AnsweredQuestion
has body: I'm facing a problem related to display properly the tooltip of the HoverTool in my Bokeh Plotting. My intention is to display only a single one, using the attribute: mode = vline As the desired plot is shown bellow: However, my plot is rendering one tooltip for each glyph (series) that the vline crosses during the interaction with the Figure, as it can be seen: Even when I change the attribute Mode to "mouse", the Figure continue to render more than one tooltip: My code: [an assembly function, part of a bigger project] from bokeh.models import (HoverTool, ColumnDataSource, Title, DatetimeTickFormatter) import pandas as pd from bokeh.io import show, output_file from bokeh.plotting import figure def assembly_chart(df, complements): """function to assembly the chart""" output_file("movigrama_chart.html") source = ColumnDataSource(df) p = figure(x_axis_type='datetime', x_axis_label='days of moviment', y_axis_label='unities movimented', plot_width=1230, plot_height=500, active_scroll='wheel_zoom') p.vbar(x='DT', bottom=0, top='STOCK', width=pd.Timedelta(days=1), fill_alpha=0.4, color='#99d8c9', source=source) p.vbar(x='DT', bottom=0, top='SOMA_SAI', width=pd.Timedelta(days=1), fill_alpha=0.8, color='crimson', source=source) p.vbar(x='DT', bottom=0, top='SOMA_ENTRA', width=pd.Timedelta(days=1), fill_alpha=0.8, color='seagreen', source=source) p.add_layout(Title(text=complements['warehouse'], text_font='helvetica', text_font_size='10pt', text_color='orangered', text_alpha=0.5, align='center', text_font_style="italic"), 'above') p.add_layout(Title(text=complements['product'], text_font='helvetica', text_font_size='10pt', text_color='orangered', text_alpha=0.5, align='center', text_font_style="italic"), 'above') p.add_layout(Title(text='Movigrama Endicon', text_font='helvetica', text_font_size='16pt', text_color='orangered', text_alpha=0.9, align='center', text_font_style="bold"), 'above') p.x_range.range_padding = 0.1 p.y_range.range_padding = 0.1 p.outline_line_width = 4 …
tagged with: bokeh
has title: Bokeh: Display only a single tooltip
type: Question
downvote count: 0
score: 4
upvote count: 4

http://stackoverflow.com/q/50655222
answer count: 1
downvote count: 0
has body: my_df = DataFrame(np.arange(1,13).reshape(4,3), columns=list('abc')) my_df.sum(axis="rows") O/P is a 22 b 26 c 30 // I expect it to sum by rows thereby giving 0 6 1 15 2 24 3 33 my_df.sum(axis="columns") //helps achieve this Why does it work counterintutively? In a similar context, drop method works as it should i.e when i write my_df.drop(['a'],axis="columns") // This drops column "a". Am I missing something? Please enlighten.
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/50655283
type: Question
has title: pandas DataFrame sum method works counterintuitively
tagged with: dataframe
tagged with: pandas

http://stackoverflow.com/q/50585306
possible better answer: http://stackoverflow.com/a/50586845
type: Question
has answer: http://stackoverflow.com/a/50597467
has body: I couldn't find the exact same question in stack-overflow. Apologies, if this is a repeated question. I am using this code snippet to pass query to a table. _body = {'_query':'SELECT * FROM `&lt;projectId&gt;.&lt;datasetId&gt;.&lt;tableId&gt;`', 'useLegacySql': False, 'maxResults': 100 } table = _bq.jobs().query(projectId= &lt;projectId&gt;,alt = "json", body = _body).execute() I am passing all the required arguments, since using jobs.query API, I am getting status code 200, with the results, but while integrating the snippet in python program, I get following error: File "D:\Applications\Python27\lib\site-packages\oauth2client\_helpers.py", line 133, in positional_wrapper\n return wrapped(*args, **kwargs)\n', ' File "D:\Applications\Python27\lib\site-packages\googleapiclient\http.py", line 842, in execute\n raise HttpError(resp, content, uri=self.uri)\n', 'HttpError: https://www.googleapis.com/bigquery/v2/projects/projectId/queries?alt=json returned "Required parameter is missing">\n']
has answer: http://stackoverflow.com/a/50586845
downvote count: 0
answer count: 3
tagged with: google-cloud-platform
has answer: http://stackoverflow.com/a/50587707
score: 1
favorite count: 0
has title: Http Error: 400 Missing Required Parameter while using jobs.query() BQ API
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50587707
upvote count: 1
tagged with: google-bigquery

http://stackoverflow.com/comment/88401248
comment on: http://stackoverflow.com/a/50695459
type: AnswerComment
score: 0
type: Comment
has text: yes, that works. add the COMPLETE path and try it out - if it works, please accept my answer.

http://stackoverflow.com/comment/88384099
has text: @ImportanceOfBeingErnest Because of the two images I have, you cannot run my code or there is any other issue? I cannot fix the problem :( can you help me
comment on: http://stackoverflow.com/q/50648127
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50602670
has comment: http://stackoverflow.com/comment/88214488
tagged with: django
tagged with: python
score: 3
tagged with: django-views
upvote count: 3
linked to: http://stackoverflow.com/q/11041405
has title: What is different between `request.data['param-name'] ` or `request.data.get('param-name')` in Django
has body: I tried to get data from API 1 request.data['param-name'] output -:'9121009000' 2 request.data.get('param-name') output -:'9121009000' Both are giving the same result. So Which one is the best to use get data and Why. Thanks in advance
type: Question
has answer: http://stackoverflow.com/a/50602777
answer count: 2
downvote count: 0
tagged with: django-rest-framework
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50603074
type: UnansweredQuestion

ubuntu
tags question: http://stackoverflow.com/q/50577112
tags question: http://stackoverflow.com/q/50563984
tags question: http://stackoverflow.com/q/50556599
tags question: http://stackoverflow.com/q/50688288
tags question: http://stackoverflow.com/q/50645548
tags question: http://stackoverflow.com/q/50655774
tags question: http://stackoverflow.com/q/50553943
tags question: http://stackoverflow.com/q/50634189
tags question: http://stackoverflow.com/q/50688187
tags question: http://stackoverflow.com/q/50602281
tag name: ubuntu
tags question: http://stackoverflow.com/q/50542645
tags question: http://stackoverflow.com/q/50580846
tags question: http://stackoverflow.com/q/50676091
tags question: http://stackoverflow.com/q/50644283
type: Tag
tags question: http://stackoverflow.com/q/50549757
tags question: http://stackoverflow.com/q/50545515
tags question: http://stackoverflow.com/q/50581760

http://stackoverflow.com/q/50610838
duplicate of: http://stackoverflow.com/q/26337003
accepted answer: http://stackoverflow.com/a/50610902
has comment: http://stackoverflow.com/comment/88231610
duplicate of: http://stackoverflow.com/q/20002503
type: Question
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/88231658
has comment: http://stackoverflow.com/comment/88231614
answer count: 1
duplicate of: http://stackoverflow.com/q/15112125
has comment: http://stackoverflow.com/comment/88231683
has comment: http://stackoverflow.com/comment/88231607
tagged with: python-3.x
linked to: http://stackoverflow.com/q/18212574
has comment: http://stackoverflow.com/comment/88231631
tagged with: python
has answer: http://stackoverflow.com/a/50610902
has title: Instead of writing many ands how to short your code in pythonic way
has comment: http://stackoverflow.com/comment/88231884
has body: sv= 0.000324 if sv != 0.00002 and 0.00003 and 0.00004 and 0.00005 and 0.0002 and 0.0003 and 0.0004 and 0.0005 and 0.000003 and 0.04 and 0.000000090 and 0.000005 and 0.00003 and 0.000000090 and 0.0000003: print (sv) instead of writing many ands or ors is there is a way to make this code shorter or more pythonic way ?
has comment: http://stackoverflow.com/comment/88246296
type: AnsweredQuestion

http://stackoverflow.com/comment/88302368
has text: @GomesJ.A. I would not recommend thinking about such optimizations until they are actually needed. They may or may not be true anyways. There may be several levels of optimization running behind the scenes. It is way more important to design a clean code.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50645781

http://stackoverflow.com/q/50635844
score: 0
tagged with: concatenation
has body: This question could be a little tricky... I have a function that labels a dataframe based on some values in its columns. The function receives as parameter, a dataframe and a dictionary. This dictionary has key-value pairs that indicate the columns(key) and the value that it have to have to be labeled with certain number. For example: {"ip_src": "192.168.84.129", "ip_dst": "192.168.84.128", "label": 1} when the column "ip_src" of the dataframe have the value "192.168.84.129" and the column "ip_dst" have the value "192.168.84.128", that rows have to be labeled whit a '1'. The thing is that those conditions may vary, so I want to generalize the code, so I could pass several other conditions as: {"ip_src": "192.168.1.101", "dst_port": 19305, "label": 4} and so on. I started with: def labeling(df, crit): for dic in crit: lbl = dic["label"] del dic["label"] conds = [] pairs = len(dic) for key in dic: conds.append((df[key] == dic[key])) But I get stuck in the last line, because I can't figure how to concatenate the conditions and then apply them as: df[conds] = lbl Thanks! Edit: Input: index ip_src ip_dst ip_proto frame_time_delta \ 0 0 192.168.84.129 192.168.84.128 17.0 0.000000 1 1 31.13.94.53 192.168.1.101 17.0 0.006656 2 2 192.168.1.101 31.13.94.53 17.0 0.012948 payload_size src_port dst_port flow_dir 0 172.0 52165.0 40002.0 1 1 176.0 40002.0 52165.0 0 2 172.0 52165.0 19305.0 1 Output: ip_src ip_dst ip_proto frame_time_delta \ 0 192.168.84.129 192.168.84.128 17.0 0.000000 1 31.13.94.53 192.168.1.101 17.0 0.006656 2 192.168.1.101 31.13.94.53 17.0 0.012948 payload_size src_port dst_port flow_dir label 0 172.0 52165.0 35456.0 1 1 1 176.0 40002.0 52165.0 0 0 2 172.0 52165.0 19305.0 1 4 Possible cases: l_crit = [{"ip_src": "192.168.84.129", "ip_dst": "192.168.84.128", "label": 1}, {"ip_src": "192.168.1.100", "ip_dst": "192.168.1.105", "dst_port": 9999, "label": 1}, {"ip_src": "192.168.1.101", "ip_dst": "104.44.195.76", "label": 2}, {"ip_src": "192.168.1.101", "ip_dst": "31…
answer count: 1
accepted answer: http://stackoverflow.com/a/50636084
tagged with: pandas
tagged with: python
type: Question
type: AnsweredQuestion
tagged with: conditional-statements
has title: Concatenate conditions
has answer: http://stackoverflow.com/a/50636084

http://stackoverflow.com/a/50546981
upvote count: 7
score: 7
downvote count: 0
answers question: http://stackoverflow.com/q/50546892
has body: Not using a space isn't a typo, but leads to portability issues when executing the same file on different machines. The purpose of the shebang line (#!/usr....) is to indicate what interpreter is to be used when executing the code in the file. According to Wikipedia: The form of a shebang interpreter directive is as follows: #!interpreter [optional-arg] in which interpreter is an absolute path to an executable program. The optional argument is a string representing a single argument. The example you provided, #!/usr/bin/env python, actually indicates to the shell that the interpreter to be used when executing the file is the first python interpreter that exists in the user's path. The shebang line is written this way to ensure portability: Shebangs must specify absolute paths (or paths relative to current working directory) to system executables; this can cause problems on systems that have a non-standard file system layout. Even when systems have fairly standard paths, it is quite possible for variants of the same operating system to have different locations for the desired interpreter. Python, for example, might be in /usr/bin/python, /usr/local/bin/python, or even something like /home/username/bin/python if installed by an ordinary user. Because of this it is sometimes required to edit the shebang line after copying a script from one computer to another because the path that was coded into the script may not apply on a new machine, depending on the consistency in past convention of placement of the interpreter. For this reason and because POSIX does not standardize path names, POSIX does not standardize the feature. Often, the program /usr/bin/env can be used to circumvent this limitation by introducing a level of indirection. #! is followed by /usr/bin/env, followed by the desired command without full path, as in this example: #!/usr/bin/env sh
type: Answer

http://stackoverflow.com/comment/88161844
has text: @Kevin As a rule of thumb, yes this applies to all classification problems and BOVW. There are instances where it doesn't apply (for example, if you are using the model for something other than prediction and don't care about its ability to generalize), so its important to consider what you know about your data and what your goals are, but they are the exception rather than the rule.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50571662

http://stackoverflow.com/comment/88114460
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50551280
type: Comment
has text: @HRG also, there is problem - roles columns would be in the random order, cuz i'm using set for collecting them. you can sort roles collection in alphabetical order if you want or just hardcode roles list.

http://stackoverflow.com/q/50590861
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/88191382
has comment: http://stackoverflow.com/comment/88191254
has answer: http://stackoverflow.com/a/50590975
type: Question
has comment: http://stackoverflow.com/comment/88191451
has comment: http://stackoverflow.com/comment/88191240
has answer: http://stackoverflow.com/a/50590962
has answer: http://stackoverflow.com/a/50590980
has comment: http://stackoverflow.com/comment/88191490
downvote count: 0
has title: Returning the minimum value in a JSON array
has answer: http://stackoverflow.com/a/50590959
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88191504
answer count: 4
score: 3
has body: Good evening folks! I have been wracking my brain on this one for a good few hours now and could do with a little bit of a pointer in the right direction. I'm playing around with some API calls and trying to make a little project for myself. The JSON data is stored in Arrays, and as such to get the information I want (it is from a Transport API) I have been making the following x = apirequest x = x.json for i in range(0,4): print(x['routes'][i]['duration']) print(x['routes'][i]['departure_time']) print(x['routes'][i]['arrival_time']) This will return the following 06:58:00 23:39 06:37 05:08:00 05:14 10:22 03:41:00 05:30 09:11 03:47:00 06:24 10:11 What I am trying to do, is return only the shortest journeys - I could do it if it was a single layer JSON string but I am not too familliar with multi-level arrays. I can't return ['duration'] without utilising ['routes'] and route indicator (in this case 0 through 3 or 4). I can use an if statement to iterate through them easily enough, but there must be a way to accomplish it directly through the JSON that I am missing. I also thought about adding the results to a separate array and then filtering that - but there is a few other fields I want to grab from the data when I've cracked this part. What I am finding as I learn is that I tend to do things a long winded way, often finding out my 10-15 line solutions on codewars are actually aimed at being done in 2-3 lines. Example JSON data { "request_time": "2018-05-29T19:03:04+01:00", "source": "Traveline southeast journey planning API", "acknowledgements": "Traveline southeast", "routes": [{ "duration": "06:58:00", "route_parts": [{ "mode": "foot", "from_point_name": "Corunna Court, Wrexham", "to_point_name": "Wrexham General Rail Station", "destination": "", "line_name": "", "duration": "00:36:00", "departure_time": "23:39", "arrival_time": "00:15" }] }] } Hope you can help steer me in the right direction!
upvote count: 3

points
tag name: points
tags question: http://stackoverflow.com/q/50556341
type: Tag
tags question: http://stackoverflow.com/q/50692725

http://stackoverflow.com/comment/88190810
type: Comment
comment on: http://stackoverflow.com/q/50589989
type: QuestionComment
score: 0
has text: @GarrettMarschke Then post the code that defines the object, as that could pertain to the problem. Why bother including the body of a function when that body will crash upon execution? At the very least, you should have added a note in your original post that you included an abridged version of your view functions. Please consider reading [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve).

http://stackoverflow.com/a/50660397
has comment: http://stackoverflow.com/comment/88331117
answers question: http://stackoverflow.com/q/50658515
score: 0
has body: Instead of supplying code to ta.EMA, do the following: short_ema = ta.EMA(close.astype(float),timeperiod=10) Talib functions usually take numpy arrays of dtype float as inputs
type: Answer
has comment: http://stackoverflow.com/comment/88330972
has comment: http://stackoverflow.com/comment/88330995

http://stackoverflow.com/comment/88398295
comment on: http://stackoverflow.com/q/50694190
score: 0
type: Comment
type: QuestionComment
has text: I actually could not use telnet to read the packet. but the hex format looks more correct, in the sensor's documentation, to get a proper reading of the angle for example, they ask me the following: exchange the 2 bytes : 0x16 0x18 get 2 bytes integer: 0x618 then transform to decimal system:1560 then multiply by 0.01 to get angle

http://stackoverflow.com/a/75169470
has comment: http://stackoverflow.com/comment/137666048
has body: it helps for me. import pandas as pd df = pd.read_csv('example.csv', low_memory=False) df.to_parquet('output.parquet', engine="fastparquet")
answers question: http://stackoverflow.com/q/50604133
downvote count: 0
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/88312347
type: Comment
has text: Thanks a lot. And you are totally right. I just copied and pasted it into Ipython and wanted to see if it works as I want to tweak the arguments to make sure it works. And forgive my ignorance, as for the command line, is it the windows command line (cmd.exe?) Sorry for the silly question, but my online courses haven't touched any command line content yet.
comment on: http://stackoverflow.com/a/50648562
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88317335
type: Comment
comment on: http://stackoverflow.com/a/50633406
type: AnswerComment
has text: If ram is a problem you can use generators instead of lists `((a,b,c) for a in original_list for b in original_list for c in original_list if a*a+b*b==c*c)`
score: 0

http://stackoverflow.com/q/50572848
answer count: 1
has comment: http://stackoverflow.com/comment/88155285
tagged with: python
has answer: http://stackoverflow.com/a/50572912
score: 0
type: Question
has comment: http://stackoverflow.com/comment/88155341
type: AnsweredQuestion
has title: 2 methods but yet couldn't solve. python 2.7
has body: I have tried: First, I did a code like this elif a_options == 2: a_update=raw_input("select a word to update:") a_renew_word = raw_input("the new word") if a_update in empt_list: empt_list[a_update]=a_renew_word else: print "sorry" # print a_list[a_options-1] got an error: TypeError: list indices must be integers, not str Also tried: elif a_options == 2: a_update=raw_input("select a word to update:") a_renew_word = raw_input("the new word") if a_update in empt_list: empt_list.index(a_update)=a_renew_word else: print "sorry" Another Error SyntaxError: can't assign to function call here you go with the complete code, i tried to do with lists, cuz i thought it suits the best, but if there is any other method i will accept it. any idea, or find where is the prob i tried to search but i couldnt find any solution, here i am here to ask you. print "hello, welcome to" a_list=["1. Add a new word","2. Update and existing word","3. Detele and existing word","4. Display a words definition"] zero=0 empt_list=[] empt_list_meaning=[] def list_game(): for i in a_list: print i a_options=input("Please select one of these options: ") if a_options== 1: a_newword=raw_input("What word you want to add? ") empt_list.append(a_newword) a_newword_meaning=raw_input("add the meaning of the word") empt_list_meaning.append(a_newword_meaning) # print a_list[a_options-1] print empt_list,a_newword,"added correctly" elif a_options == 2: a_update=raw_input("select a word to update:") a_renew_word = raw_input("the new word") if a_update in empt_list: empt_list.index(a_update)=a_renew_word else: print "sorry" # print a_list[a_options-1] elif a_options == 3: a_del_word=raw_input("selct the word you want to delete") for i in empt_list: if a_del_word in empt_list: empt_list.remove(a_del_word) # print a_list [a_options-1] elif a_options == 4: for i in empt_list: print i print ("would you like to continue or exit?\n1.contine\n2.exit") now=input("&gt;&gt;&gt; ") if now==1: list_game() else: print "arrivederch…
accepted answer: http://stackoverflow.com/a/50572912
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/88155333

http://stackoverflow.com/comment/88160142
type: AnswerComment
comment on: http://stackoverflow.com/a/50575312
type: Comment
has text: What would I have to add on my Python's script then?
score: 0

http://stackoverflow.com/a/50627033
has body: Flask-Cache uses the RedisCache backend provided by Werkzeug, which serializes values using pickle.dumps. It also prepends a ! for help when deserializing. You should typically not mess with these values directly, and let Flask-Caching handle it. You can use pickletools.dis to safely examine the representation, then pickle.loads to deserialize it. Security note: pickle.loads can execute arbitrary code, so make sure you understand untrusted data first using pickletools.dis. &gt;&gt;&gt; data = b'!\x80\x03cflask.wrappers\nResponse\nq\x00)\x81q\x01}q\x02(X\x07\x00\x00\x00headersq\x03cwerkzeug.datastructures\nHeaders\nq\x04)\x81q\x05}q\x06X\x05\x00\x00\x00_listq\x07]q\x08X\x0c\x00\x00\x00Content-Typeq\tX\x10\x00\x00\x00application/jsonq\n\x86q\x0basbX\x0c\x00\x00\x00_status_codeq\x0cK\xc8X\x07\x00\x00\x00_statusq\rX\x06\x00\x00\x00200 OKq\x0eX\x12\x00\x00\x00direct_passthroughq\x0f\x89X\t\x00\x00\x00_on_closeq\x10]q\x11X\x08\x00\x00\x00responseq\x12Xn\x00\x00\x00[\n {\n "desc": "pronoun object", \n "tag": "CLO"\n }, \n {\n "desc": "pronoun", \n "tag": "CLS"\n }\n]q\x13X\x01\x00\x00\x00\nq\x14\x86q\x15ub.' &gt;&gt;&gt; value = value[1:] # strip leading ! &gt;&gt;&gt; import pickletools &gt;&gt;&gt; pickletools.dis(data) 0: \x80 PROTO 3 2: c GLOBAL 'flask.wrappers Response' 27: q BINPUT 0 29: ) EMPTY_TUPLE 30: \x81 NEWOBJ 31: q BINPUT 1 33: } EMPTY_DICT 34: q BINPUT 2 36: ( MARK 37: X BINUNICODE 'headers' 49: q BINPUT 3 51: c GLOBAL 'werkzeug.datastructures Headers' 84: q BINPUT 4 86: ) EMPTY_TUPLE 87: \x81 NEWOBJ 88: q BINPUT 5 90: } EMPTY_DICT 91: q BINPUT 6 93: X BINUNICODE '_list' 103: q BINPUT 7 105: ] EMPTY_LIST 106: q BINPUT 8 108: X BINUNICODE 'Content-Type' 125: q BINPUT 9 127: X BINUNICODE 'application/json' 148: q BINPUT 10 150: \x86 TUPLE2 151: q BINPUT 11 153: a APPEND 154: s SETITEM 155: b BUILD 156: X BINUNICODE '_status_code' 173: q BINPUT 12 175: K BININT1 200 177: X BINUNICODE '_status' 189: q BINPUT 13 191: X BINUNICODE '200 OK' 202: q BINPUT 14 204: X …
downvote count: 0
score: 3
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50624908
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50624908

http://stackoverflow.com/a/50692004
upvote count: 1
type: Answer
has body: For your input, following will be executed in sequence. if a &gt; 0 and b &gt; 0: # (a,b) = (1,1) a = a + 1 # a = 2 b = b - 1 # b = 0 if a &gt; 0 or b &lt; 0: b = b - 1 # -1
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50691681

http://stackoverflow.com/comment/88384673
score: 0
comment on: http://stackoverflow.com/a/50684085
type: Comment
has text: I haven't run into that problem before, but it sounds like it just can't handle that many ticks. Maybe reconsider the interval (use a much larger interval, that way there will be way fewer ticks)
type: AnswerComment

http://stackoverflow.com/a/50553534
has comment: http://stackoverflow.com/comment/88119577
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88119255
has body: You probably have the import file2 statement at the beginning of file1.py. If you would import file1, it would load the whole module, but since you import just a function - you miss the dependency. You can fix it by either import file1 or by adding import file2 statement at the beginning of function1 definition. E.g, # file1.py def function1(some_input): import file2 .. your code ..
has comment: http://stackoverflow.com/comment/88119702
type: Answer
answers question: http://stackoverflow.com/q/50553500
upvote count: 1

http://stackoverflow.com/q/50595727
downvote count: 1
has answer: http://stackoverflow.com/a/50619344
has comment: http://stackoverflow.com/comment/88202046
type: Question
has answer: http://stackoverflow.com/a/50595966
tagged with: opencv
score: 3
has comment: http://stackoverflow.com/comment/88206538
has comment: http://stackoverflow.com/comment/88219011
upvote count: 4
answer count: 3
has body: I am working on hair removal from skin lesion images. Is there any way to convert binary back to rgb? Original Image: Mask Image: I just want to restore the black area with the original image.
has answer: http://stackoverflow.com/a/70701801
has comment: http://stackoverflow.com/comment/88247665
accepted answer: http://stackoverflow.com/a/50619344
has title: How to convert a Binary Image to Grayscale and RGB using python?
favorite count: 0
has comment: http://stackoverflow.com/comment/88246922
tagged with: python
type: AnsweredQuestion
tagged with: image-processing
possible better answer: http://stackoverflow.com/a/50595966

http://stackoverflow.com/a/50634222
score: 3
answers question: http://stackoverflow.com/q/50634193
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50634193
upvote count: 3
type: Answer
has body: fix for future was def upload(self): s3 = boto3.client('s3') try: with open(self.flow_cells +'.zip', 'rb') as data: s3.upload_fileobj(data, self.output_s3_bucket, self.flow_cells +'.zip',ExtraArgs={'ServerSideEncryption': 'AES256'}) return True except botocore.exceptions.ClientError as error: print(error.response['Error']['Code'])

http://stackoverflow.com/comment/88286255
comment on: http://stackoverflow.com/q/50638104
has text: `mapping_dict = self.__dict__` **does not** create a new dictionary, so the next line is actually overwriting the instance attribute. Why don't you implement e.g. [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping) so you can use the object itself like a dictionary?
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/50661994
downvote count: 0
upvote count: 14
answer count: 3
has answer: http://stackoverflow.com/a/50662039
has answer: http://stackoverflow.com/a/50662070
has answer: http://stackoverflow.com/a/50662090
favorite count: 0
tagged with: beautifulsoup
tagged with: python
score: 14
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50662039
has body: I'm using BeautifulSoup to search for several elements in a web page. I'm saving the elements I find, but because there is a chance that my script will look for an element and it doesn't exist for the particular page it's parsing, I have try/except statements for every element: # go through a bunch of webpages for soup in soups: try: # look for HTML element data['val1'].append(soup.find('div', class_="something").text) except: # add NA if nothing found data['val1'].append("N/A") try: data['val2'].append(soup.find('span', class_="something else").text) except: data['val2'].append("N/A") # and more and more try/excepts for more elements of interest Is there a cleaner or better way to write something like this?
type: Question
has title: BeautifulSoup: Return None if HTML element not found
accepted answer: http://stackoverflow.com/a/50662070

http://stackoverflow.com/a/50697498
accepted answer of: http://stackoverflow.com/q/50697410
answers question: http://stackoverflow.com/q/50697410
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88404891
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/88405018
score: 2
has body: You need to set a backupCount value, or change the file mode from appending to truncating on open. The log file is closed, but then re-opened again for appending, so you never actually see a difference. What happens now is: The handler tests if the current file length plus the message pushes the file length over the maximum. If the length is over the maximum, close the file If backupCount is greater than zero, rotate any existing backup files, and then rename the log file to add .1 Open the logfile for appending. If there already is a file there with the same name, then that file is re-opened. Write the message to the open log file. Apart from setting backupCount to a number higher than 0, you could also change the mode parameter to 'w', at which point you'll find that the file is truncated each time it would get too large: # 'rotate' logfile by truncating: logFile = RotatingFileHandler(logfilename, mode='w', maxBytes=1024) Note that the file can still become larger than maxBytes, if the new message itself is greater than 1024 bytes long. There is no option to retain all rotated files. You'd indeed have to use an insanely high number, or use a different file rotation strategy. For example, the TimedRotatingFileHandler rotates files after a given interval, and if you leave backupCount at zero, it'll never delete rotated backups. You could also subclass RotatingFileHandler() to implement your own renaming strategy, providing your own doRollover() method. You need to generate unique names if you want to retain all backups; you could add a UUID to ensure this (together with the date): import uuid from datetime import datetime from logging import RotatingFileHandler class InfiniteRotatingFileHandler(RotatingFileHandler): def doRollover(self): if self.stream: self.stream.close() self.stream = None new_name = '{}.{:%Y%m%d%H%M%S}.{}'.format( self.baseFilename, datetime.now(), uuid.uuid4()) self.rotate(self.baseFilename, new_name) if not self.delay: self.stream = self._open(…

http://stackoverflow.com/comment/88169004
comment on: http://stackoverflow.com/q/50579671
type: QuestionComment
type: Comment
has text: You want a `defaultdict`.
score: 0

http://stackoverflow.com/q/50662896
tagged with: seq2seq
tagged with: deep-learning
has title: Tensorflow seq2seq chatbot always give the same outputs
downvote count: 0
type: Question
type: AnsweredQuestion
score: 3
has body: I'm trying to make a seq2seq chatbot with Tensorflow, but it seems to converge to the same outputs despite different inputs. The model gives different outputs when first initialized, but quickly converges to the same outputs after a few epochs. This is still an issue even after a lot of epochs and low costs. However, the models seems to do fine when trained with smaller datasets (say 20) but it fails with larger ones. I'm training on the Cornell Movie Dialogs Corpus with a 100-dimensional and 50000-vocab glove pretrained embedding. The encoder seems to have very close final states (in the ranges of around 0.01) when given totally different inputs. I've tried using a simple LSTM/GRU, bidirectional LSTM/GRU, multi-layer/stacked LSTM/GRU, and multi-layer bidirection LSTM/GRU. The rnn nodes have been tested with from 16 to 2048 hidden units. The only difference is that the model tends to output only the start and end tokens (GO and EOS) when having lesser hidden units. For multi-layer GRU, here's my code: cell_encode_0 = tf.contrib.rnn.GRUCell(self.n_hidden) cell_encode_1 = tf.contrib.rnn.GRUCell(self.n_hidden) cell_encode_2 = tf.contrib.rnn.GRUCell(self.n_hidden) self.cell_encode = tf.contrib.rnn.MultiRNNCell([cell_encode_0, cell_encode_1, cell_encode_2]) # identical decoder ... embedded_x = tf.nn.embedding_lookup(self.word_embedding, self.x) embedded_y = tf.nn.embedding_lookup(self.word_embedding, self.y) _, self.encoder_state = tf.nn.dynamic_rnn( self.cell_encode, inputs=embedded_x, dtype=tf.float32, sequence_length=self.x_length ) # decoder for training helper = tf.contrib.seq2seq.TrainingHelper( inputs=embedded_y, sequence_length=self.y_length ) decoder = tf.contrib.seq2seq.BasicDecoder( self.cell_decode, helper, self.encoder_state, output_layer=self.projection_layer ) outputs, _, _ = tf.contrib.seq2seq.dynamic_decode(decoder, maximum_iterations=self.max_sequence, swap_memory=True) return outputs.rnn_output ... # Optimization dynamic_max_sequence = tf.reduce_max(se…
tagged with: python
has answer: http://stackoverflow.com/a/52616035
favorite count: 0
tagged with: machine-learning
answer count: 1
tagged with: tensorflow
upvote count: 3
accepted answer: http://stackoverflow.com/a/52616035

http://stackoverflow.com/comment/88329232
score: 1
has text: Why are you using a while loop to read a file? What is `menu`? Why do you set `i = 0` if the next command overwrites it? Why are you expecting `len` to give you an iterable? It would help you to make a [MCVE].
type: QuestionComment
comment on: http://stackoverflow.com/q/50659383
type: Comment

http://stackoverflow.com/a/57844130
answers question: http://stackoverflow.com/q/50674419
type: Answer
score: 0
has body: In the URL you should give http://127.0.0.1:8000/polls/1/ and the o/p visible is "You are looking at question 1." or http://127.0.0.1:8000/polls/34/ and the o/p visible is "You are looking at question 34."

http://stackoverflow.com/comment/88189615
has text: thank you for your response. May i ask you about quantifiers in Lambda calculus for example i have "who is the inventor of facebook "this should be ∃x <facebook,inventor,x> how can i achieve such a representation with python and lambda-calculus ?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50586362

http://stackoverflow.com/comment/88263124
type: QuestionComment
has text: @BryanOakley the implementation using `mainloop` is something I did only to test. Instead of looping over `update_idletasks` and `update` I called `mainloop`. The problem was that I didn't find a viable way to end the loop when the process ends (I had to do it manually) and only did it to see if it made a difference. As for calling `update_idletasks`, I don't see any significant difference whether I remove it or not. Thanks.
comment on: http://stackoverflow.com/q/50616685
score: 0
type: Comment

http://stackoverflow.com/q/50669993
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88350480
downvote count: 1
type: Question
has body: This might not make sense but I have a file which consists of (in each line) Song name, length of the song, artist, album, and genre. So, I try to split them by spaces, and of course that splits song titles, so I just use the first whatevers of the list depending on another calculation. My example will be: Hells Bells 5:13 AC/DC Back In Black Rock 0 6 Shoot to Thrill 5:18 AC/DC Back In Black Rock 0 6 Back in Black 4:16 AC/DC Back in Black Rock 0 6 So I have a for loop that counts the length of the list of those things split and it gives me what I want. for line in f: Thing = line.replace(' ', ',').replace('\t', ',') a = Thing.split(',') integar = len(a)-11 #This subtract 11 is to get just the song which doesn't work situationally because if the album has more than 3 words unlike in this situation, then it wouldn't give the right amount integar = integar+1 for i in range(integar): print(a[i+1]) namelist.append(a[i]) name = str(namelist) namelist=[] I'm curious as to how I would get just the title out of it. I guess its possible to iterate through the list and find the length until it finds a number, but I'm not sure how I would do that, or if there is a better solution.
has comment: http://stackoverflow.com/comment/88350594
has comment: http://stackoverflow.com/comment/88349816
has comment: http://stackoverflow.com/comment/88350290
has comment: http://stackoverflow.com/comment/88350469
has title: How would I split these song details details properly
has comment: http://stackoverflow.com/comment/88350418
score: -1
has answer: http://stackoverflow.com/a/50671568
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88349841
has comment: http://stackoverflow.com/comment/88350514
has comment: http://stackoverflow.com/comment/88350384

http://stackoverflow.com/q/50669307
has body: I'm trying to determine when a website updates. I've done this by creating two variables and requesting the same site data in each. Then comparing them in a while loop, updating one variable in each iteration of the loop (see code below). The website HTML actually changes every minute, as the time changes on the site. So you would expect the loop to end every minute. Unfortunately, the site seems to send the same original data for each additional request and therefore the while loop does not exit. In order to reproduce the problem, run the code below a couple of times and then inspect the time in the HTML (origsite[4050:4114]) to see if it's the current time or the time from when you first ran the block of code. import time import random import sys import requests site = requests.get("http://www.supremenewyork.com/shop/all/").text origsite = requests.get("http://www.supremenewyork.com/shop/all/").text n = 1 while (origsite == site): x = round(random.uniform(0.8,1.2),3) time.sleep(x) origsite = requests.get("http://www.supremenewyork.com/shop/all/").text print(n) n = n + 1 print("site changed") Is this a known issue with requests? Or is the website sending old information on purpose? I have tried using a VPN to change my IP and it still returns old data. Is there another way to test if a site has changed? Below is an example of it using old data. origsite is storing data from 5min before site data is run. origsite[4050:4114] Out[94]: b'ime data-timezone-offset="3600">04/06/2018 03:11am <span ' site[4050:4114] Out[95]: b'04/06/2018 03:16am LDN</'
score: 0
has comment: http://stackoverflow.com/comment/88359990
tagged with: selenium
tagged with: python-requests
has comment: http://stackoverflow.com/comment/88351717
has comment: http://stackoverflow.com/comment/88349592
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88349481
has answer: http://stackoverflow.com/a/50898461
has title: Running Python requests consecutively returns old website data
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/88419243
has comment: http://stackoverflow.com/comment/88350892
type: Question
has comment: http://stackoverflow.com/comment/88364471
tagged with: python

http://stackoverflow.com/q/50590014
type: Question
has body: This code has been working fine for me: a = '31' b = '' c = '' d = '' codes = [a, b, c, d] set_one = ('07', '10', '17', '31') set_two = ('01','02','03','04','05','06','08') if any(s in test for test in codes for s in set_one): result = '"ONE"' elif any(s in test for test in codes for s in set_two): result = '"TWO"' else: result = 'NULL' print(result) In this example, result would print back "ONE" If either a, b, c, or d is set to 01, then result would print back "TWO", etc etc. This solution worked for a while as there was only ever one group of codes that could be represented in the equation, but I now need to account for both ONE and TWO being represented, (e.g. A = 07, B = 01). If this were to happen, the "07" would be picked up by the first if any statement, and would report out "ONE". I need to build in the functionality so that if in the entire codes object, both groups are represented, (e.g. codes = ['07','01','','']), then it reports back "THREE". I'm not sure how to do that though as python is not my forte... edit This works. Thank you guys! a = '01' b = '' c = '' d = '' codes = [a, b, c, d] one_match = 0 two_match = 0 set_one = ('07', '10', '17', '31', 'CO', '12', '13', '25', '55', 'ZN', 'Z3', 'Z2') set_two = ('01','02','03','04','05','06','08','11','14','15','16','18','19','20') if any(s in test for test in codes for s in set_one): one_match = 1 if any(s in test for test in codes for s in set_two): two_match = 1 if one_match == 1 and two_match == 1: result = "MIX" elif one_match == 1: result = "ONE ONLY" elif two_match == 1: result = "TWO ONLY" else: result = 'NULL' print(result)
has title: Matching to multiple items in a python data set
answer count: 2
has comment: http://stackoverflow.com/comment/88189468
has answer: http://stackoverflow.com/a/50590064
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88189499
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50590064
score: 1
possible better answer: http://stackoverflow.com/a/50590220
upvote count: 1
has answer: http://stackoverflow.com/a/50590220

http://stackoverflow.com/comment/88403531
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50696949
score: 0
has text: The closes I could get was ignoring the similarity calculation for those attributes, which is not close at all. I have edited my question to include my approach

http://stackoverflow.com/q/50688288
has comment: http://stackoverflow.com/comment/88386929
has comment: http://stackoverflow.com/comment/88386784
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/88388106
score: 0
answer count: 1
has title: Create a subprocess in a new shell that can be killed at any point
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88386329
has comment: http://stackoverflow.com/comment/88386692
type: UnansweredQuestion
tagged with: python
tagged with: unix
has comment: http://stackoverflow.com/comment/88386456
tagged with: subprocess
has comment: http://stackoverflow.com/comment/88386358
has comment: http://stackoverflow.com/comment/88386859
has answer: http://stackoverflow.com/a/50688342
has comment: http://stackoverflow.com/comment/88386511
has body: I want to run a terminal command in a separate shell, but I also want to be able to kill/terminate it at any time. I've read some answers here, and they say to do something like process = subprocess.Popen(args=['gnome-terminal', '--command=%s' % cmd]). The problem with this is, calling process.kill() or process.terminate() after the new shell has been opened does nothing. I want to be able to call a function and kill or terminate the new shell process.
type: Question

http://stackoverflow.com/a/50662520
answers question: http://stackoverflow.com/q/50662469
has body: Once you groupby and select a column, your dog column doesn't exist anymore in the context you have selected (and even if it did you are not accessing it correctly). Filter your dataframe first, then use groupby with mean df[df.dog].groupby('breed')['rating'].mean().reset_index() breed rating 0 Chihuahua 8.5 1 Dalmatian 10.0
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50662469
type: Answer
upvote count: 7
score: 7

http://stackoverflow.com/q/50640883
type: Question
score: 0
has title: function is not able to properly write output data file - Python
has comment: http://stackoverflow.com/comment/88292100
answer count: 1
has answer: http://stackoverflow.com/a/50641082
tagged with: flush
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88291899
has body: Scenario: I have two files, file1 size = 19.7MB and file2 size = 446KB. I am running the following code to process the data from both files and get an output data file. But after a certain output file size (332KB) the program stops writing data to the output file. I tried using flush() function but again the output file contains the exact same size as output file without using flush() function (and took exact same time to write these data in both conditions (file created and last modifed)) while loop is still running. Please someone suggest the potential reason(s)? Should I use sleep() function to wake up the program after a certain time? Thanks with open("file2",'rU') as gg: for g in gg: g = g.rstrip().split('\t') with open(file1) as cc: c = c.rstrip().split('\t') if int(c[0]) == int(g[0]) and int(c[1]) &gt;= int(g[2]) and int(g[3]) &gt;= int(c[1]): with open('output.txt', 'a') as ii: ii.write(c[1]+'\t'+'\t'.join(g)+'\n') ii.flush()
has comment: http://stackoverflow.com/comment/88291863

http://stackoverflow.com/comment/88388764
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50689272
has text: Although not relevant here, you do not have to add an `id = AutoField()` yourself, if no primary key is mentioned, Django generates one automatically.

http://stackoverflow.com/q/50670392
score: 1
has comment: http://stackoverflow.com/comment/88357489
type: Question
has body: Example of my current server side code (This will stay in the terminal) import socket import threading port = 7064 server = "0.0.0.0" server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind((server, port)) server_socket.listen(5) def client_thread_code(addr, client_sock): client_sock.send("Ping".encode("utf8")) try: while True: # Accepts and sorts user connections to server. (client_sock, addr) = server_socket.accept() print("Connection from: " + str(addr)) # Spawns client thread # socket is blocking so offload to thread. client_thread = threading.Thread(target=client_thread_code, args=(addr, client_sock,)).start() except Exception as exception: print("Critical Error Server halted " + str(exception)) The client would be a complicated version of this: import socket server = "localhost" port = 7064 client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect((server, port)) print(client_socket.recv(1024).decode("utf8")) Is there any way to move the client functionality to a website so a client could access it through a browser.
duplicate of: http://stackoverflow.com/q/12407778
has title: How would I have a web based application commincate with a python server with sockets
linked to: http://stackoverflow.com/q/25741177
downvote count: 0
has comment: http://stackoverflow.com/comment/88351332
linked to: http://stackoverflow.com/q/27571414
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/12407778
answer count: 0
type: UnansweredQuestion
tagged with: sockets
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88350685

http://stackoverflow.com/a/50601209
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50600531
upvote count: 24
has body: This would do the magic: from django.db.models import DurationField, F, ExpressionWrapper import datetime Race.objects.annotate( diff=ExpressionWrapper(F('end') - F('start'), output_field=DurationField()) ).filter(diff__gte=datetime.timedelta(5)) This will return all Race instances whose duration is greater than or equal to 5 References: ExpressionWrapper SO Post - How should I use DurationField in my model?-
has comment: http://stackoverflow.com/comment/88212132
score: 24
answers question: http://stackoverflow.com/q/50600531
type: AcceptedAnswer

http://stackoverflow.com/comment/88634284
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50620908
has text: I'm not using Apache or Nginx anymore.
type: AnswerComment

http://stackoverflow.com/a/50563479
has comment: http://stackoverflow.com/comment/88137559
has comment: http://stackoverflow.com/comment/88137310
has comment: http://stackoverflow.com/comment/88137847
has body: Try with groupby, from itertools import groupby from operator import itemgetter grouper = itemgetter("cycle", "zone") dict_one,dict_two = (list(g) for _,g in groupby(d,key=grouper)) The code will return a tuple now we have only 2 elements. So the value assignment will work here. If you have more values you can assign these values to a dict or store as iterable. Output In [9]: dict_one Out[9]: [{'count': '100', 'cycle': '15', 'zone': 'PIMPRI'}, {'count': '50', 'cycle': '15', 'zone': 'PIMPRI'}] In [10]: dict_two Out[10]: [{'count': '150', 'cycle': '30', 'zone': 'PIMPRI'}]
has comment: http://stackoverflow.com/comment/88137503
has comment: http://stackoverflow.com/comment/88137768
has comment: http://stackoverflow.com/comment/88137245
answers question: http://stackoverflow.com/q/50563293
has comment: http://stackoverflow.com/comment/88137565
type: Answer
has comment: http://stackoverflow.com/comment/88137680
score: 0

http://stackoverflow.com/a/50759287
answers question: http://stackoverflow.com/q/50625320
type: Answer
score: 2
upvote count: 2
has body: Here what I use to download a file from Google Drive to Google Colab file system, substitute fileId value with your Drive file id. !pip install -U -q PyDrive from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth) fileId = '1234567890dcz4qL-JQtYqX9ZXUt7JXe' fileName = fileId downloaded = drive.CreateFile({'id': fileId}) downloaded.GetContentFile(fileName) To get Drive file id look at this answer.
downvote count: 0

http://stackoverflow.com/a/57693010
type: Answer
has body: @Shariq You could also use the cx_Oracle driver: from sqlalchemy.engine import create_engine DIALECT = 'oracle' SQL_DRIVER = 'cx_oracle' USERNAME = 'your_username' #enter your username PASSWORD = 'your_password' #enter your password HOST = 'subdomain.domain.tld' #enter the oracle db host url PORT = 1521 # enter the oracle port number SERVICE = 'your_oracle_service_name' # enter the oracle db service name ENGINE_PATH_WIN_AUTH = DIALECT + '+' + SQL_DRIVER + '://' + USERNAME + ':' + PASSWORD +'@' + HOST + ':' + str(PORT) + '/?service_name=' + SERVICE engine = create_engine(ENGINE_PATH_WIN_AUTH) #test query import pandas as pd test_df = pd.read_sql_query('SELECT * FROM global_name', engine)
answers question: http://stackoverflow.com/q/50680685
score: 0

http://stackoverflow.com/comment/88329701
comment on: http://stackoverflow.com/q/50649919
type: Comment
score: 1
has text: Yes. The Issue is only occurring when i want to run a function at a specific time of the day.
type: QuestionComment

logging
tags question: http://stackoverflow.com/q/50567564
tag name: logging
tags question: http://stackoverflow.com/q/50619722
tags question: http://stackoverflow.com/q/50591198
tags question: http://stackoverflow.com/q/50604860
tags question: http://stackoverflow.com/q/50614664
tags question: http://stackoverflow.com/q/50651797
tags question: http://stackoverflow.com/q/50677656
tags question: http://stackoverflow.com/q/50635038
tags question: http://stackoverflow.com/q/50614109
tags question: http://stackoverflow.com/q/50620900
tags question: http://stackoverflow.com/q/50615078
tags question: http://stackoverflow.com/q/50697410
tags question: http://stackoverflow.com/q/50556584
tags question: http://stackoverflow.com/q/50615566
type: Tag
tags question: http://stackoverflow.com/q/50570755

python-requests
tags question: http://stackoverflow.com/q/50612940
tags question: http://stackoverflow.com/q/50568534
type: Tag
tags question: http://stackoverflow.com/q/50669307
tags question: http://stackoverflow.com/q/50563689
tags question: http://stackoverflow.com/q/50599818
tags question: http://stackoverflow.com/q/50668927
tags question: http://stackoverflow.com/q/50628120
tags question: http://stackoverflow.com/q/50649401
tags question: http://stackoverflow.com/q/50688323
tags question: http://stackoverflow.com/q/50651624
tags question: http://stackoverflow.com/q/50696576
tags question: http://stackoverflow.com/q/50632089
tags question: http://stackoverflow.com/q/50546871
tags question: http://stackoverflow.com/q/50648324
tags question: http://stackoverflow.com/q/50580053
tags question: http://stackoverflow.com/q/50592504
tags question: http://stackoverflow.com/q/50623935
tags question: http://stackoverflow.com/q/50656455
tags question: http://stackoverflow.com/q/50660567
tags question: http://stackoverflow.com/q/50628805
tags question: http://stackoverflow.com/q/50592182
tags question: http://stackoverflow.com/q/50608944
tags question: http://stackoverflow.com/q/50661184
tags question: http://stackoverflow.com/q/50589439
tags question: http://stackoverflow.com/q/50594392
tags question: http://stackoverflow.com/q/50597721
tags question: http://stackoverflow.com/q/50580619
tags question: http://stackoverflow.com/q/50660215
tags question: http://stackoverflow.com/q/50663890
tags question: http://stackoverflow.com/q/50542102
tags question: http://stackoverflow.com/q/50664558
tags question: http://stackoverflow.com/q/50665082
tags question: http://stackoverflow.com/q/50638138
tags question: http://stackoverflow.com/q/50578810
tag name: python-requests
tags question: http://stackoverflow.com/q/50654380
tags question: http://stackoverflow.com/q/50618945
tags question: http://stackoverflow.com/q/50650983
tags question: http://stackoverflow.com/q/50591307

http://stackoverflow.com/comment/88289906
has text: Great solution! Thank you.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50638625
score: 0

http://stackoverflow.com/comment/118195261
type: AnswerComment
comment on: http://stackoverflow.com/a/50572526
type: Comment
has text: You can `extractall()` to extract all the contents of a zip file or you can get the `namelist()` and iterate through the names.
score: 0

http://stackoverflow.com/a/50627136
type: AcceptedAnswer
has body: this should be sufficient if x is None
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/50627029
score: 2
accepted answer of: http://stackoverflow.com/q/50627029
downvote count: 0

machine-learning
tags question: http://stackoverflow.com/q/50606448
tags question: http://stackoverflow.com/q/50659994
tags question: http://stackoverflow.com/q/50598225
tags question: http://stackoverflow.com/q/50543692
tags question: http://stackoverflow.com/q/50682119
tags question: http://stackoverflow.com/q/50551428
tags question: http://stackoverflow.com/q/50583772
tags question: http://stackoverflow.com/q/50642763
tags question: http://stackoverflow.com/q/50641866
tags question: http://stackoverflow.com/q/50588274
tags question: http://stackoverflow.com/q/50642358
tags question: http://stackoverflow.com/q/50542636
tags question: http://stackoverflow.com/q/50618266
tags question: http://stackoverflow.com/q/50626539
tags question: http://stackoverflow.com/q/50664424
tags question: http://stackoverflow.com/q/50612899
tags question: http://stackoverflow.com/q/50569782
tags question: http://stackoverflow.com/q/50639614
tags question: http://stackoverflow.com/q/50565937
tags question: http://stackoverflow.com/q/50690865
tags question: http://stackoverflow.com/q/50671251
tags question: http://stackoverflow.com/q/50697550
tags question: http://stackoverflow.com/q/50544917
tags question: http://stackoverflow.com/q/50672019
tags question: http://stackoverflow.com/q/50626288
tags question: http://stackoverflow.com/q/50644567
tags question: http://stackoverflow.com/q/50598405
tags question: http://stackoverflow.com/q/50697716
tags question: http://stackoverflow.com/q/50686123
tags question: http://stackoverflow.com/q/50685576
tags question: http://stackoverflow.com/q/50559152
tags question: http://stackoverflow.com/q/50555298
tags question: http://stackoverflow.com/q/50569288
tags question: http://stackoverflow.com/q/50671283
tags question: http://stackoverflow.com/q/50667735
tags question: http://stackoverflow.com/q/50558559
tags question: http://stackoverflow.com/q/50628586
tags question: http://stackoverflow.com/q/50636819
tags question: http://stackoverflow.com/q/50546170
tags question: http://stackoverflow.com/q/50630657
tags question: http://stackoverflow.com/q/50685155
tags question: http://stackoverflow.com/q/50558546
tags question: http://stackoverflow.com/q/50669873
tags question: http://stackoverflow.com/q/50615156
tags question: http://stackoverflow.com/q/50630849
tags question: http://stackoverflow.com/q/50545411
tags question: http://stackoverflow.com/q/50571493
tags question: http://stackoverflow.com/q/50664480
tags question: http://stackoverflow.com/q/50661075
tag name: machine-learning
tags question: http://stackoverflow.com/q/50672979
tags question: http://stackoverflow.com/q/50581985
tags question: http://stackoverflow.com/q/50631147
tags question: http://stackoverflow.com/q/50613294
tags question: http://stackoverflow.com/q/50605692
tags question: http://stackoverflow.com/q/50647248
tags question: http://stackoverflow.com/q/50587834
tags question: http://stackoverflow.com/q/50658725
tags question: http://stackoverflow.com/q/50559570
tags question: http://stackoverflow.com/q/50687651
tags question: http://stackoverflow.com/q/50575118
tags question: http://stackoverflow.com/q/50616680
tags question: http://stackoverflow.com/q/50617442
type: Tag
tags question: http://stackoverflow.com/q/50686217
tags question: http://stackoverflow.com/q/50676717
tags question: http://stackoverflow.com/q/50589333
tags question: http://stackoverflow.com/q/50688189
tags question: http://stackoverflow.com/q/50650066
tags question: http://stackoverflow.com/q/50545339
tags question: http://stackoverflow.com/q/50583563
tags question: http://stackoverflow.com/q/50600661
tags question: http://stackoverflow.com/q/50628376
tags question: http://stackoverflow.com/q/50552142
tags question: http://stackoverflow.com/q/50547953
tags question: http://stackoverflow.com/q/50661990
tags question: http://stackoverflow.com/q/50661907
tags question: http://stackoverflow.com/q/50634095
tags question: http://stackoverflow.com/q/50666091
tags question: http://stackoverflow.com/q/50659796

pipeline
type: Tag
tags question: http://stackoverflow.com/q/50671008
tag name: pipeline

http://stackoverflow.com/q/50546852
has title: Python Open Error for Absolute Filepath from Command Prompt in Windows 10
tagged with: windows-10
has comment: http://stackoverflow.com/comment/88105072
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88104633
has comment: http://stackoverflow.com/comment/88104513
has comment: http://stackoverflow.com/comment/88104468
tagged with: python
has body: I have the Anaconda3 distribution for Python 3.6 on Windows 10. I am making the following call from the command window to a script that will create and write to a text file: C:\WINDOWS\system32&gt;python C:\Users\shawn\Documents\Google_Maps_Drive_Times\Commute_Times.py And get the following error: Traceback (most recent call last): File "C:\Users\shawn\Documents\Google_Maps_Drive_Times\Commute_Times.py", line 97, in &lt;module&gt; with open(ff, 'w') as f: FileNotFoundError: [Errno 2] No such file or directory: 'C:\\WINDOWS\\system32\\Daily_Trip_Times\\Commute_Times_05-26-18_1558.txt' The strange part is that the code runs perfectly fine when I run it using the Spyder IDE. Even more strange is that the code works from the command prompt if I add ff = ff.replace('\\','\') However, that then breaks the functionality in Spyder, as I would expect. I also tried using backslashes, but get the same error as with "\\". Note that I have made some simple scripts to verify that Python is working and where python provides C:\ProgramData\Anaconda3\python.exe as I would expect. Any help in understanding the path directory nuances between Spyder and the command prompt would be greatly appreciated.
tagged with: command-prompt
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/88105284
has comment: http://stackoverflow.com/comment/88104953
score: 0
tagged with: spyder

http://stackoverflow.com/comment/88362413
has text: Actually it returns `bool` if all groups are of size one. If one of the groups is lager you'll get `float`.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50676278

http://stackoverflow.com/q/50689217
tagged with: python-3.x
type: Question
upvote count: 2
possible better answer: http://stackoverflow.com/a/50689262
answer count: 2
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/50689272
has body: I am coming from .NET Core and I am curious if Django has anything similar to .NET Core's projections. For instance, I can describe a relationship in a .NET Core model and then later query for it. So, if Articles can have an Author I can do something like: var articles = dbContext.Where(article.ID == id).Inclue(a =&gt; a.author); What I would get back are articles that have their author attached. Is there anything similar to this in Django? How can I load related data in Django that's described in the model?
has title: Django get foreign key objects
tagged with: django-models
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50689262
downvote count: 0
has answer: http://stackoverflow.com/a/50689272
favorite count: 0

http://stackoverflow.com/comment/88352892
type: Comment
score: 0
type: AnswerComment
has text: I saw the question as, and I think it would be a more valuable question to ask: "Do .pyc files contain type hinting information?". The specific example is syntactically incorrect and in my eyes an error in asking the question, not part of the question itself. It would be silly to ask if an incorrect program stores information in the bytecode, as it would never reach that stage.
comment on: http://stackoverflow.com/a/50631635

http://stackoverflow.com/comment/88368888
comment on: http://stackoverflow.com/q/50669030
score: 0
type: Comment
type: QuestionComment
has text: For Raspberry Pi, [SPI0](https://pinout.xyz/pinout/spi) supports two channels with two CS pins, with CE0 on pin 24, and CE1 on pin 26.

http://stackoverflow.com/a/50609520
has body: First off, you probably don't need map_async if you are going to immediately wait on it. If that is the case, then just use map. You can potentially also remove your queue and just return the values. But that's probably not the problem you are having. The problem is likely that the wait method doesn't raise remote exceptions. It is likely that your process_file method is actually failing in the pool processes but that you aren't seeing those exceptions. Like Blckknght mentioned, you should switch to using a get method which, as you can see here, will raise the remote exception. Here is a simple example where the wait method hides the remote process exceptions and how if you switch to get you can see them again: import multiprocessing as mp def just_dies(n): raise ValueError("Test") if __name__ == "__main__": pool = mp.Pool(4) results = pool.map_async(just_dies, range(10)) # the wait will immediately silently pass #results.wait() # this will actually raise the remote exception results.get() If you run this you will get a traceback error message like so The above exception was the direct cause of the following exception: Traceback (most recent call last): File "foo.py", line 14, in &lt;module&gt; results.get() File "XXX/python3.5/multiprocessing/pool.py", line 608, in get raise self._value ValueError: Test If you switch to using the wait method then you won't see it.
type: Answer
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50572875
upvote count: 3
answers question: http://stackoverflow.com/q/50572875
type: AcceptedAnswer

rfid
tag name: rfid
tags question: http://stackoverflow.com/q/50646571
tags question: http://stackoverflow.com/q/50669030
tags question: http://stackoverflow.com/q/50645215
type: Tag

http://stackoverflow.com/a/50646530
answers question: http://stackoverflow.com/q/50645806
upvote count: 1
has comment: http://stackoverflow.com/comment/88307798
has comment: http://stackoverflow.com/comment/88307807
score: 1
type: AcceptedAnswer
downvote count: 0
has body: You need: import matplotlib.pyplot as plt a_x_axis = [32, 30, 40, 50, 60, 78] a_live = [1, 3, 2, 1, 2, 4] a_alive_for = [a + b for a, b in zip(a_x_axis, a_live)] b_x_axis = [22, 25, 45, 55, 60, 72] b_live = [1, 3, 2, 1, 2, 4] b_alive_for = [a + b for a, b in zip(b_x_axis, b_live)] a_y_axis = [] b_y_axis = [] for i in range(0, len(a_x_axis)): a_y_axis.append('process-1') b_y_axis.append('process-2') print("size of a: %s" % len(a_x_axis)) print("size of a: %s" % len(a_y_axis)) plt.xlabel('time (s)') plt.scatter(a_x_axis, [1]*len(a_x_axis)) plt.scatter(a_alive_for, [1]*len(a_x_axis)) plt.scatter(b_x_axis, [2]*len(b_x_axis)) plt.scatter(b_alive_for, [2]*len(b_x_axis)) for i in range(0, len(a_x_axis)): plt.plot([a_x_axis[i],a_alive_for[i]], [1,1], 'green') for i in range(0, len(b_x_axis)): plt.plot([b_x_axis[i],b_alive_for[i]], [2,2], 'green') plt.show() Output:
type: Answer
accepted answer of: http://stackoverflow.com/q/50645806

web-scraping
tags question: http://stackoverflow.com/q/50613071
tags question: http://stackoverflow.com/q/50673895
tags question: http://stackoverflow.com/q/50668209
tags question: http://stackoverflow.com/q/50676990
tags question: http://stackoverflow.com/q/50692065
tags question: http://stackoverflow.com/q/50683637
tags question: http://stackoverflow.com/q/50689857
tags question: http://stackoverflow.com/q/50609199
tags question: http://stackoverflow.com/q/50689422
tags question: http://stackoverflow.com/q/50560526
tags question: http://stackoverflow.com/q/50589151
tags question: http://stackoverflow.com/q/50547975
tags question: http://stackoverflow.com/q/50597923
tags question: http://stackoverflow.com/q/50659431
tags question: http://stackoverflow.com/q/50666816
tags question: http://stackoverflow.com/q/50604186
tags question: http://stackoverflow.com/q/50628120
tags question: http://stackoverflow.com/q/50557840
tags question: http://stackoverflow.com/q/50556793
tags question: http://stackoverflow.com/q/50543282
tags question: http://stackoverflow.com/q/50668575
tags question: http://stackoverflow.com/q/50678858
tags question: http://stackoverflow.com/q/50661642
tags question: http://stackoverflow.com/q/50548373
tags question: http://stackoverflow.com/q/50546401
tags question: http://stackoverflow.com/q/50668452
tags question: http://stackoverflow.com/q/50591612
tags question: http://stackoverflow.com/q/50697834
tags question: http://stackoverflow.com/q/50548180
tags question: http://stackoverflow.com/q/50556613
tags question: http://stackoverflow.com/q/50665990
tags question: http://stackoverflow.com/q/50592764
tags question: http://stackoverflow.com/q/50611496
tags question: http://stackoverflow.com/q/50674031
tags question: http://stackoverflow.com/q/50665045
tags question: http://stackoverflow.com/q/50650342
tags question: http://stackoverflow.com/q/50615824
tags question: http://stackoverflow.com/q/50549369
tag name: web-scraping
tags question: http://stackoverflow.com/q/50558056
tags question: http://stackoverflow.com/q/50594392
tags question: http://stackoverflow.com/q/50632242
tags question: http://stackoverflow.com/q/50602931
tags question: http://stackoverflow.com/q/50645836
tags question: http://stackoverflow.com/q/50685356
tags question: http://stackoverflow.com/q/50692122
tags question: http://stackoverflow.com/q/50578090
tags question: http://stackoverflow.com/q/50677132
tags question: http://stackoverflow.com/q/50573455
tags question: http://stackoverflow.com/q/50633442
type: Tag
tags question: http://stackoverflow.com/q/50631800
tags question: http://stackoverflow.com/q/50602194
tags question: http://stackoverflow.com/q/50655036
tags question: http://stackoverflow.com/q/50665082
tags question: http://stackoverflow.com/q/50578810
tags question: http://stackoverflow.com/q/50637847
tags question: http://stackoverflow.com/q/50622856
tags question: http://stackoverflow.com/q/50574869
tags question: http://stackoverflow.com/q/50676937
tags question: http://stackoverflow.com/q/50649171
tags question: http://stackoverflow.com/q/50568330
tags question: http://stackoverflow.com/q/50672029
tags question: http://stackoverflow.com/q/50562793
tags question: http://stackoverflow.com/q/50570910
tags question: http://stackoverflow.com/q/50649425
tags question: http://stackoverflow.com/q/50650983

http://stackoverflow.com/comment/88133521
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50543479
type: AnswerComment
has text: Just in case it's the largest value, would you update the value of max_number with the new instance of it at another index?

http://stackoverflow.com/comment/88229786
score: 0
type: Comment
type: QuestionComment
has text: What would you want as `payment` for days which are not in your existing dataframe? It might help if you can show a sample of your expected output.
comment on: http://stackoverflow.com/q/50610012

http://stackoverflow.com/comment/88197219
has text: Have you profiled your code to see where it's actually spending most of its time?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50593573
score: 0

http://stackoverflow.com/q/50663706
tagged with: odoo
has title: How to create multiple values at a time into ODOO using odoo-xml-rpc?
type: Question
has body: Can I create multiple values at a time using the following code? id = models.execute_kw(db ,uid ,password ,'res.partner' ,'create' ,[{}]
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50664306
type: UnansweredQuestion
tagged with: python
score: 3
upvote count: 3

http://stackoverflow.com/comment/88272814
type: Comment
comment on: http://stackoverflow.com/q/50631393
type: QuestionComment
score: 1
has text: something like this? https://stackoverflow.com/questions/14882138/replace-value-in-json-file-for-key-which-can-be-nested-by-n-levels

http://stackoverflow.com/q/50627578
upvote count: 1
has body: Here I've written a test to determine if an API is responding to a bad request with the expected content... Scenario: Unkown user response body properties contain expected content Given I have a valid client auth token And I request a user with an unknown "valid" uuid And I get the response json Then the expected fields should contain expected content | field | content | | statusCode | 404 | | error | Not Found | | message | User record not found | This is the corresponding step: @then(u'the expected fields should contain expected content') def step_impl(context): for row in context.table: received_content = str(context.request_json.get(row['field'])) expected_content = row['content'] assert_equal(received_content, expected_content) It seems that Behave converts table row content to strings. My question is: Is it possible to specify the data type of a cell in a Behave table? In the actual response statusCode is an integer, but as you can see in my step function I'm forced to convert the request content to a string in order to validate it. I wouldn't need to do this if I could specify that the 404 I'm passing in the content column is an integer.
type: Question
tagged with: python-behave
has answer: http://stackoverflow.com/a/50651915
tagged with: cucumber
answer count: 2
tagged with: bdd
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50639963
tagged with: python
has title: Specify Behave table row data type
type: UnansweredQuestion
score: 1

http://stackoverflow.com/comment/99123984
comment on: http://stackoverflow.com/a/50585787
type: AnswerComment
score: 0
type: Comment
has text: @Christoph90, Good spot, I've corrected the answer now.

http://stackoverflow.com/a/50677009
accepted answer of: http://stackoverflow.com/q/50676651
answers question: http://stackoverflow.com/q/50676651
has comment: http://stackoverflow.com/comment/88364155
has body: IIUC, you want to randomly select 1 from every row and make the rest 0. Here's one approach. Sample the indices and based on indices assign 1. i.e idx = pd.DataFrame(np.stack(np.where(df==1))).T.groupby(0).apply(lambda x: x.sample(1)).values # array([[0, 2], # [1, 1], # [2, 0], # [3, 3]]) ndf = pd.DataFrame(np.zeros(df.shape),columns=df.columns) ndf.values[idx[:,0],idx[:,1]] = 1 W1 W2 W3 W4 0 0 0 1 0 1 1 0 0 0 2 1 0 0 0 3 0 1 0 0
upvote count: 2
has comment: http://stackoverflow.com/comment/88363967
type: AcceptedAnswer
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/88396240
downvote count: 0

http://stackoverflow.com/comment/88268599
comment on: http://stackoverflow.com/q/50629307
score: 3
type: Comment
type: QuestionComment
has text: Yes, simply set the [`prefix_chars`](https://docs.python.org/3/library/argparse.html#prefix-chars) option.

http://stackoverflow.com/q/50672792
accepted answer: http://stackoverflow.com/a/50672886
favorite count: 0
tagged with: python-3.x
upvote count: 2
possible better answer: http://stackoverflow.com/a/50672900
has answer: http://stackoverflow.com/a/50672900
tagged with: python
score: 2
type: AnsweredQuestion
has title: Summing elements at the beginning with the elements at the end of a list
tagged with: list
has body: Given a list of numbers, create a new list of numbers such that the first and last numbers are added and stored as the first number, the second and second-to-last numbers are stored as the second number, and so on num_list = [1,2,3,4,5,6] num_list2 = [num_list[-1] + num_list[0], num_list[-2] + num_list[1], num_list[-3] + num_list[2]] print(num_list2) output is [7,7,7] I got the correct output this way but I am sure this is not an efficient way to do it. Is there a better way? I also am supposed to check for even and odd length of the list and if its an odd number of integers, add the central integer in the original list to the end of the new list but don't know how I would go about doing this
has answer: http://stackoverflow.com/a/50673037
has answer: http://stackoverflow.com/a/50672886
type: Question
has answer: http://stackoverflow.com/a/50672907
answer count: 6
has answer: http://stackoverflow.com/a/50673172
has answer: http://stackoverflow.com/a/50673093
downvote count: 0

http://stackoverflow.com/a/50656392
downvote count: 0
type: Answer
has body: The problem is that you rewrite the content of x as the keys (text, author, tags) are the same at each iteration, so to keep all the data, you can do: dict_x = {} index_nb = 0 for quote in sel.css("div.quote"): text = quote.css("span.text::text").extract_first() author = quote.css("small.author::text").extract_first() tags = quote.css("div.tags a.tag::text").extract() dict_x[index_nb] = dict(text=text, author=author, tags=tags) index_nb += 1 and then your df can be created like: import pandas as pd df = pd.DataFrame.from_dict(dict_x, orient='index') and you have each row a quote, and with data for columns text, author and tags You can create the csv by df.to_csv('file_name.csv') add some parameters according to the documentation if you want a specific format for your output
upvote count: 1
answers question: http://stackoverflow.com/q/50656043
score: 1
accepted answer of: http://stackoverflow.com/q/50656043
type: AcceptedAnswer

http://stackoverflow.com/comment/88124277
score: 0
comment on: http://stackoverflow.com/q/50556645
type: Comment
type: QuestionComment
has text: Can columns `A` or `B` have values greater then 2.5?

http://stackoverflow.com/comment/88368966
has text: The docs of OpenOffice are slightly better (although not great either): https://www.openoffice.org/api/docs/common/ref/com/sun/star/text/TextField.html#XPropertySet
comment on: http://stackoverflow.com/q/50679134
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/59278225
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50639614
has body: RDD -> spark dataframe using Spark like: import spark.implicits._ val testDF = rdd.map {line=&gt; (line._1,line._2) }.toDF("col1","col2")

http://stackoverflow.com/a/50662237
has body: Don't mix __getitem__ based indexing and (i)loc based. Use one or the other. I prefer (i)loc when you're accessing by index, and __getitem__ when you're accessing by column or using boolean indexing. Here's some commonly bad methods of indexing: df.loc[idx].loc[:, col] df.loc[idx][col] df[column][idx] df[column].loc[idx] The correct method for all the above would be df.loc[idx, col]. If idx is an integer label, use df.loc[df.index[idx], col]. Most of these solutions will cause issues down the pipeline (mainly in the form of a SettingWithCopyWarning), when you try assigning to them, because these create views and are tied to the original DataFrame they're viewing into. The correct solution to all these versions is df.iloc[idx, df.columns.get_loc(column)] Note that idx is an array of integer indexes, and column is a string label. Similarly for loc. If you have an array of booleans, use loc instead, like this: df.loc[boolean_idx, column] Furthermore, these are fine: df[column], and df[boolean_mask] There are rules for indexing a single row or single column. Depending on how it is done, you will get either a Series or DataFrame. So, if you want to index the 100th row from a DataFrame df as a DataFrame slice, you need to do: df.iloc[[100], :] # `:` selects every column And not df.iloc[100, :] And similarly for the column-based indexing. Lastly, if you want to index a single scalar, use at or iat. OTOH, for your requirement, I would suggest a third alternative: ts = df.loc[df.timestamp.between(5, 10), 'timestamp'] Or if you're subsetting the entire thing, df = df[df.timestamp.between(5, 10)]
score: 3
type: Answer
answers question: http://stackoverflow.com/q/50662176
upvote count: 3
has comment: http://stackoverflow.com/comment/104521124
downvote count: 0

http://stackoverflow.com/comment/88214042
type: Comment
comment on: http://stackoverflow.com/a/50601461
has text: I've updated to clarify. Yes, each worker performs the `runit` method on a single email at a time. If there are many more emails than workers, the workers will work in parallel, processing one email at a time, with all the results returned in `result_list`.
score: 0
type: AnswerComment

http://stackoverflow.com/a/50686678
upvote count: 2
type: Answer
downvote count: 2
has comment: http://stackoverflow.com/comment/88424931
answers question: http://stackoverflow.com/q/50686608
score: 0
has body: You are trapped in a endless while loop on: while float(line) &lt; 22.0: while float(line2) &lt; 27.0: Change them to: if float(line) &lt; 22.0: if float(line2) &lt; 27.0:

http://stackoverflow.com/q/50625366
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/50625675
accepted answer: http://stackoverflow.com/a/50625888
tagged with: python
has comment: http://stackoverflow.com/comment/88260735
has body: Results running the code for python3: ------- input option 1 - exec code is executed -------- 0 - for running inside function, 1 - for running in main programa: 1 option = 1 10 ------- input option 0 - exec code not executed inside function ---- 0 - for running inside function, 1 - for running in main programa: 0 option = 0 code inside execfunction =&gt; A = 10 Traceback (most recent call last): File "myexec.py", line 19, in &lt;module&gt; print(A) NameError: name 'A' is not defined ---------------------Code -------------------------- myexec.py def execfunction(icode): print('code inside execfunction =&gt; %s' %(icode)) exec(icode) option = int(input("0 - for running inside function, 1 - for running in main programa: ")) print('option = %d' %(option)) code = 'A = 10' if (option == 1): exec(code) else: execfunction(code) print(A)
score: 0
has comment: http://stackoverflow.com/comment/88260987
answer count: 3
has comment: http://stackoverflow.com/comment/88261239
has title: Why running exec inside function fail in python3?
has comment: http://stackoverflow.com/comment/88261017
has answer: http://stackoverflow.com/a/50625888
has comment: http://stackoverflow.com/comment/88261047
linked to: http://stackoverflow.com/q/15086040
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/25076883
possible better answer: http://stackoverflow.com/a/50625540
has comment: http://stackoverflow.com/comment/88260896
has answer: http://stackoverflow.com/a/50625540

http://stackoverflow.com/comment/88131911
score: 0
type: Comment
has text: Thank you. What is completely `error`?
type: QuestionComment
comment on: http://stackoverflow.com/q/50560652

http://stackoverflow.com/comment/88348592
comment on: http://stackoverflow.com/q/50669205
score: 0
type: QuestionComment
has text: @EOF what do you mean by that? It should work, as it did in windows based system with virtualalloc rtlmemorymove createThread function calls, the problem of segmentation fault happens only dealing with POSIX systems
type: Comment

http://stackoverflow.com/comment/88311222
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50634103
has text: Experimenting with filesystems is rather hard, perhaps you could manipulate one of the modules — for example, install `crypto`, rename its directory and rewrite the code — fix `import crypto` and `from crypto import…`. After that install `Crypto`.
score: 1

http://stackoverflow.com/comment/88310457
type: Comment
has text: Thank you for the reply. But the code still does not get beyond 20.
score: 0
comment on: http://stackoverflow.com/a/50649758
type: AnswerComment

matplotlib
tags question: http://stackoverflow.com/q/50556864
tags question: http://stackoverflow.com/q/50656253
tags question: http://stackoverflow.com/q/50604349
tags question: http://stackoverflow.com/q/50601939
tags question: http://stackoverflow.com/q/50602158
tags question: http://stackoverflow.com/q/50543055
tags question: http://stackoverflow.com/q/50648207
tags question: http://stackoverflow.com/q/50648950
tags question: http://stackoverflow.com/q/50626358
tags question: http://stackoverflow.com/q/50603091
tags question: http://stackoverflow.com/q/50682676
tags question: http://stackoverflow.com/q/50698608
tags question: http://stackoverflow.com/q/50551692
tags question: http://stackoverflow.com/q/50662685
tags question: http://stackoverflow.com/q/50602569
tags question: http://stackoverflow.com/q/50593250
tags question: http://stackoverflow.com/q/50632785
tags question: http://stackoverflow.com/q/50577457
tags question: http://stackoverflow.com/q/50640015
tags question: http://stackoverflow.com/q/50662638
tags question: http://stackoverflow.com/q/50605628
tags question: http://stackoverflow.com/q/50630825
tags question: http://stackoverflow.com/q/50693223
tag name: matplotlib
tags question: http://stackoverflow.com/q/50649556
tags question: http://stackoverflow.com/q/50559200
tags question: http://stackoverflow.com/q/50689996
tags question: http://stackoverflow.com/q/50646523
tags question: http://stackoverflow.com/q/50659030
tags question: http://stackoverflow.com/q/50633016
tags question: http://stackoverflow.com/q/50557982
tags question: http://stackoverflow.com/q/50590900
tags question: http://stackoverflow.com/q/50632550
tags question: http://stackoverflow.com/q/50658809
tags question: http://stackoverflow.com/q/50688595
tags question: http://stackoverflow.com/q/50560525
tags question: http://stackoverflow.com/q/50653454
tags question: http://stackoverflow.com/q/50601325
tags question: http://stackoverflow.com/q/50544794
tags question: http://stackoverflow.com/q/50585111
tags question: http://stackoverflow.com/q/50649553
tags question: http://stackoverflow.com/q/50641042
tags question: http://stackoverflow.com/q/50580918
tags question: http://stackoverflow.com/q/50559775
tags question: http://stackoverflow.com/q/50688992
tags question: http://stackoverflow.com/q/50615357
tags question: http://stackoverflow.com/q/50671566
tags question: http://stackoverflow.com/q/50584736
tags question: http://stackoverflow.com/q/50555179
tags question: http://stackoverflow.com/q/50638314
tags question: http://stackoverflow.com/q/50565952
tags question: http://stackoverflow.com/q/50662007
tags question: http://stackoverflow.com/q/50654620
tags question: http://stackoverflow.com/q/50550801
tags question: http://stackoverflow.com/q/50571592
tags question: http://stackoverflow.com/q/50567195
tags question: http://stackoverflow.com/q/50697254
tags question: http://stackoverflow.com/q/50576224
tags question: http://stackoverflow.com/q/50633132
tags question: http://stackoverflow.com/q/50694835
tags question: http://stackoverflow.com/q/50607534
tags question: http://stackoverflow.com/q/50691151
tags question: http://stackoverflow.com/q/50649461
tags question: http://stackoverflow.com/q/50633040
tags question: http://stackoverflow.com/q/50642641
tags question: http://stackoverflow.com/q/50589835
tags question: http://stackoverflow.com/q/50655774
tags question: http://stackoverflow.com/q/50602212
tags question: http://stackoverflow.com/q/50608927
tags question: http://stackoverflow.com/q/50611171
tags question: http://stackoverflow.com/q/50545802
tags question: http://stackoverflow.com/q/50573579
tags question: http://stackoverflow.com/q/50626539
tags question: http://stackoverflow.com/q/50658806
tags question: http://stackoverflow.com/q/50579184
tags question: http://stackoverflow.com/q/50648127
tags question: http://stackoverflow.com/q/50583392
tags question: http://stackoverflow.com/q/50566896
tags question: http://stackoverflow.com/q/50631713
tags question: http://stackoverflow.com/q/50594613

http://stackoverflow.com/comment/88404361
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50697130
has text: `__contains__` is not generally supposed to be called directly, instead you can do `if vertex in faces[row]:`... But anyway, the problem is that you are using a loop-based solution instead of a vectorized one (see answer).

http://stackoverflow.com/comment/88249458
type: AnswerComment
has text: accessing `.index` is useless. You will get the same length if you use `df` directly
type: Comment
score: 2
comment on: http://stackoverflow.com/a/50619807

http://stackoverflow.com/a/50575426
answers question: http://stackoverflow.com/q/50560803
score: 0
has comment: http://stackoverflow.com/comment/88228135
has comment: http://stackoverflow.com/comment/88199108
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88240098
has comment: http://stackoverflow.com/comment/88209376
accepted answer of: http://stackoverflow.com/q/50560803
type: Answer
has body: Other than a memory leak (only deleted the outer new not then inner ones), your code looks fine. Here's what I did: test.i %module test %typemap(out) int** { $result = PyList_New(4); for(int i=0;i&lt;4;i++) { PyObject *o = PyList_New(4); for(int j=0;j&lt;4;j++) { PyList_SetItem(o,j,PyInt_FromLong((long)$1[i][j])); } delete [] $1[i]; PyList_SetItem($result, i, o); } delete [] $1; } %inline %{ int** myfunction() { int **value = new int*[4]; for(int i=0;i&lt;4;i++) { value[i] = new int[4]; for(int j=0;j&lt;4;j++) value[i][j] = i*4+j; } return value; } %} Built with SWIG and VS2015 compiler: swig -c++ -python test.i cl /EHsc /LD /W3 /MD /Fe_test.pyd /Ic:\python36\include test_wrap.cxx -link /libpath:c:\python36\libs Output: &gt;&gt;&gt; import test &gt;&gt;&gt; test.myfunction() [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]
has comment: http://stackoverflow.com/comment/88198711

python-2.7
tags question: http://stackoverflow.com/q/50550397
tags question: http://stackoverflow.com/q/50558480
tags question: http://stackoverflow.com/q/50657434
tags question: http://stackoverflow.com/q/50542736
tags question: http://stackoverflow.com/q/50673870
tags question: http://stackoverflow.com/q/50553585
tags question: http://stackoverflow.com/q/50610838
tags question: http://stackoverflow.com/q/50576681
tags question: http://stackoverflow.com/q/50590087
tags question: http://stackoverflow.com/q/50681241
tags question: http://stackoverflow.com/q/50638652
tags question: http://stackoverflow.com/q/50542767
tags question: http://stackoverflow.com/q/50630221
tags question: http://stackoverflow.com/q/50673212
tags question: http://stackoverflow.com/q/50669200
tags question: http://stackoverflow.com/q/50568826
tags question: http://stackoverflow.com/q/50614980
tags question: http://stackoverflow.com/q/50544763
tags question: http://stackoverflow.com/q/50550433
tags question: http://stackoverflow.com/q/50668927
tags question: http://stackoverflow.com/q/50611171
tags question: http://stackoverflow.com/q/50677554
tags question: http://stackoverflow.com/q/50615031
tags question: http://stackoverflow.com/q/50696311
tags question: http://stackoverflow.com/q/50602489
tags question: http://stackoverflow.com/q/50643953
tags question: http://stackoverflow.com/q/50686078
tags question: http://stackoverflow.com/q/50570258
tags question: http://stackoverflow.com/q/50584236
tags question: http://stackoverflow.com/q/50691116
tags question: http://stackoverflow.com/q/50594442
tags question: http://stackoverflow.com/q/50672758
tags question: http://stackoverflow.com/q/50680085
tags question: http://stackoverflow.com/q/50670355
tags question: http://stackoverflow.com/q/50609761
tags question: http://stackoverflow.com/q/50672603
tags question: http://stackoverflow.com/q/50680783
tags question: http://stackoverflow.com/q/50577761
tags question: http://stackoverflow.com/q/50589771
tags question: http://stackoverflow.com/q/50595428
tags question: http://stackoverflow.com/q/50696357
tags question: http://stackoverflow.com/q/50676079
tags question: http://stackoverflow.com/q/50695027
tags question: http://stackoverflow.com/q/50639495
tags question: http://stackoverflow.com/q/50636877
tags question: http://stackoverflow.com/q/50684708
tags question: http://stackoverflow.com/q/50576975
tags question: http://stackoverflow.com/q/50632842
tags question: http://stackoverflow.com/q/50686742
tags question: http://stackoverflow.com/q/50653986
tags question: http://stackoverflow.com/q/50547454
tags question: http://stackoverflow.com/q/50548180
tags question: http://stackoverflow.com/q/50588127
tags question: http://stackoverflow.com/q/50671629
tags question: http://stackoverflow.com/q/50677892
tags question: http://stackoverflow.com/q/50668973
tags question: http://stackoverflow.com/q/50592764
tags question: http://stackoverflow.com/q/50601646
tags question: http://stackoverflow.com/q/50693884
tags question: http://stackoverflow.com/q/50622319
tags question: http://stackoverflow.com/q/50613391
tags question: http://stackoverflow.com/q/50677712
tags question: http://stackoverflow.com/q/50652004
tags question: http://stackoverflow.com/q/50632506
tags question: http://stackoverflow.com/q/50649825
tags question: http://stackoverflow.com/q/50599163
tags question: http://stackoverflow.com/q/50658649
tags question: http://stackoverflow.com/q/50577489
tags question: http://stackoverflow.com/q/50651216
tags question: http://stackoverflow.com/q/50657217
tags question: http://stackoverflow.com/q/50652782
tags question: http://stackoverflow.com/q/50601883
tags question: http://stackoverflow.com/q/50586519
tags question: http://stackoverflow.com/q/50690876
tags question: http://stackoverflow.com/q/50607467
tags question: http://stackoverflow.com/q/50642532
tags question: http://stackoverflow.com/q/50648114
tags question: http://stackoverflow.com/q/50603671
tags question: http://stackoverflow.com/q/50639222
tags question: http://stackoverflow.com/q/50587834

http://stackoverflow.com/q/50602304
accepted answer: http://stackoverflow.com/a/50602805
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88214165
score: -1
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50602805
favorite count: 0
tagged with: tkinter
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88213842
has body: I'm having trouble placing three frames using the ttk module. I need to have them at the same size. The left one is placed correctly, but the ones from the right should match the first one's size. My code is this: from tkinter import * from tkinter import ttk master = Tk() frame_labels = ttk.Frame(master, width=500, height=500, relief=SUNKEN) frame_labels.grid(row=1, column=1, padx=10, pady=10, sticky='n') frame_log = ttk.Frame(master, width=500, height=300, relief=SUNKEN) frame_log.grid(row=1, column=3, padx=0, pady=10, sticky='n') credits_frame = ttk.Frame(master, width=500, height=200, relief=SUNKEN) credits_frame.grid(row=2, column=3, padx=0, pady=10, sticky='n') master.mainloop() Thanks for any help!
has title: Tkinter align multiple frames

gdal
tags question: http://stackoverflow.com/q/50585177
tags question: http://stackoverflow.com/q/50606174
tag name: gdal
tags question: http://stackoverflow.com/q/50644447
type: Tag

http://stackoverflow.com/comment/88376881
type: Comment
has text: @AntonvBR the data has been scraped from a website, I don't control how a website presents their data.
type: QuestionComment
comment on: http://stackoverflow.com/q/50683529
score: 0

http://stackoverflow.com/a/50564789
type: AcceptedAnswer
has body: Using ElementTree Demo: from xml.etree import ElementTree as ET import os import csv res = [] for filename in os.listdir(path): #Check Dir For file if filename.endswith('.xml'): #Check if extension is '.xml' filePath = os.path.join(path, filename) x = ET.parse(filePath) #Read xml using 'ET.parse' res.append([x.find("Task").text.strip(), x.find("author").attrib["type"], x.find("comments").text.strip()]) #Get required values. with open(r"C:\Users\zk0h098\Desktop\testFiles\A.csv", "w") as infile: writer = csv.writer(infile, delimiter=",") writer.writerow(["Task", "Author", "Comments"]) #Write Header for line in res: writer.writerow(line) #Write content
type: Answer
has comment: http://stackoverflow.com/comment/89178477
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/50563724
answers question: http://stackoverflow.com/q/50563724
upvote count: 1

http://stackoverflow.com/comment/110486346
score: 0
has text: From the data you have you ideally create train, validation and test datasets. (TRAVALTES). Train for training, validation to check if you are overfitting/underfitting. You calculate accuracy score, or some other score (f1...) to get some clues and ideally create confusion matrix if you have a problem like classification. So this post of mine sucks. I will improve it later today.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/56672709

http://stackoverflow.com/comment/88399164
type: Comment
has text: Mr.T, thats whats I'm looking for indeed. But I can't get my head around the how
comment on: http://stackoverflow.com/q/50694219
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88198736
has text: Your `Mixin` is not acting like a mixin, or like a class at all. You have a bunch of methods that don't take `self`, which you call by relying on the fact that unbound methods are implemented as regular functions. So, why not just use a list, or an `OrderedDict`, or a `namedtuple`, or something else?
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50594741

http://stackoverflow.com/q/50578090
type: Question
score: 0
has body: I would like to get all of the displayed text on an HTML page up until a certain tag is hit. For example, I would like to get all of the displayed text on a page up until a tag with the id "end_content" is hit. Is there a way to do this with BeautifulSoup? This would be similar to the soup.get_text() method, except it would just stop fetching text after it hits a tag with the id "end_content".
answer count: 1
favorite count: 0
tagged with: beautifulsoup
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50579262
has title: BeautifulSoup: Get tag text up to certain tag
tagged with: web-scraping
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/50571916
tagged with: linear-regression
score: 0
has title: Linear regression getting NaN for loss
linked to: http://stackoverflow.com/q/37232782
has comment: http://stackoverflow.com/comment/88154153
has answer: http://stackoverflow.com/a/50572571
type: AnsweredQuestion
answer count: 1
tagged with: keras
type: Question
has body: Cant understand why keras linear regression model is not working. Using Boston Housing data.Get Loss as nan path='/Users/admin/Desktop/airfoil_self_noise.csv' df=pd.read_csv(path,sep='\t',header=None) y=df[5] #TARGET df2=df.iloc[:,:-1] X_train, X_test, y_train, y_test = train_test_split(df2, y, test_size=0.2) p = Sequential() p.add(Dense(units=20, activation='relu', input_dim=5)) p.add(Dense(units=20, activation='relu')) p.add(Dense(units=1)) p.compile(loss='mean_squared_error', optimizer='sgd') p.fit(X_train, y_train, epochs=10, batch_size=32) this yeilds: Epoch 1/10 1202/1202 [==============================] - 0s 172us/step - loss: nan Epoch 2/10 1202/1202 [==============================] - 0s 37us/step - loss: nan Epoch 3/10 1202/1202 [==============================] - 0s 38us/step - loss: nan Epoch 4/10 1202/1202 [==============================] - 0s 36us/step - loss: nan Epoch 5/10 1202/1202 [==============================] - 0s 36us/step - loss: nan Epoch 6/10 1202/1202 [==============================] - 0s 40us/step - loss: nan
tagged with: python
accepted answer: http://stackoverflow.com/a/50572571

http://stackoverflow.com/a/50612359
has body: In your snake's __init__ method you have defined an attribute, self.changeDirectionTo, which points to a string and which overrides the method with the same name. You should delete that line.
has comment: http://stackoverflow.com/comment/88234854
answers question: http://stackoverflow.com/q/50612328
score: 0
type: Answer

http://stackoverflow.com/a/58839800
has comment: http://stackoverflow.com/comment/107822913
upvote count: 3
has body: If you are using python3, write: fgbg =cv2.createBackgroundSubtractorMOG2() #For python3 And not: fgbg = cv2.bgsegm.createBackgroundSubtractorMOG()
downvote count: 1
answers question: http://stackoverflow.com/q/50674051
type: Answer
score: 2

http://stackoverflow.com/q/50630069
upvote count: 0
has body: I am trying to do Alert Exception Handling, I have tried a few options but I cant seem to get the script to try the exception, it just errors out. #Add Alert Bypass try: driver.switch_to.default_content() except NoAlertPresentException: print('Alert Popup') alert = driver.switch_to.alert() alert.dismiss() Error Message: Message: unexpected alert open: {Alert text : ...}
answer count: 1
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88273612
tagged with: python
has comment: http://stackoverflow.com/comment/88270308
tagged with: selenium
tagged with: error-handling
has comment: http://stackoverflow.com/comment/88270183
downvote count: 1
has title: Alert Popup Exception Handling Python Selenium
type: Question
score: -1
has answer: http://stackoverflow.com/a/50632482
has comment: http://stackoverflow.com/comment/88272389

http://stackoverflow.com/q/50650491
duplicate of: http://stackoverflow.com/q/5564418
type: Question
linked to: http://stackoverflow.com/q/5564418
tagged with: arrays
has comment: http://stackoverflow.com/comment/88361345
has title: Cannot retrieve array environment variables with `os.environ`
score: 4
has comment: http://stackoverflow.com/comment/88312058
tagged with: bash
has comment: http://stackoverflow.com/comment/88312104
tagged with: environment-variables
has comment: http://stackoverflow.com/comment/88311954
has comment: http://stackoverflow.com/comment/88312041
downvote count: 0
has body: If I declare an environment variable like: $ export simple_variable="Test" $ echo $simple_variable Test I can retrieve it in python with: &gt;&gt;&gt; import os &gt;&gt;&gt; var = os.environ['simple_variable'] &gt;&gt;&gt; print(var) 'Test' But if I declare an array environment variable like: $ export array_variable=(one two three) $ echo ${array_variable[*]} one two three The same python scrit will fail: &gt;&gt;&gt; import os &gt;&gt;&gt; os.environ['array_variable'] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python3.5/os.py", line 725, in __getitem__ raise KeyError(key) from None KeyError: 'array_variable' Why? How do I retrieve this array environment variable from my python script?
favorite count: 0
has comment: http://stackoverflow.com/comment/88361387
has comment: http://stackoverflow.com/comment/88311993
has comment: http://stackoverflow.com/comment/88311964
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88311919
tagged with: python
upvote count: 4
answer count: 0

http://stackoverflow.com/a/50670223
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: First you need to group by ID and then calculate the mean. import pandas as pd df = pd.read_csv('Book1.csv') df1 = df.groupby(['ID'], as_index= False)'Salary', 'days'.mean() print(df1) ID Salary days 1 1999.666667 3.0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50669877
answers question: http://stackoverflow.com/q/50669877
score: 1

http://stackoverflow.com/q/50645134
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50645212
score: 4
type: AnsweredQuestion
type: Question
upvote count: 4
has body: Let I have a dataframe with datetime index like this: date_time open high low close vol 2018-05-13 18:00:00 70.54 70.60 70.42 70.55 2665 2018-05-13 18:15:00 70.55 70.59 70.53 70.58 378 2018-05-13 18:30:00 70.58 70.70 70.57 70.69 1470 2018-05-13 18:45:00 70.68 70.68 70.63 70.65 427 ... 2018-05-14 00:00:00 70.46 70.47 70.40 70.41 1276 2018-05-14 00:15:00 70.41 70.45 70.38 70.39 1356 2018-05-14 00:30:00 70.39 70.48 70.39 70.46 1161 2018-05-14 00:45:00 70.46 70.47 70.43 70.46 359 I need two more columns with DAILY High and DAILY low values. I'm trying make this: df['day_high']= x.resample('D').high.max() df.day_high = x.day_high.fillna(method='ffill') It is works perfectly on days, where 00:00:00 datatime exist. Thus, 14.05.2018 I have a value with datetime 00:00:00 and my code works. But 2018-05-13 day began at 18:00 and my code return "NaN" value (I know, why, but I don't know how to write correct code). Could you help me? Thanks.
tagged with: dataframe
has title: Daily High/Low on intraday data
has answer: http://stackoverflow.com/a/50645212
tagged with: pandas

shell-exec
tags question: http://stackoverflow.com/q/50599163
tag name: shell-exec
type: Tag
tags question: http://stackoverflow.com/q/50631331

http://stackoverflow.com/q/50558798
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/50558850
accepted answer: http://stackoverflow.com/a/50558892
tagged with: numpy
linked to: http://stackoverflow.com/q/6910641
possible better answer: http://stackoverflow.com/a/50558850
has comment: http://stackoverflow.com/comment/88128710
downvote count: 0
tagged with: sorting
has body: I want to get the top N (maximal) args &amp; values across an entire numpy matrix, as opposed to across a single dimension (rows / columns). Example input (with N=3): import numpy as np mat = np.matrix([[9,8, 1, 2], [3, 7, 2, 5], [0, 3, 6, 2], [0, 2, 1, 5]]) print(mat) [[9 8 1 2] [3 7 2 5] [0 3 6 2] [0 2 1 5]] Desired output: [9, 8, 7] Since max isn't transitive across a single dimension, going by rows or columns doesn't work. # by rows, no 8 np.squeeze(np.asarray(mat.max(1).reshape(-1)))[:3] array([9, 7, 6]) # by cols, no 7 np.squeeze(np.asarray(mat.max(0)))[:3] array([9, 8, 6]) I have code that works, but looks really clunky to me. # reshape into single vector mat_as_vector = np.squeeze(np.asarray(mat.reshape(-1))) # get top 3 arg positions top3_args = mat_as_vector.argsort()[::-1][:3] # subset the reshaped matrix top3_vals = mat_as_vector[top3_args] print(top3_vals) array([9, 8, 7]) Would appreciate any shorter way / more efficient way / magic numpy function to do this!
answer count: 3
tagged with: matrix
linked to: http://stackoverflow.com/q/50533797
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/50558892
has answer: http://stackoverflow.com/a/50558927
has title: How to get max (top) N values across entire numpy matrix
upvote count: 3
type: Question

http://stackoverflow.com/comment/88267134
type: QuestionComment
score: 0
has text: This is a known issue; the `=` solution was provided in https://stackoverflow.com/a/16175115/901925
comment on: http://stackoverflow.com/q/50621922
type: Comment

http://stackoverflow.com/comment/88304373
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50632892
has text: Thanks , tried both suggestions. I could not find a function that will read metadata from sas7 files
type: AnswerComment

http://stackoverflow.com/a/50592304
score: -1
has comment: http://stackoverflow.com/comment/88196838
has comment: http://stackoverflow.com/comment/88222151
has comment: http://stackoverflow.com/comment/88222553
has body: you can uninstall using a requirements package simply create / take your requriements list like so: django flask other_packages put that in a text file called requirements.txt then do pip uninstall -r requirements.txt or in your case pip3 uninstall -r requirements.txt
type: Answer
answers question: http://stackoverflow.com/q/50591842
has comment: http://stackoverflow.com/comment/88222038
has comment: http://stackoverflow.com/comment/88221740
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/88221527
has comment: http://stackoverflow.com/comment/88222342

http://stackoverflow.com/a/50646687
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50644567
has body: Unfortunately there is no workaround here unless you provide a tf.Variable() (which is not possible in your case) to the parameter of tf.nn.embedding_lookup()/tf.gather(). This is happening because, When you declare them with a placeholder of shape [None, None], from tf.gather() function tf.IndexedSlices() become a sparse tensor. I have already done projects facing this warning. What I can tell you that if there is a tf.nn.dynamic_rnn() next to the embedding_lookup then make the parameter named swap_memory of tf.nn.dynamic_rnn() to True. Also to avoid OOM or Resource Exhausted error make the batch size smaller (test for different batch size). There are already some good explanation on this. Please refer to the following Question of the Stackoverflow. Tensorflow dense gradient explanation?

http://stackoverflow.com/comment/88245152
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50612201
has text: Thanks a lot for working this out. It looked easy, but I'm not sure I'd ever have got there myself! I can make G square in any cases where it isn't, so there should be no problem there.

http://stackoverflow.com/comment/88125338
has text: @JohnRotenstein, hi John. Thanks for the response. I have math model, which I want to test implementation multipart upload (As in this link at tip 6 was said [link](https://www.sumologic.com/aws/s3/10-things-might-not-know-using-s3/) ). My problem is I want to separate single large object and upload that to different storages, instead of one storage one object principles. If the info in the link is correct that means I should be able to do that.But I have no idea how
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50556549

http://stackoverflow.com/comment/88268288
score: 1
has text: Use a non-capturing group - `r"\w+(?:'\w+)?|[!-~]"`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50629057

http://stackoverflow.com/q/50694089
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50694620
has comment: http://stackoverflow.com/comment/88405528
tagged with: multithreading
has comment: http://stackoverflow.com/comment/88397830
has body: We use cx_Oracle to connect multiple threads to the database and issue various selects and updates. However, for unknown reasons, the script is being killed by the system on random database connections. There are no informations in the syslog or messages-files. Due to the error handling we try to write tracebacks in the logfile. Unfortunately we have no information about the crash of the script in the logfile. Only in stdout is a printout with "PID killed" at the last line. Could it be a problem to make database connections with multiple threads at the same time? There are also other scripts running at the same time that also talk to the database (not multi-threaded) but access other tables. This is our Function that is called for every select. For the updates we have other Functions. def ora_send_sql( logger, statement): try: dsn = cx_Oracle.makedsn(SQL_IP, SQL_PORT, SQL_SID) con = cx_Oracle.connect(SQL_USR, SQL_PWD, dsn) cur = con.cursor() cur.execute(statement) con.commit() con.close() return 0 except cx_Oracle.Warning as w: logger.warning(" Oracle-Warning: "+ str(e).strip()) pass except cx_Oracle.Error as e: error, = exc.args logger.error(" Oracle-Error-Code:", error.code) logger.error(" Oracle-Error-Message:", error.message) return -1 except: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] logger.exception(" Got Traceback in ora_send_sql: " + str(exc_type) + " Fname=" + str(fname) + " Lineno=" + str(exc_tb.tb_lineno)) return -2
upvote count: 1
has title: Python 2.7 Multi-threaded DB-Connection crashes randomly
has comment: http://stackoverflow.com/comment/88405635
type: Question
has comment: http://stackoverflow.com/comment/88405120
has answer: http://stackoverflow.com/a/50699028
has comment: http://stackoverflow.com/comment/88407812
score: 1
has comment: http://stackoverflow.com/comment/88398560
has comment: http://stackoverflow.com/comment/88405038
tagged with: cx-oracle
downvote count: 0
has comment: http://stackoverflow.com/comment/88407598
has comment: http://stackoverflow.com/comment/88406003
favorite count: 0
has comment: http://stackoverflow.com/comment/88398405
accepted answer: http://stackoverflow.com/a/50699028
answer count: 3
has answer: http://stackoverflow.com/a/50694620
has answer: http://stackoverflow.com/a/50710350
tagged with: python
has comment: http://stackoverflow.com/comment/88405898

http://stackoverflow.com/q/50576540
has comment: http://stackoverflow.com/comment/88163095
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88163173
type: UnansweredQuestion
tagged with: physics
has comment: http://stackoverflow.com/comment/88163482
upvote count: 1
tagged with: python
has title: Python Slingshot Model
has comment: http://stackoverflow.com/comment/88163314
has answer: http://stackoverflow.com/a/50576921
has comment: http://stackoverflow.com/comment/88162902
has comment: http://stackoverflow.com/comment/88163335
score: 0
has body: I am trying to model firing a projectile from a slingshot. This is my code: from pylab import * import numpy as np from scipy.integrate import odeint import seaborn ## set initial conditions and parameters g = 9.81 # acceleration due to gravity th = 30 # set launch angle th = th * np.pi/180. # convert launch angle to radians v0 = 10.0 # set initial speed c = 0.5 # controls strength of air drag d = 0.02 # diameter of the spherical rock A = pi * (d/2)**2 #the cross-sectional area of the spherical rock ro = 1.2041 #the density of the medium we are perfoming the launch in m = 0.01 #mass x0=0 # specify initial conditions y0=0 vx0 = v0*sin(th) vy0 = v0*cos(th) ## defining our model def slingshot_model(state,time): z = zeros(4) # create array to hold z vector z[0] = state[2] # z[0] = x component of velocity z[1] = state[3] # z[1] = y component of velocity z[2] = - c*A*ro/2*m*sqrt(z[0]**2 + z[1]**2)*z[0] # z[2] = acceleration in x direction z[3] = -g/m - c*A*ro/2*m*sqrt(z[0]**2 + z[1]**2)*z[1] # z[3] = acceleration in y direction return z ## set initial state vector and time array X0 = [x0, y0, vx0, vy0] # set initial state of the system t0 = 0 tf = 4 #final time tau = 0.05 #time step # create time array starting at t0, ending at tf with a spacing tau t = arange(t0,tf,tau) ## solve ODE using odeint X = odeint(slingshot_model,X0,t) # returns an 2-dimensional array with the # first index specifying the time and the # second index specifying the component of # the state vector # putting ':' as an index specifies all of the elements for # that index so x, y, vx, and vy are arrays at times specified # in the time array x = X[:,0] y = X[:,1] vx = X[:,2] vy = X[:,3] plt.rcParams['figure.figsize'] = [10, 10] plot(x,y) But it gives me this plot that doesn't make sense to me: What am I missing? The values shouldn't come out like they do, but for the life of me I can't see why. It is probably something trivial, but I have been staring at this too long, so I figured bringing in a fresh…
has comment: http://stackoverflow.com/comment/88163309
has comment: http://stackoverflow.com/comment/88163187
downvote count: 1
tagged with: scipy
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88163072
has comment: http://stackoverflow.com/comment/88163390
tagged with: kinematics
has comment: http://stackoverflow.com/comment/88163167
has comment: http://stackoverflow.com/comment/88163038

http://stackoverflow.com/comment/88237042
has text: I just made the simple python script as you suggested, which receives the data (it's the binary data): import sys, in = sys.stdin.read(), print(len(in)). However, using the line you suggested: (cat mypipe | ssh second_com@IP_address 'python myscript.py') makes this program to be executed on the second machine (from which I want to send data) and I need to receive and process the data on the first machine.
comment on: http://stackoverflow.com/a/50612859
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88231311
has text: @ChootsMagoots Methods/Functions have attributes. cont is an attribute in the __init__ method of the class. An attribute is a variable that belongs to a method or function. So I don't think what you're saying is correct.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50610516
type: QuestionComment

http://stackoverflow.com/q/50575902
answer count: 3
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50620452
linked to: http://stackoverflow.com/q/21034201
has answer: http://stackoverflow.com/a/50693479
has answer: http://stackoverflow.com/a/50620452
tagged with: django
has comment: http://stackoverflow.com/comment/88249717
score: 13
tagged with: python
has title: saving Base64ImageField Type using Django Rest saves it as Raw image. How do I convert it to a normal image
has body: I have 5 image fields in my model , imageA, imageB, imageC, imageD and imageE I am trying to save the images in the following manner.The image are of type Base64ImageField images=["imageA","imageB","imageC","imageD","imageE"] for field in images: if field in serializer.validated_data: content = serializer.validated_data[field] dict = {field : content} modelJob.objects.filter(id=modjob.id).update(**dict) In the above code content contains the raw data.I am trying to update the image using the dict I created (the key is the field name and value is the content). However the images saved in the imageField of the model are raw and not an actual image. How can I fix this ? This is what my serializer looks like class Serializer_Custom_RX(serializers.ModelSerializer): imageA = Base64ImageField(max_length=None, use_url=True, ) imageB = Base64ImageField(max_length=None, use_url=True, ) imageC = Base64ImageField(max_length=None, use_url=True, ) imageD = Base64ImageField(max_length=None, use_url=True, ) class Meta: model = modelTest fields = [ 'title', 'zip', 'imageA','imageB','imageC','imageD', ] More info: If I do something like this modelJob.instance.imageA.save(content=content,name="image.jpeg") it works fine and the problem is solved.However there are two problems with this approach first of all I do not know the extension. How do I extract an extension ? I am just guessing a jpeg here and it works. The next thing is Ill have to check for imageA,B,C,D and E if they exist and then save each one individually. If I could come up with a dynamic solution close to something that I have that would work as well. This is what my jsondata looks like that I am posting { "title" : "Some Title", "zip":12345, "imageA":"[binary]" }
upvote count: 13
has answer: http://stackoverflow.com/a/50739244
linked to: http://stackoverflow.com/q/26070547
has comment: http://stackoverflow.com/comment/88447259
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/2323128
has comment: http://stackoverflow.com/comment/88248419
linked to: http://stackoverflow.com/q/8332443
accepted answer: http://stackoverflow.com/a/50739244
has comment: http://stackoverflow.com/comment/88447343
type: Question
downvote count: 0
tagged with: django-rest-framework

http://stackoverflow.com/q/50610334
tagged with: pointers
has title: Wrap a double** c++ function with cython
has body: I have a C++ function which returns a pointer double** - a high dimensional matrix in particular - and I'd like to wrap it to some python code using Cython. How should I act? Here an example with a function with a double* pointer for sake of simplicity. My C++ fib.cpp code: double add(double a, double b) { return a+b; } double p[]= {1,2,3,4}; double* mult(double a) { p[0]=p[0]*a; p[1]=p[1]*a; return p; } Then there is the fib.hpp file: double add(double a,double b); double* mult(double a); Then the pxd file fib.pxd: cdef extern from "fib.hpp": double add(double a,double b); double* mult(double a); In the end the pyx file # distutils: language = c++ # distutils: sources = fib.cpp cimport fib def add(a,b): return fib.add(a,b) def mult(a): # dropping these lines return fib.mult(a) # the code works without the double* function Everything is compiled with the rather standard setup.py : from distutils.core import setup, Extension from Cython.Build import cythonize ext = Extension("fib2cpp", sources=["fib.pyx", "fib.cpp"], language="c++") setup(name="fib", ext_modules=cythonize(ext)) When I compile the code: setup.py build_ext -if Cannot convert 'double *' to python object. When I try with a double** function I get the same error. What should I do?
answer count: 1
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: c++
score: 2
has answer: http://stackoverflow.com/a/50643383
type: Question
downvote count: 0

http://stackoverflow.com/comment/88176654
has text: Yep, you need to add a `while True` loop inside capture and run the function in a thread.
type: Comment
comment on: http://stackoverflow.com/a/50581583
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88132777
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50557145
has text: I tried the list style, I still go the same error. I'll try without the square brackets

http://stackoverflow.com/comment/88137407
comment on: http://stackoverflow.com/a/50559949
has text: Muali I have been testing it and I have two questions if you have time to explain that would be great. 1. What exactly does the levels[1] command refer to? and my second question is : say I have a lot more traces maybe 10 or more, would there be an easy way to create a single loop that creates traces depending on the availability. Say if the trace values are stored in one column/variable.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88371671
score: 0
type: Comment
type: QuestionComment
has text: When asking about an error you get when loading a textfile you need to present the textfile (a minimal version of it) and a code that is specific to this problem (not some plotting commands, which are unrelated). See [mcve].
comment on: http://stackoverflow.com/q/50680783

http://stackoverflow.com/a/50656128
upvote count: 4
has body: Apart from looking for color space information in ICC profile, you can also look into EXIF metadata tags. Particularly EXIF tag ColorSpace (0xA001) indicates sRGB when it is equal to 1. Other values are not standard, according to this document, but might indicate other color spaces. Another helpful EXIF tag might be InteropIndex (0x0001). You could check these tags like this: from PIL import Image img = Image.open('image.jpg') def exif_color_space(img): exif = img._getexif() or {} if exif.get(0xA001) == 1 or exif.get(0x0001) == 'R98': print ('This image uses sRGB color space') elif exif.get(0xA001) == 2 or exif.get(0x0001) == 'R03': print ('This image uses Adobe RGB color space') elif exif.get(0xA001) is None and exif.get(0x0001) is None: print ('Empty EXIF tags ColorSpace and InteropIndex') else: print ('This image uses UNKNOWN color space (%s, %s)' % (exif.get(0xA001), exif.get(0x0001))) Also if your files come from DCIM folder (like in digital cameras or smartphones), Adobe RGB color space can be indicated by name starting from an underscore (like _DSC) or having an extension other than JPG (like JPE). If the color space of your image is still unknown, the safest is just to assume sRGB. If later a user finds out that the image looks too dull or dim, they can just view the image in other color spaces and it will probably make the image to appear more saturated.
downvote count: 0
score: 4
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/138135539
accepted answer of: http://stackoverflow.com/q/50641637
answers question: http://stackoverflow.com/q/50641637

http://stackoverflow.com/comment/88295683
score: 0
type: Comment
has text: I know it isn't a great idea to use regex for html, but i am constrained to do it by making use of regex. HTML parser wouldn't help me much. Any suggestion on modifying the regex to get what i need would be very much helpful.
type: QuestionComment
comment on: http://stackoverflow.com/q/50641495

http://stackoverflow.com/q/50555668
type: Question
tagged with: ckeditor
tagged with: flask
score: 0
tagged with: ckeditor4.x
answer count: 1
has answer: http://stackoverflow.com/a/51518762
has body: For Flask Admin How is it possible to upload images in Text area with editor ? I need simpler version than this: https://github.com/greyli/flask-ckeditor
tagged with: flask-admin
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51518762
has title: Flask Admin Ckeditor Image Upload

http://stackoverflow.com/comment/88312041
has text: @Aran-Fey Ah ok, I can see that now because I've reloaded the page, so... it wasn't that "evident" for me when the page wasn't explaining the reason and just showing a disabled "Post your answer" button ;)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50650491

http://stackoverflow.com/comment/132759057
has text: That is brilliant, I didn't hear of it! Thanks alot. maybe it is worth updating the answe to cover both situations.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50667147
type: Comment

http://stackoverflow.com/comment/88289853
has text: Or you can also convert the date according to your database date time format before inserting it to the database.
score: 0
comment on: http://stackoverflow.com/q/50617557
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88351133
comment on: http://stackoverflow.com/q/50670644
type: Comment
type: QuestionComment
score: 2
has text: You need to decide how the program will know to stop the polyline. In your example, it is done when the user clicks on the first point. How close must that click be to the first point to be considered on the first point? Is that the only way to end the connected segments? How about the user pressing the Escape key to end the segments? Or clicking a button to stop? And so on. You need to decide those items then add them to your problem description. You should look at commercial drawing programs to see how they handle this part of the user interface.

http://stackoverflow.com/a/57386306
has comment: http://stackoverflow.com/comment/129308702
has body: With Spark 2.4.0+, this is easier with builtin functions: array_repeat + explode: from pyspark.sql.functions import expr df = spark.createDataFrame([(1,2,1), (2,9,1), (3,8,2), (4,1,1), (5,3,3)], ["A", "B", "n"]) new_df = df.withColumn('n', expr('explode(array_repeat(n,int(n)))')) &gt;&gt;&gt; new_df.show() +---+---+---+ | A| B| n| +---+---+---+ | 1| 2| 1| | 2| 9| 1| | 3| 8| 2| | 3| 8| 2| | 4| 1| 1| | 5| 3| 3| | 5| 3| 3| | 5| 3| 3| +---+---+---+
answers question: http://stackoverflow.com/q/50624745
has comment: http://stackoverflow.com/comment/124536995
score: 22
has comment: http://stackoverflow.com/comment/124506783
type: Answer
upvote count: 22
has comment: http://stackoverflow.com/comment/124509913
downvote count: 0

http://stackoverflow.com/comment/88232580
comment on: http://stackoverflow.com/q/50611330
type: QuestionComment
type: Comment
score: 1
has text: You can easily do that with the sleep function of the time library, why using a loop?

http://stackoverflow.com/q/50695786
downvote count: 0
has title: Django Channels testing fails
has answer: http://stackoverflow.com/a/50715328
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/63631703
tagged with: websocket
favorite count: 0
answer count: 3
has body: I'm putting up django-channels on a basic django site, configured in the following way. consumers.py from channels.generic.websocket import WebsocketConsumer import json class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({ 'message': message })) routing.py from django.conf.urls import url from consumers import ChatConsumer #supposed to be on the main routing from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter websocket_urlpatterns = [ url(r'^ws/chat/$', ChatConsumer), ] #after linking to above as chat.routing application = ProtocolTypeRouter({ # (http-&gt;django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( websocket_urlpatterns ) ), }) settings.py ASGI_APPLICATION = 'chatsys.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('35.185.80.98', 6379)], }, }, } INSTALLED_APPS = [ ... 'channels', ] After installing the necessary applications I went to the next step in the tutorial that's testing this on the shell. In [1]: import channels.layers In [2]: from asgiref.sync import async_to_sync In [3]: async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'}) --------------------------------------------------------------------------- NameError Traceback (most recent call last) &lt;ipython-input-3-80e65666e9e2&gt; in &lt;module&gt;() ----&gt; 1 async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'}) NameError: name 'channel_layer' is not defined In [4]: channel_layer = channels.layers.get_channel_layer() In [5]: async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'}) --------------------------------------------------------------------------- TimeoutError Traceback (most recent call last) &lt;ip…
type: UnansweredQuestion
tagged with: django-channels
tagged with: django
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/66983892

http://stackoverflow.com/a/52368583
score: 1
answers question: http://stackoverflow.com/q/50593538
upvote count: 1
has body: This is essentially the same question as python multiprocessing on windows, if __name__ == &quot;__main__&quot; Since Windows has no fork, the multiprocessing module starts a new Python process and imports the calling module. Without __name__ == __main__ idiom the new process (started by keras' fit_generator()) will call your all code again and will start another process, and so on ad infinitum (until OOM). You have to put the initial code into main and the multiprocessing part outside.
type: Answer
downvote count: 0

http://stackoverflow.com/a/50656470
downvote count: 0
has body: Your input is a single item mapping, with as value a list of single item mappings. Your output is a a list of single item mappings. That list is ordered in the same way the keys of the original mappings appear. This indicates that gathering that information should be done using a list or OrderedDict The corresponding values of those mappings is a list of original values for the keys of those mappings, also in the order they appear, but which at least partly repeat in the original, not in the target. Since the order needs preserving, a set (which would automatically filter doubles), cannot be used. Instead a list could be used, which requires checking of an item already being in the list. However in the following I use another OrderedDict, abused as "OrderedSet" by not looking at the values. The input is assumed to be in the file input.yaml: import sys import pathlib from collections import OrderedDict import ruamel.yaml yaml_file = pathlib.Path('input.yaml') yaml = ruamel.yaml.YAML() yaml.default_flow_style = None data = yaml.load(yaml_file) indexed = OrderedDict() for elem in data['index']: for k in elem: # just one each single_item_map = indexed.setdefault(k, OrderedDict()) single_item_map[elem[k]] = None # arbitrary value, unused l = [] for elem in indexed: l.append({elem: [k for k in indexed[elem]]}) data['index'] = l yaml.dump(data, sys.stdout) which gives: index: - BANKNIFTY_O_C_0_09_W: [books, trends, trades, relations] - BANKNIFTY_O_P_0_09_W: [books, trends, trades, negrelations] - BANKNIFTY_O_C_0_10_W: [books, trends, trades, relations, options_banknifty_weekly] - BANKNIFTY_O_P_0_10_W: [books, trends, trades, negrelations] - BANKNIFTY_F_0: [books, trends, trades, relations] - NIFTY_F_0: [books, trends, trades, relations] The yaml.default_flow_style=None is necessary as by default an instance YAML() will use block style, whereas your output has flow style on the leaf-nodes. More fine tuned control is possible in ruamel.yaml by not making "normal" dicts and l…
has comment: http://stackoverflow.com/comment/88322988
type: Answer
answers question: http://stackoverflow.com/q/50647450
accepted answer of: http://stackoverflow.com/q/50647450
upvote count: 1
has comment: http://stackoverflow.com/comment/88352449
score: 1
has comment: http://stackoverflow.com/comment/88341716
type: AcceptedAnswer

http://stackoverflow.com/a/50630725
downvote count: 0
has body: With groupby shift, create the subgroup of each person by the place changes, if it change more than twice , then we should not keep the whole group in the new dataframe s=df.groupby('person').apply(lambda x : (x['place'].shift()!=x['place']).cumsum().nunique()) df.loc[df.person.isin(s[s&lt;=2].index)] place other_stuff person 0 home f a 1 home g a 2 home d a 3 home q a 4 office w a 5 office r a 6 office s a 7 home t b 8 office u b
type: Answer
upvote count: 5
accepted answer of: http://stackoverflow.com/q/50630569
answers question: http://stackoverflow.com/q/50630569
has comment: http://stackoverflow.com/comment/88274481
score: 5
type: AcceptedAnswer

http://stackoverflow.com/q/50666427
tagged with: modelform
type: Question
has comment: http://stackoverflow.com/comment/88342758
has answer: http://stackoverflow.com/a/50666463
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/21164798
type: UnansweredQuestion
has title: Trying to create new object by HTML Form, Django,. HttpResponse object. It returned None instead
tagged with: http://stackoverflow.com/tag/html
has body: I am trying to create a new object Book using HTML form but I get HttpResponse None. I find almost the same case here: Django ModelForm with foreign key but my code still doesn't work. I can't find what is wrong. models.py class Author(models.Model): """ Author's class - defines an book's author """ name = models.CharField(max_length=140) def __str__(self): return self.name class Book(models.Model): """ Book class - defines a book """ title = models.CharField(max_length=140) author = models.ForeignKey("Author", on_delete=models.CASCADE) read = models.BooleanField(default=False) forms.py class BookForm(forms.ModelForm): title = forms.CharField(max_length=200) author = forms.ModelChoiceField(queryset=Author.objects.all()) class Meta: model = Book fields = ["title", "author", "read"] class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ["name"] books.html {% csrf_token %} Add New Book views.py def books(request): if request.method == 'POST': form = BookForm(request.POST or None) if form.is_valid(): form.save(commit=True) all_books = Book.objects.all all_authors = Author.objects.all return render(request, 'books.html', {'all_books': all_books, 'all_authors':all_authors}) else: all_books = Book.objects.all all_authors = Author.objects.all return render(request, 'books.html', {'all_books': all_books, 'all_authors':all_authors}) I guess something is wrong with views.py or books.html. I read a big part of Django documentation but still doesn't find an answer that will help me in my case.
tagged with: django
tagged with: python
tagged with: request
has comment: http://stackoverflow.com/comment/88342781

http://stackoverflow.com/comment/88209446
comment on: http://stackoverflow.com/a/50599773
score: 0
type: Comment
has text: @sayansen - oops, it was my typo, need `transform`
type: AnswerComment

http://stackoverflow.com/a/50682930
has comment: http://stackoverflow.com/comment/88378544
type: Answer
has comment: http://stackoverflow.com/comment/88474217
has comment: http://stackoverflow.com/comment/88376193
has comment: http://stackoverflow.com/comment/88385910
score: 1
has body: First you have to run the script as Administrator if you use .connect(...). I've already added warning about that and error in the .click() method when target process has higher privileges. See pull request #499. It will be included into coming pywinauto==0.6.5. There is one more method: .click_input() moves mouse cursor and performs real click. While .click() just sends WM_CLICK window message (might be useful for minimized or non-active window). P.S. By the way, for Outlook I'd recommend using Application(backend="uia") and you'll have no Win32 API specific problems. See Getting Started Guide about backends difference.
upvote count: 1
answers question: http://stackoverflow.com/q/50682448
has comment: http://stackoverflow.com/comment/88411677
has comment: http://stackoverflow.com/comment/88413926
has comment: http://stackoverflow.com/comment/88496368
has comment: http://stackoverflow.com/comment/88376492
downvote count: 0
has comment: http://stackoverflow.com/comment/88376549

http://stackoverflow.com/comment/88324970
comment on: http://stackoverflow.com/q/50657434
has text: @Mr.T, yeah but then always will have the same order of unorderedness
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/50590684
score: 6
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/50590536
accepted answer of: http://stackoverflow.com/q/50590536
has comment: http://stackoverflow.com/comment/88191671
has body: Your encoder is defined as a model that takes inputs inputs and gives outputs [z_mean, z_log_var, z]. You then define your decoder separately to take some input, here called latent_inputs, and output outputs. Finally, your overall model is defined in the line that states: outputs = decoder(encoder(inputs)[2]) This means you are going to run encoder on your inputs, which yields [z_mean, z_log_var, z], and then the third element of that (call it result[2]) gets passed in as the input argument to decoder. In other words, when you implement your network, you are setting latent_inputs equal to the third output of your encoder, or [z_mean, z_log_var, z][2] = z. You could view it as (probably not valid code): encoder_outputs = encoder(inputs) # [z_mean, z_log_var, z] outputs = decoder(latent_inputs=encoder_outputs[2]) # latent_inputs = z
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/50687968
type: Answer
has comment: http://stackoverflow.com/comment/88386163
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88386157
has body: You need the indices of the rows where your condition is met. You can convert series to numeric, which would turn string into NaN, then look for your condition and simply remove the row. Note that we are not saving the series with NaN back to the dataframe. ser = pd.to_numeric(df['A'], errors='coerce') df.loc[df['A']!='abc'].drop(list(ser[ser&lt;=-1].index)) Output: A B C 0 1.0 abc 1.0
answers question: http://stackoverflow.com/q/50687882
score: 0

http://stackoverflow.com/comment/88390982
has text: First get this working with just finding a single index. Then, add code at the end of the function that (if the value was found—otherwise just return `[-1]` or whatever) builds a list by extending out left and right from that index until the value no longer matches.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50690549
score: 0

http://stackoverflow.com/q/50573394
tagged with: quandl
has comment: http://stackoverflow.com/comment/88156447
tagged with: python
has body: I'm working on a script to retreive data from Quandl which manipulates the data before saving. I'm stuck on 1 step which is id like to reorder my columns using pandas like df = df'Code','Date','Open','High','Low','Close','Volume' or in simpler terms, swap date with Code I thought this was because the system is auto setting Date as an index, however the traceback says ['Date'] not in index I have observed that the date label drops out of the dataframe when df.index = df.index.strftime('%Y%m%d'), Print 2 output. If I comment this line out the error code persists. I tried inserting df.set_index('Code') to see if changing the index would help but did not. Does anyone know what the issue is here? Code myArr = ['CHRIS/CME_AD1'] cDate=int(time.strftime("%Y%m%d")) # get quandl data, edit dataframe &amp; save to csv for qCode in myArr: data = qdl.get(qCode, start_date=StartDate) df = pd.DataFrame(data) # df.to_dict() qID=(str(qCode[qCode.find('/')+1:])) print(df) # format data &amp; save df.insert(loc=0, column='Code', value=qID) df=df.drop(columns=['Change','Settle','Previous Day Open Interest']) df.rename(columns={'Last':'Close'}, inplace=True) df.index = df.index.strftime('%Y%m%d') print(df) df = df'Code','Date','Open','High','Low','Close','Volume' #reorder columns df.to_csv(path + qID + '_' + str(cDate) + '.txt', sep=',', index=True, header=1) print('Quandl Download Complete') Traceback Traceback (most recent call last): File "\\progsql\SQL\Script\Python\EOD_Quandl - Copy.py", line 29, in &lt;module&gt; df = df'Code','Date','Open','High','Low','Close','Volume' #reorder columns File "C:\Python35\lib\site-packages\pandas\core\frame.py", line 2679, in __getitem__ return self._getitem_array(key) File "C:\Python35\lib\site-packages\pandas\core\frame.py", line 2723, in _getitem_array indexer = self.loc._convert_to_indexer(key, axis=1) File "C:\Python35\lib\site-packages\pandas\core\indexing.py", line 1327, in _convert_to_indexer .format(mask=objarr[mask])) KeyError…
has answer: http://stackoverflow.com/a/50653054
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50653054
upvote count: 0
has title: pandas dataframe won't reorder columns
possible better answer: http://stackoverflow.com/a/50573812
downvote count: 1
type: Question
tagged with: dataframe
score: -1
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/50573812
favorite count: 0

http://stackoverflow.com/comment/88141678
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50565488
type: Comment
has text: Sorry I do not understand. Do you mean `print(d)`?

http://stackoverflow.com/q/50615626
upvote count: 1
type: Question
has title: Level Order Traversal BST Code
downvote count: 0
favorite count: 0
tagged with: binary-search-tree
type: UnansweredQuestion
tagged with: python
has body: I was wondering if someone can review my code for level order traversal in a BST. I am suppose to have [[3],[9,20],[15,7]] but instead I get [[3],[9],[20],[15],[7]] I know I need an outer while loop but, not sure how to construct it. # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None import queue class Solution(object): def levelOrder(self, root): L = queue.Queue() local = [] L.put(root) while not L.empty(): node = L.get() local.append([node.val]) if(node.left): L.put(node.left) if(node.right): L.put(node.right) return local
answer count: 0
score: 1

http://stackoverflow.com/comment/88111769
has text: I suspect that you switched between latitude and longitude. Because the location is in remote South Atlantic.
type: QuestionComment
comment on: http://stackoverflow.com/q/50545802
type: Comment
score: 0

http://stackoverflow.com/q/50578714
has answer: http://stackoverflow.com/a/50579079
has comment: http://stackoverflow.com/comment/88167121
has comment: http://stackoverflow.com/comment/88168410
tagged with: python
has title: Index out of bounds error : Python
has comment: http://stackoverflow.com/comment/88166553
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/50579417
has comment: http://stackoverflow.com/comment/88168750
type: Question
upvote count: 2
tagged with: numpy
has comment: http://stackoverflow.com/comment/88168254
has comment: http://stackoverflow.com/comment/88168607
has body: I have a set of data that is not smooth. Hence I'm trying to interpolate it with the generated mesh. import numpy as np data=np.loadtxt('test.txt') x=data[:,0] #len(x) = 730 y=data[:,1] Nx= len(x) Ny=len(y) del_x= 0.5 xn = np.linspace(0,Nx,2000) yn = np.linspace(0,Ny,2000) #loop for i in range(0,Nx-1): if x[i] &gt; xn[i] and x[i] &lt; xn[i+1]: new_x= (i + (xn[i] - x[i])/(xn[i]-xn[i+1]))*del_x print new_x I would like to perform the loop that basically does the operation i.e : if my original data x[i] is in between the two grid points xn[i],xn[i+1], then compute new_x. But I get the following error Traceback (most recent call last): File "new.py", line 27, in &lt;module&gt; if x[i] &gt; xn[i] and x[i] &lt; xn[i+1]: IndexError: index out of bound Can someone help me out ?
has answer: http://stackoverflow.com/a/50579417
has comment: http://stackoverflow.com/comment/88167147
has comment: http://stackoverflow.com/comment/88166747
has answer: http://stackoverflow.com/a/50579355
has comment: http://stackoverflow.com/comment/88167077
has answer: http://stackoverflow.com/a/50579129
linked to: http://stackoverflow.com/q/18691084
downvote count: 1
has comment: http://stackoverflow.com/comment/88166890
answer count: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/88166964
possible better answer: http://stackoverflow.com/a/50579079

http://stackoverflow.com/q/50584212
tagged with: poisson
upvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50589882
accepted answer: http://stackoverflow.com/a/50589882
has title: agents arrival according to poisson process
has body: I am trying to achieve agents arrival in my model according to a poisson process. I know from data that on average 230 agents arrive per day (or 9.583 agents/hr or 0.1597/minute). In the simulations, now I need to use this information to add agents. One simulation time step is equal to 5 minutes (real time) and if if we calculate from data, then on average 0.7986 agents should be added to simulation every time step to achieve an average of 230 per day. But how could I do this? I cannot use 0.7986 per time step because I need integer number to add agent. If I round off 0.7986 to 1, then I over estimate this. It is clear that we cannot add agent every time step but I have no clue how to select a time step in which an agent must be added. If I know which time step I need to select to add an agent, I can do that easily. Does any one know how to do this in Python? I tried the below code but cannot really understand what it is actually for i in range(1,12): # 1 simulation time step is equal 5min, so this loops covers 1 hour. time=int(random.expovariate(1/0.7986)) I do not really understand the above code as it produces quite different numbers. Any help please.
tagged with: python
downvote count: 0
type: Question
type: AnsweredQuestion
tagged with: agent-based-modeling
score: 1

http://stackoverflow.com/comment/88950676
type: Comment
type: QuestionComment
has text: related: https://stackoverflow.com/questions/46528343/how-to-use-gcp-cloud-sql-as-dataflow-source-and-or-sink-with-python
comment on: http://stackoverflow.com/q/50630372
score: 0

http://stackoverflow.com/a/50663219
type: Answer
answers question: http://stackoverflow.com/q/50663198
has comment: http://stackoverflow.com/comment/88336564
has comment: http://stackoverflow.com/comment/88336504
has comment: http://stackoverflow.com/comment/88336483
has comment: http://stackoverflow.com/comment/88336713
has comment: http://stackoverflow.com/comment/88336602
has comment: http://stackoverflow.com/comment/88336672
has body: from collections import Counter c = dict(Counter(long_list_with_duplicates)) print(c)
has comment: http://stackoverflow.com/comment/88336588
score: 0
has comment: http://stackoverflow.com/comment/88336543
has comment: http://stackoverflow.com/comment/88336605

http://stackoverflow.com/q/50683716
tagged with: capitalization
has comment: http://stackoverflow.com/comment/88377287
downvote count: 1
type: Question
upvote count: 4
has title: How to avoid capitalised acronyms and abbreviations from being lowercased by .capitalize()? Python
has comment: http://stackoverflow.com/comment/88377205
accepted answer: http://stackoverflow.com/a/50683802
answer count: 1
tagged with: string
has body: Capitalising the first letter of a sentence using .capitalize() works fine. Except when the first word of the sentence is an acronym like 'IBM' or 'SIM', which get lowercased (except for the first letter). For example: L = ["IBM", "announced", "the", "acquisition."] L = [L[0].capitalize()] + L[1:] L = " ".join(L) print(L) gives: "Ibm announced the acquisition." But I would like this: "IBM announced the acquisition." Is there a way to avoid this - e.g. by skipping acronyms - while still outputting capitalised sentences like below? "IBM's CEO announced the acquisition." "The IBM acquisition was announced."
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88377191
tagged with: python
has comment: http://stackoverflow.com/comment/88377184
has answer: http://stackoverflow.com/a/50683802
has comment: http://stackoverflow.com/comment/88377224
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/88377259

http://stackoverflow.com/comment/88394758
type: QuestionComment
has text: 4. make a pandas dataframe based on your data?
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50692100

http://stackoverflow.com/comment/88218480
comment on: http://stackoverflow.com/q/50604349
has text: @Hamidreza - Basically - I want to show how efficient the machine is? Any idea how can I represent it?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50616439
type: Question
has title: Python: Array search improvement
answer count: 1
tagged with: arrays
score: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50616514
tagged with: list
accepted answer: http://stackoverflow.com/a/50616514
has body: New to python and I don't fully get a way to improve this better (Even if I know this is not the right way to do this). I have a list of elements with this format: HIGH-CPU, MID-GPU, HIGH-RAM There are 27 possible combinations, for each combination I want to add to a pandas dataframe a family combination as a new value. IE: For HIGH-CPU, MID-GPU, HIGH-RAM will be Family 1. This is what I have and works, but it should be simpler specially if tomorrow I have to add more possible combinations: def match_list(row): fam_list = "" tomatch = row ##This CSV contains the possible 27 combinations said above. result = pd.read_csv("family_list.csv") for row in result : if tomatch == "HIGH-CPU, MID-GPU, HIGH-RAM": fam_list = "Family 1" elif tomatch == "HIGH-CPU, MID-GPU, MID-RAM": fam_list = "Family 2" elif tomatch == "HIGH-CPU, MID-GPU, LOW-RAM": fam_list = "Family 3" elif tomatch == "HIGH-CPU, HIGH-GPU, HIGH-RAM": fam_list = "Family 4" elif tomatch == "HIGH-CPU, HIGH-GPU, MID-RAM": fam_list = "Family 5" elif tomatch == "HIGH-CPU, HIGH-GPU, LOW-RAM": fam_list = "Family 6" elif tomatch == "HIGH-CPU, LOW-GPU, HIGH-RAM": fam_list = "Family 7" elif tomatch == "HIGH-CPU, LOW-GPU, MID-RAM": fam_list = "Family 8" elif tomatch == "HIGH-CPU, LOW-GPU, LOW-RAM": fam_list = "Family 9" elif tomatch == "MID-CPU, MID-GPU, HIGH-RAM": fam_list = "Family 10" elif tomatch == "MID-CPU, MID-GPU, MID-RAM": fam_list = "Family 11" elif tomatch == "MID-CPU, MID-GPU, LOW-RAM": fam_list = "Family 12" elif tomatch == "MID-CPU, HIGH-GPU, HIGH-RAM": fam_list = "Family 13" elif tomatch == "MID-CPU, HIGH-GPU, MID-RAM": fam_list = "Family 14" elif tomatch == "MID-CPU, HIGH-GPU, LOW-RAM": fam_list = "Family 15" elif tomatch == "MID-CPU, LOW-GPU, HIGH-RAM": fam_list = "Family 16" elif tomatch == "MID-CPU, LOW-GPU, MID-RAM": fam_list = "Family 17" elif tomatch == "MID-CPU, LOW-GPU, LOW-RAM": fam_list = "Family 18" elif tomatch == "LOW-CPU, MID-GPU, HIGH-RAM": fam_list = "Family 19" elif tomatch == "LOW-CPU, MID-G…

http://stackoverflow.com/comment/88406215
type: Comment
has text: Yes. After segmenting into sentences you should segment each sentence into words. I tried now. I can provide the solution if you post a new question, since posting a different answer here is a kind of a mess.
comment on: http://stackoverflow.com/a/50666007
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88201289
has text: Example :- Original County Choloropleth Map Hover Text County: xx State:xx FIPS:xx Value:xx Expected County Choloropleth Map Hover Text County : xx Attribute 1 :Value 1 Attribute 2 :Value 2
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50584924

http://stackoverflow.com/comment/88125345
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50557233
has text: While requests for links to external resource (like Python source code) are off-topic, you might find [this lecture](https://www.youtube.com/watch?v=ix6MTSemdUU) entertaining.
score: 0

http://stackoverflow.com/q/50586834
has body: I have a pandas dataframe containing a bunch of words describing professions in a language that I do not know (it could be english, dutch, german...whatever). The list of words might contain errors. import pandas df = pandas.DataFrame(data=['teacer','leraar','insegniaante','designer'],columns = ['professions']) What I would like to do is: To search in google image for the word, take the first image download the first tags associated In short I would like to use google image to rename my original set of words taking advantage of the ability of google of ignoring the spelling mistakes when looking for images. Is that possible? Could you help me in building such script?
tagged with: pandas
has title: using google image to convert list of words in python
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/50586941
type: UnansweredQuestion
tagged with: google-api
downvote count: 1
score: -1
type: Question
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/88333575
comment on: http://stackoverflow.com/a/50661706
type: AnswerComment
has text: something like adobe after effects or something similar. In such programs it is much easier to work with images.
score: 0
type: Comment

http://stackoverflow.com/q/50543965
tagged with: plot
has title: Scatter Plot on Mapbox in Python error message
downvote count: 0
answer count: 0
score: 1
tagged with: plotly
has body: I am trying to create this Scatter Plot on Mapbox in Python. Even with my access token in the script, I receive: PlotlyRequestError: No message. My following code is below.... This is also done on Kaggle's kernal. import plotly.plotly as py import plotly.graph_objs as go mapbox_access_token = 'pk.eyJ1IjoiamFtZXNwOTkiLCJhIjoiY2pobmd5aGJxMWdiYzNhcXdpaWVhdzhkbCJ9._o-_ysHz5HG9S49UizQiqQ' #pk.eyJ1IjoiamFtZXNwOTkiLCJhIjoiY2pobmd5aGJxMWdiYzNhcXdpaWVhdzhkbCJ9._o-_ysHz5HG9S49UizQiqQ data = [ go.Scattermapbox( lat=['45.5017'], lon=['-73.5673'], mode='markers', marker=dict( size=14 ), text=['Montreal'], ) ] layout = go.Layout( autosize=True, hovermode='closest', mapbox=dict( accesstoken=mapbox_access_token, bearing=0, center=dict( lat=45, lon=-73 ), pitch=0, zoom=5 ), ) fig = dict(data=data, layout=layout) py.iplot(fig, filename='Montreal Mapbox')
type: Question
tagged with: token
upvote count: 1
favorite count: 0
tagged with: mapbox
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/88376246
type: Comment
has text: I tried like you advised and I'm still getting MemmoryError. Is this Ram related or some other error? I did quite some Googling but I feel kinda lost..
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50682787

http://stackoverflow.com/comment/88140398
comment on: http://stackoverflow.com/q/50564390
type: Comment
type: QuestionComment
score: 0
has text: @eyllanesc no error from cmd

http://stackoverflow.com/q/50566934
favorite count: 0
linked to: http://stackoverflow.com/q/8309902
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88143905
has answer: http://stackoverflow.com/a/56636632
has comment: http://stackoverflow.com/comment/88143879
linked to: http://stackoverflow.com/q/31875
has answer: http://stackoverflow.com/a/50567397
has comment: http://stackoverflow.com/comment/88144323
answer count: 5
accepted answer: http://stackoverflow.com/a/50567397
tagged with: multithreading
linked to: http://stackoverflow.com/q/489720
linked to: http://stackoverflow.com/q/6760685
has answer: http://stackoverflow.com/a/78563614
tagged with: python
has comment: http://stackoverflow.com/comment/88143940
upvote count: 16
has comment: http://stackoverflow.com/comment/88143842
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/55629949
has comment: http://stackoverflow.com/comment/88144357
score: 16
has comment: http://stackoverflow.com/comment/88144177
type: Question
has comment: http://stackoverflow.com/comment/88144113
has body: 1. The @Singleton decorator I found an elegant way to decorate a Python class to make it a singleton. The class can only produce one object. Each Instance() call returns the same object: class Singleton: """ A non-thread-safe helper class to ease implementing singletons. This should be used as a decorator -- not a metaclass -- to the class that should be a singleton. The decorated class can define one `__init__` function that takes only the `self` argument. Also, the decorated class cannot be inherited from. Other than that, there are no restrictions that apply to the decorated class. To get the singleton instance, use the `Instance` method. Trying to use `__call__` will result in a `TypeError` being raised. """ def __init__(self, decorated): self._decorated = decorated def Instance(self): """ Returns the singleton instance. Upon its first call, it creates a new instance of the decorated class and calls its `__init__` method. On all subsequent calls, the already created instance is returned. """ try: return self._instance except AttributeError: self._instance = self._decorated() return self._instance def __call__(self): raise TypeError('Singletons must be accessed through `Instance()`.') def __instancecheck__(self, inst): return isinstance(inst, self._decorated) I found the code here: Is there a simple, elegant way to define singletons? The comment at the top says: [This is] a non-thread-safe helper class to ease implementing singletons. Unfortunately, I don't have enough multithreading experience to see the 'thread-unsafeness' myself. &nbsp; 2. Questions I'm using this @Singleton decorator in a multithreaded Python application. I'm worried about potential stability issues. Therefore: Is there a way to make this code completely thread-safe? If the previous question has no solution (or if its solution is too cumbersome), what precautions should I take to stay safe? @Aran-Fey pointed out that the decorator is badly coded. Any improvements are of course very much appre…
tagged with: python-3.6
has answer: http://stackoverflow.com/a/74175261
tagged with: singleton
has answer: http://stackoverflow.com/a/55629949
downvote count: 0
has title: Why is this singleton implementation "not thread safe"?

http://stackoverflow.com/comment/88383881
score: 0
type: Comment
type: QuestionComment
has text: please create a [mcve] instead of just disjointed blocks of code. You also need to show the `AutoScroll` class, or show us where you're importing it from.
comment on: http://stackoverflow.com/q/50686913

http://stackoverflow.com/comment/88315658
type: Comment
comment on: http://stackoverflow.com/a/50651851
type: AnswerComment
has text: Okay, that's all I was asking. Genuine question ;-)
score: 0

http://stackoverflow.com/a/50687485
has comment: http://stackoverflow.com/comment/88384795
type: Answer
has comment: http://stackoverflow.com/comment/88395300
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/50685384
accepted answer of: http://stackoverflow.com/q/50685384
has body: Short answer - No A longer answer - DICOM standard does not care in any way or form, how the files are stored on the PACS server, that's left up to the implementation. The PACS server could use a robotic carving tool to engrave them on stone tablets and read the with OCR, if it could still receive and send them out according to the standard. Therefore there is no way to influence such details through the DICOM interface. From the standard's viewpoint - everything is already neatly organised hierarchically on the scale of Patient - Study - Series - Instance, where each levels has their only unique ID-s. These ID-s are stored in each and every DICOM file in the relevant DICOM tags and most PACS servers keep track of these ID-s using a database to facilitate quick lookups. The actual location of the DICOM file on the disk is also stored in the database, but that is internal implementation details and is not exposed via the DICOM interface. And frankly - I don't see what's the use case for this requirement anyway? The organisation is there already and You can query by these attributes using the DICOM interface.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88120777
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50554945
type: Comment
has text: The initial question was the same, just the later edits made it more clear

http://stackoverflow.com/comment/88203537
type: Comment
has text: The data-set I am having currently doesn't have any y. i.e. no output labels(its a clustering problem). So in that scenario, how to use this solution???
comment on: http://stackoverflow.com/a/50589208
type: AnswerComment
score: 0

http://stackoverflow.com/a/50570868
answers question: http://stackoverflow.com/q/50570808
has body: You have sparse_categorical_crossentropy which expects just the integer labels of classes whereas you give encoded versions already (18,). As such, you need to change loss='categorical_crossentropy' to fix the problem.
upvote count: 3
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 3
accepted answer of: http://stackoverflow.com/q/50570808

http://stackoverflow.com/a/50670097
has body: Modifying process.env alters environment variables for the current process and (optionally) child processes. So, unless you are starting your Python script from the Node.js app, environment variables set in the Node.js app wouldn't be accessible from Python script. EDIT: PythonShell accepts second parameter options, which you can use to propagate environment variables down to the child process. var pyshell = new PythonShell(myPythonScriptPath, { env: process.env, });
has comment: http://stackoverflow.com/comment/88349999
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50669874
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50669874
score: 3

http://stackoverflow.com/q/50676725
accepted answer: http://stackoverflow.com/a/50676845
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: list
type: Question
has body: I have a list of lists. For example, [ [1, 2, 0.10], [1, 3, 0.22], [1, 4, 0.20], [1, 5, 0.37], [1, 8, 0.60], [1, 10, 0.01], [1, 15, 0.26], [2, 3, 0.28], [2, 6, 0.12], [2, 7, 0.72], [2, 10, 0.77], [2, 11, 0.36], ... ] I want to sort the list of lists by the first item of the sub-list then by the third item, and get top three result of each first item, how to do that? thanks! result example, [ [1, 15, 0.26], [1, 5, 0.37], [1, 8, 0.60], [2, 11, 0.36], [2, 7, 0.72], [2, 10, 0.77], ... ]
downvote count: 4
has title: How to sort a list of lists by the first item of the sub-list then by the third item
tagged with: sorting
has comment: http://stackoverflow.com/comment/88363228
favorite count: 0
has comment: http://stackoverflow.com/comment/88365389
answer count: 1
has answer: http://stackoverflow.com/a/50676845
score: -3

http://stackoverflow.com/q/50561162
has answer: http://stackoverflow.com/a/50561218
tagged with: python
has answer: http://stackoverflow.com/a/50561423
accepted answer: http://stackoverflow.com/a/50561423
score: 2
type: AnsweredQuestion
has body: I have two dataframes and I need to create a sort of union of these two dataframes(of the first column 'A'). df1 = pd.DataFrame({'A' : ['a','b','c'], 'B' : [10,20,30], 'C' : [2,5,3]}) df2= pd.DataFrame({'A' : ['a','b','d'], 'B' : [34,21,45], 'C' : [1,5,5]}) output- A f_M d_M f_B d_B 0 a 10 2 34 1 1 b 20 5 21 5 2 c 30 3 0 0 3 d 0 0 45 5 This is the new dataframe created which has the union of two dataframes of column('A').The f_M column is if 'B'column has value in the df1 and f_B is for if it is in df2 and 0 if not in any of the df1/df2.
type: Question
has comment: http://stackoverflow.com/comment/88132793
tagged with: dataframe
upvote count: 2
answer count: 2
tagged with: pandas
downvote count: 0
possible better answer: http://stackoverflow.com/a/50561218
favorite count: 0
has title: Taking the union of two dataframes and add the resp column separately

http://stackoverflow.com/comment/88400906
has text: You could just do `''.join([i for i in String if i in string.ascii_letters])`
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50695819
score: 0

http://stackoverflow.com/comment/88304469
type: AnswerComment
comment on: http://stackoverflow.com/a/50646879
type: Comment
has text: It was just an example, he asked for a method
score: 0

http://stackoverflow.com/comment/88322050
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50655975
has text: Yes, that was the problem. Two lengths of the small triangle fit into one length of the bigger triangle. The code can be simpler if you completely remove the code from `if a == 0`, because it works without it as well ;) Otherwise, it looks fine to me.

http://stackoverflow.com/comment/88127126
has text: How can i vectorise the problem if the data is processed in groups? thanks
comment on: http://stackoverflow.com/q/50558108
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88333606
score: 0
type: Comment
has text: User agent and another extra fields are best practice for web scraping. Keep in mind.
type: AnswerComment
comment on: http://stackoverflow.com/a/50661742

http://stackoverflow.com/comment/88203035
has text: What's the desired output?
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50596895
type: Comment

http://stackoverflow.com/comment/88231986
comment on: http://stackoverflow.com/q/50609790
type: Comment
type: QuestionComment
score: 1
has text: @Aaron Python also has to ask the OS to create/open files, make network connections, write text to the terminal, etc. By your logic, "pure Python" can hardly do anything by itself.

http://stackoverflow.com/q/50560521
has title: Django 2.0 using views.py to render a html page (TemplateDoesNotExist)
tagged with: django
type: Question
has answer: http://stackoverflow.com/a/50560560
score: 3
upvote count: 3
answer count: 1
favorite count: 0
tagged with: python
has body: still learning the basics of Django and I'm struggling a little. Right now I'm trying to create a home page for my site. The project name is 'meal_planner' and the app is 'meal_plans'. meal_planner/urls.py contains this code: from django.conf.urls import include, url from django.contrib import admin from django.urls import path urlpatterns = [ # url(r'', include('meal_plans.urls', namespace='meal_plans')) path('', include('meal_plans.urls', namespace='meal_plans')) ] meal_plans/urls.py contains this code: """Define URL patterns for meal_plans""" from django.conf.urls import url from . import views app_name = 'meal_plans' urlpatterns = [ # Home page url(r'^$', views.index, name='index') ] and meal_plans/views.py contains this code: from django.shortcuts import render # Create your views here. def index(request): """Homepage""" return render(request, 'main\index.html') The error I'm getting is TemplateDoesNotExist at / main\index.html Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: ...\meal_planner\mp\lib\site-packages\django\contrib\admin\templates\main\index.html (Source does not exist) django.template.loaders.app_directories.Loader: ...\meal_planner\mp\lib\site-packages\django\contrib\auth\templates\main\index.html (Source does not exist) I've tried searching on how to do this but I just can't get it right. Any help is appreciated.
accepted answer: http://stackoverflow.com/a/50560560
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/a/50570529
answers question: http://stackoverflow.com/q/50570334
type: Answer
has body: def rotation(N): return [N[i:] + N[:i] for i in range(len(N))] K = [1, 9, 7] print(rotation(K))
has comment: http://stackoverflow.com/comment/88155178
has comment: http://stackoverflow.com/comment/88155143
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88155217
upvote count: 1

http://stackoverflow.com/q/50662971
upvote count: 1
has answer: http://stackoverflow.com/a/50664814
has body: I have to insert 10 million documents in CouchDB localhost. I have used a python script to create random data in this format: { "docs": [ {"_id": "0", "integer": 0, "string": "0"}, {"_id": "1", "integer": 1, "string": "1"}, {"_id": "2", "integer": 2, "string": "2"} ] } The size of the file is 1.5 GB as I have 10 key-value pairs in each document. I am using this command to load the json file: curl -d @db.json -H "Content-type: application/json" -X POST http://127.0.0.1:5984/new/_bulk_docs For 100,000 documents it tool 10-15 seconds to load, but for 10,000,000 it didn't even load in 12 hours. Any help on how can I bulk insert in couchDB will be appreciated. TIA
type: UnansweredQuestion
downvote count: 0
has title: How to insert millions of documents in couchDB through curl?
score: 1
tagged with: couchdb
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50664039
tagged with: python
linked to: http://stackoverflow.com/q/8290397
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/q/50670271
has body: Let's suppose we want to create a loop function with billion iterations. if we use for i in range(0, 1000000000) in Python 2 it would create a LIST with billion data members, which takes a lot of space. By using for i in xrange(0, 1000000000), in Python 2 it doesn't create a list, but selects one index at a time. in PYTHON 3, there is no xrange(), and range() works in either case. How can we save space in Python 3 in this case?
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/88350294
has comment: http://stackoverflow.com/comment/88350301
type: Question
linked to: http://stackoverflow.com/q/15014310
has title: range() & xrange() in Python 3
score: 0
duplicate of: http://stackoverflow.com/q/15014310

http://stackoverflow.com/q/50650250
has body: So I have written a code that generates a random list with random number of values. Then asks the user what number the user is looking for and if its in the list, it will tell the user what position in the list the number is in. import random a = [random.randint(1, 20) for i in range(random.randint(8, 30))] a.sort() print(a) def askUser(): n = input("What number are you looking for?") while not n.isdigit(): n = input("What number are you looking for?") n = int(n) s = 0 for numbers in a: if numbers == n: s += 1 print("Number", n, "is located in the list and the position is:", (a.index(n)+1)) # Something here to skip this index next time it goes through the loop else: pass if s == 0: print("Your number could not be found") askUser() I would like to add something that will skip the index it found first time and then look for the index of the duplicate if there is one. Current result [2, 4, 8, 9, 10, 10, 16, 19, 20, 20] What number are you looking for?20 Number 20 is located in the list and the position is: 9 Number 20 is located in the list and the position is: 9 Desired result [2, 4, 8, 9, 10, 10, 16, 19, 20, 20] What number are you looking for?20 Number 20 is located in the list and the position is: 9 Number 20 is located in the list and the position is: 10
has title: Checking duplicates in list from user input
accepted answer: http://stackoverflow.com/a/50650288
possible better answer: http://stackoverflow.com/a/50650498
downvote count: 0
has answer: http://stackoverflow.com/a/50650498
favorite count: 0
has comment: http://stackoverflow.com/comment/88311513
tagged with: python-3.x
upvote count: 2
tagged with: input
tagged with: python
answer count: 4
score: 2
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/50650326
has answer: http://stackoverflow.com/a/50650288
type: Question
has answer: http://stackoverflow.com/a/50650378

http://stackoverflow.com/comment/88342339
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50665760
type: Comment
has text: @Zoozoo - But still it depends of number of movies, if larger data it should be slow or another performance problems.

http://stackoverflow.com/q/50627048
tagged with: python
tagged with: depth-first-search
accepted answer: http://stackoverflow.com/a/50627359
type: AnsweredQuestion
score: 1
has body: I was following Tushar Roy's video on detecting cycles in directed graphs. I understand the use of the white, gray and black sets to detect the cycle but the main thing that I don't understand is how as we check for the length of the white set, next(iter(white)) would know where to go next since the set size has changed. The documentation says that iter gives you an iterator object and next would retrieve the next item. Is the main point that the iterator is evaluated differently each time? You can find the code here or here. def has_cycle(graph): white = set() gray = set() black = set() for vertex in graph.all_vertex.values(): white.add(vertex) while len(white) &gt; 0: current = next(iter(white)) if dfs(current, white, gray, black) == True: return True return False def dfs(current, white, gray, black): move_vertex(current, white, gray) for neighbor in current.adjacent_vertices: if neighbor in black: continue if neighbor in gray: return True if dfs(neighbor, white, gray, black) == True: return True move_vertex(current, gray, black) return False def move_vertex(vertex, source_set, destination_set): source_set.remove(vertex) destination_set.add(vertex)
upvote count: 1
type: Question
has title: Python: Detect cycle using next and iter in a diminishing set
has comment: http://stackoverflow.com/comment/88448050
tagged with: iterator
has answer: http://stackoverflow.com/a/50627359
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88293114

http://stackoverflow.com/q/50615848
has comment: http://stackoverflow.com/comment/88241711
has title: python/pandas merge two dataframes if both exist in dataframe
score: 0
linked to: http://stackoverflow.com/q/11976503
tagged with: pandas
tagged with: python
has body: I'm new to python/pandas and I had a question of merging two dataframes together. Consider I had df1: Portfolio Value Date 2016-07-01 100000 2016-07-08 100005 2016-07-15 100010 2016-07-22 100015 2016-07-29 100020 2016-08-05 100025 2016-08-12 100030 2016-08-19 100035 2016-08-26 100040 2016-09-02 100045 2016-09-09 100050 2016-09-16 100055 2016-09-23 100060 2016-09-30 100065 2016-10-07 100070 2016-10-14 100075 2016-10-21 100080 and df2: Portfolio Value 0 100015 1 100030 2 100040 3 100075 I would like to result in a dataframe that keeps the values and date of df1 that also exists in df2 as shown below: newdf: Portfolio Value Date 2016-07-22 100015 2016-08-12 100030 2016-08-26 100040 2016-10-14 100075 I believe that this a merge, but I am not certain. If any other implementation would be better that is fine as well. Any tips would be greatly appreciated! Edit an inner join was attempted as shown in the possible duplicate by the first comment but it does not keep the date index. Is there a way to get the dates with the Portfolio Values to show as well?
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88241679
has comment: http://stackoverflow.com/comment/88241765
type: Question
linked to: http://stackoverflow.com/q/46472172
tagged with: dataframe
duplicate of: http://stackoverflow.com/q/46472172

http://stackoverflow.com/q/50653773
linked to: http://stackoverflow.com/q/35372700
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/88318019
has answer: http://stackoverflow.com/a/73322807
favorite count: 0
has answer: http://stackoverflow.com/a/67708039
type: UnansweredQuestion
tagged with: python
has body: I have been trying to make an OpenCV-Py program to draw rectangle, line, and circle on mouse click and drag. I could successfully do it for line and rectangle but the code for the circle is wrong and I need help with that. import numpy as np import cv2 as cv import math drawing = False # true if mouse is pressed ix,iy = -1,-1 # mouse callback function def draw_circle(event,x,y,flags,param): global ix,iy,drawing if event == cv.EVENT_LBUTTONDOWN: drawing = True ix,iy = x,y elif event == cv.EVENT_MOUSEMOVE: if drawing == True: k = cv.waitKey(33) if k == ord('r'): cv.rectangle(img,(ix,iy),(x,y),(0,255,0),-1) elif k==ord('c'): cv.circle(img,int(((ix+x)/2,(iy+y)/2)),int(math.sqrt( ((ix-x)**2)+((iy-y)**2) )),(0,0,255),-1) elif k== ord('l'): cv.line(img,(ix,iy),(x,y),(255,0,0),5) elif event == cv.EVENT_LBUTTONUP: drawing = False img = np.zeros((512,512,3), np.uint8) cv.namedWindow('image') cv.setMouseCallback('image',draw_circle) while(1): cv.imshow('image',img) k = cv.waitKey(1) &amp; 0xFF if k == 27: break cv.destroyAllWindows() ERROR: Traceback (most recent call last): File "mouse.py", line 19, in draw_circle cv.circle(img,int(((ix+x)/2,(iy+y)/2)),int(math.sqrt( ((ix-x)**2)+((iy-y)**2) )),(0,0,255),-1) TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'
tagged with: opencv
score: 2
has comment: http://stackoverflow.com/comment/88433589
has title: Dynamically draw circle using mouse in openCV
upvote count: 3
tagged with: image-processing
downvote count: 1

http://stackoverflow.com/comment/88401703
type: Comment
comment on: http://stackoverflow.com/a/50692627
score: 0
type: AnswerComment
has text: Some separation of responsibilities? The OP question is agnostic to input style, this can be factored out at least. Eg `label_change(filename: str, old_label: str, new_label: str)`. I think putting this all together teaches bad coding style.

http://stackoverflow.com/q/50611023
has answer: http://stackoverflow.com/a/50628640
has body: I´m using XlsxWriter (version 1.0.2) for creating an Excel file, but when I exporting and opening it, an error is showed: “We found a problem with some content in filename.xlsx. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes.” When I click “Yes” button and after: “Close”, the Excel is opening and all is fine, so I can´t understand why this error is showed. I´m using Python 3.6.4, Django 2.0.1, Microsoft Office 2016, Windows 10 and module IO´s Python. I would like to know how to fix that problem. Added code after comments: def testError(request): data = [["Goal 1", 0, 0], ["1", "Activity 1", "Alex, Peter"], ["1.1", "Activity 1.1", "Matthew"], ["1.1.1", "Activity 1.1.1", "Jhon"]] output = io.BytesIO() workbook = xlsxwriter.Workbook(output, {'in_memory': True}) worksheet = workbook.add_worksheet("Sheet1") bold = workbook.add_format({'bold': True}) title = 'Example' merge_format = workbook.add_format({ 'bold': 1, 'align': 'left', 'valign': 'vcenter'}) worksheet.merge_range('A1:C1', title, merge_format) a = 'B3:D' a += str(len(data)+4) worksheet.add_table(a, {'columns': [{'header': 'No'}, {'header': 'ACTIVITY'}, {'header': 'PARTAKERS'}], 'banded_rows': False, 'banded_columns': False, 'autofilter': 0}) border_format = workbook.add_format({ 'border': 1, 'align': 'left', 'font_size': 10 }) merge_format = workbook.add_format({ 'bold': 1, 'border': 1, 'align': 'left', 'valign': 'vcenter', }) header_format = workbook.add_format({ 'bold': 1, 'align': 'center', 'valign': 'vcenter', }) tab = 'B3:D' tab += str(len(data)+3) worksheet.autofilter(tab) it = 0 countElem = (len(data)) max_width_number = 0 max_width_name = 0 max_width_partaker = 0 for ite in range(3, countElem+3): cel = 'B' cel += str(ite+1) if (data[it][0] != 0 and data[it][1] == 0 and data[it][2] == 0): worksheet.write_row(cel, data[it]) iniCel = cel finCel = 'D' finCel += str(ite+1) mergecel = iniCel+':'+finCel worksheet.merge_range(mergecel, data[it][0], merge_…
has title: Exporting to xlsx using Python and XlsxWriter
tagged with: python
upvote count: 2
downvote count: 2
tagged with: xlsxwriter
accepted answer: http://stackoverflow.com/a/50628640
tagged with: excel
type: AnsweredQuestion
type: Question
score: 0
has comment: http://stackoverflow.com/comment/88232364
answer count: 1
favorite count: 0

http://stackoverflow.com/a/50861665
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/50662485
type: Answer
has body: I worked on your code, and made modifications to make it work. Making a list was not needed. Just put data straight into a dict. The else statements were not needed. You want to keep checking if the new value is larger then the old value, and if so, then make it the new value. Bigcount and bigword both needed to be set to None before the if statement Also, you need a second condition in the if statement if the value is None for the first pass. And moved the print of bigword and bigcount outside the for loop to only print the result one time. One more thing, the assignment says to find all lines with "From ", not lines with "From". See the difference? I hope this helps. name = input("Enter file:") if len(name) &lt; 1 : name = "mbox-short.txt" handle = open(name) emcount = dict() for line in handle: if not line.startswith("From "): continue line = line.split() line = line[1] emcount[line] = emcount.get(line, 0) +1 bigcount = None bigword = None for word,count in emcount.items(): if bigcount == None or count &gt; bigcount: bigcount = count bigword = word print(bigword, bigcount)
score: 2

http://stackoverflow.com/q/50600661
has comment: http://stackoverflow.com/comment/88212486
accepted answer: http://stackoverflow.com/a/50602975
upvote count: 2
has body: I am making an input pipeline in tensorflow for a task I want to do. I have set up a TFRecord dataset which has been saved out to a file on disk. I am trying to load in the dataset (to be batched and sent to the actual ML algorithm) using the following code: dataset = tf.data.TFRecordDataset(filename) print("Starting mapping...") dataset = dataset.map(map_func = read_single_record) print("Mapping complete") buffer = 500 # How large of a buffer will we sample from? batch_size = 125 capacity = buffer + 2 * batch_size print("Shuffling dataset...") dataset = dataset.shuffle(buffer_size = buffer) print("Batching dataset...") dataset = dataset.batch(batch_size) dataset = dataset.repeat() print("Creating iterator...") iterator = dataset.make_one_shot_iterator() examples_batch, labels_batch = iterator.get_next() However, I get an error on the dataset.map() line. The error I get looks like this: TypeError: Expected int64, got &lt;tensorflow.python.framework.sparse_tensor.SparseTensor object at 0x00000000085F74A8&gt; of type 'SparseTensor' instead. The read_single_record() function looks like this: keys_to_features = { "image/pixels": tf.FixedLenFeature([], tf.string, default_value = ""), "image/label/class": tf.FixedLenFeature([], tf.int64, default_value = 0), "image/label/numbb": tf.FixedLenFeature([], tf.int64, default_value = 0), "image/label/by": tf.VarLenFeature(tf.float32), "image/label/bx": tf.VarLenFeature(tf.float32), "image/label/bh": tf.VarLenFeature(tf.float32), "image/label/bw": tf.VarLenFeature(tf.float32) } features = tf.parse_single_example(record, keys_to_features) image_pixels = tf.image.decode_image(features["image/pixels"]) print("Features: {0}".format(features)) example = image_pixels # May want to do some processing on this at some point label = [features["image/label/class"], features["image/label/numbb"], features["image/label/by"], features["image/label/bx"], features["image/label/bh"], features["image/label/bw"]] return example, label I'm not sure w…
tagged with: machine-learning
tagged with: python
tagged with: computer-vision
linked to: http://stackoverflow.com/q/41921746
type: AnsweredQuestion
score: 2
tagged with: tensorflow
type: Question
has title: Tensorflow TFRecordDataset.map Error
has answer: http://stackoverflow.com/a/50602975
has comment: http://stackoverflow.com/comment/88211608
downvote count: 0
has comment: http://stackoverflow.com/comment/88212269
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/88402044
has text: This is not related to the client library. This is an authentication server issue. Check the other answer @nvnagr is from Google Oauth team
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50695377
type: AnswerComment

http://stackoverflow.com/comment/88273288
has text: You **can't** invoke something in the "current" shell, if by that you mean the one that started your program. It's the parent process. Any creation of a new program is always generating a subprocess; you can't modify the parent process without its active involvement in allowing you to do so.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50631577
score: 1

http://stackoverflow.com/q/50614711
type: Question
tagged with: macos-high-sierra
tagged with: pyspider
tagged with: tornado
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50634883
tagged with: python
score: 1
has body: When I start pyspider by pyspider all in terminal, it pops out an ImportError: ImportError: cannot import name 'Curlasync_HTTPClient' from 'tornado.curl_httpclient' (/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tornado/curl_httpclient.py) There's some other texts in the error message, but I think this is the main cause. I tried to reinstall tornado by reinstalling tornado(4.5.3), but it does not seem to be helpful. So any of you guys ever experienced the same problem? Any tips will be appreciated. Thanks in advance. Config Info: macOS High Sierra 10.13.4 python version:3.7.0a2 tornado version:4.5.3
upvote count: 1
has title: Getting ImportError when starting pyspider in Terminal

http://stackoverflow.com/comment/88156110
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50573053
has text: Are they text of the artists' names?

http://stackoverflow.com/q/50633581
has comment: http://stackoverflow.com/comment/88277422
type: Question
has comment: http://stackoverflow.com/comment/88321831
has title: ValueError: Expecting ',' delimiter, while trying to load string as json in python3
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50635746
favorite count: 0
has comment: http://stackoverflow.com/comment/88284604
tagged with: python-3.x
tagged with: file-io
has comment: http://stackoverflow.com/comment/88277467
linked to: http://stackoverflow.com/q/12451431
tagged with: python
has comment: http://stackoverflow.com/comment/88283946
has body: I have around 5 million tweets in the following format: {"created_at":"Mon May 21 05:40:26 +0000 2018","id":998438346987683840,"id_str":"998438346987683840","text":"sometext","display_text_range":[0,0],"source":"u003ca href="someURL" rel="nofollow"u003eTwitter for iPhoneu003c/au003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":1062745482,"id_str":"1062745482","name":"u3074u30fc","screen_name":"maga12171","location":null,"url":null,"description":"u3068u3063u3066u3082u30aau30c8u30cau3067u3059 u706bu661fu4ebauff08uff0buff09 u7652u3057u306fu95a2u30b8u30e3u30cb u6c34u66dcu3069u3046u3067u3057u3087u3046","translator_type":"none","protected":false,"verified":false,"followers_count":4,"friends_count":23,"listed_count":0,"favourites_count":977,"statuses_count":238,"created_at":"Sat Jan 05 11:09:11 +0000 2013","utc_offset":32400,"time_zone":"Tokyo","geo_enabled":false,"lang":"ja","contributors_enabled":false,"is_translator":false,"profile_background_color":"000000","profile_background_image_url":"someURL","profile_background_image_url_https":"https://abs.twimg.com/images/themes/theme1/bg.png","profile_background_tile":false,"profile_link_color":"0066FF","profile_sidebar_border_color":"000000","profile_sidebar_fill_color":"000000","profile_text_color":"000000","profile_use_background_image":false,"profile_image_url":"http://pbs.twimg.com/profile_images/874952211184222209/UZ8RcGuU_normal.jpg","profile_image_url_https":"someURL","profile_banner_url":"someURL","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"quote_count":0,"reply_count":0,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[],"urls":[],"user_mentions":[],"symbols":[],"media":[{"id":998438345532325888,"id_str":"9984…
score: 2
has comment: http://stackoverflow.com/comment/88277586
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88277504
has comment: http://stackoverflow.com/comment/88277542
has comment: http://stackoverflow.com/comment/88281693
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/88277513
has comment: http://stackoverflow.com/comment/88277523

http://stackoverflow.com/q/50661734
tagged with: class
has comment: http://stackoverflow.com/comment/88333655
has title: "Unbound Local Error" in a decorator
downvote count: 0
tagged with: decorator
favorite count: 0
tagged with: python
has body: I'm getting an error that has me pretty stumped. #! /usr/bin/env python3 from sys import modules from inspect import isclass from functools import partial from abc import abstractmethod from abc import ABC as AbstractClass class Decoration(AbstractClass): defaults = {} def __init__(self, *list, **map): self.list = list self.map = map def __get__(self, caller, owner): return partial(self.__call__, caller) @abstractmethod def __call__(self, decoratee, *list, **map): pass @staticmethod def set_defaults(defaults): Decoration.defaults = defaults class Decorator(Decoration): def __init__(self, *list, **map): super().__init__(self, *list, **map) def __call__(self, function, *list, **map): print(function) def decorated(*list, **map): if map: for decorator in map: for arguments in map[decorator]: function = getattr([__name__], decorator)(function, arguments) return function(*list, **map) return decorated @Decorator() def dummy(*list, **map): for item in list: print(item) for k, v in map: print('{} {}'.format(k, v)) def main(): dummy({'banana': True}) if __name__ == '__main__': main() On the "function = getattr ..." line, I'm getting this error: UnboundLocalError: local variable 'function' referenced before assignment I'm confused mainly because the print statement above finds the function's definition as &lt;function dummy at (address)&gt; which is correct. Furthermore, deleting that line lets the program run fine and return currently on the next line. As far as I can tell, it's not a syntax problem of getattr. Any ideas?
tagged with: getattr
tagged with: python-3.x
answer count: 0
has comment: http://stackoverflow.com/comment/88333594
linked to: http://stackoverflow.com/q/370357
type: UnansweredQuestion
upvote count: 1
type: Question
duplicate of: http://stackoverflow.com/q/370357
score: 1
has comment: http://stackoverflow.com/comment/88333668

http://stackoverflow.com/q/50635112
has comment: http://stackoverflow.com/comment/88280546
type: UnansweredQuestion
tagged with: python
has body: there is something in JSON that says "title":{"rendered":"[보도자료] 스스로 지키는 소중한 개인정보 빗썸, ‘비밀번호 변경하기’ 보안 캠페인 실시"} how can I convert this rendered 보 stuff into English? i'm not even sure what this stuff is called so i'm not sure what to google for.. any help would be appreciated !
answer count: 0
type: Question
tagged with: decode
has title: Translate \ucweirdnumberscharacters into English?
score: 0
linked to: http://stackoverflow.com/q/16566069
has comment: http://stackoverflow.com/comment/88280591
has comment: http://stackoverflow.com/comment/88280658
tagged with: character
has comment: http://stackoverflow.com/comment/88280588

http://stackoverflow.com/a/50592692
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50592540
score: 48
answers question: http://stackoverflow.com/q/50592540
has comment: http://stackoverflow.com/comment/95025743
type: Answer
has comment: http://stackoverflow.com/comment/134371102
has comment: http://stackoverflow.com/comment/88197836
has comment: http://stackoverflow.com/comment/88225598
downvote count: 0
has comment: http://stackoverflow.com/comment/88222591
upvote count: 48
has comment: http://stackoverflow.com/comment/134370900
has body: I expected the numbers to keep printing even after some_func is completed. The argument to run_until_complete controls how long the event loop is run. And once the event loop stops running, all coroutines are effectively suspended, not just the one that you've been waiting for. But you do have different options: loop.run_until_complete(some_func()) - what you already used; run the event loop until the some_func coroutine finishes. Executes other coroutines in parallel during that time as well, but also stops executing them as soon as the event loop finishes. loop.run_forever() - run the event loop until some coroutine or callback invokes loop.stop(). If none of them do that, then the event loop will not halt, even if all the coroutines come to an end. In your case you'd call loop.create_task(while_loop()) followed by loop.create_task(some_func()) and then loop.run_forever(). loop.run_until_complete(asyncio.gather(while_loop(), some_func())) run the event loop until both the specified coroutines finish. This (wait for all the tasks) is apparently what you expected loop.run_until_complete() to do automatically even if you name only one, except it doesn't work like that, it stops as soon as the specified coroutine finishes. asyncio.gather can be used to wait for multiple coroutines at once. For a more fine-tuned control of waiting, also see asyncio.wait. Since one of your coroutines runs forever, the last two options will be equivalent and will result in the expected output.
has comment: http://stackoverflow.com/comment/88210427

http://stackoverflow.com/comment/88096426
comment on: http://stackoverflow.com/q/50542149
has text: I meant that you should edit your question to give more information, I don't know enough to help you, I am just trying to make it easy for anyone else reading the question so they can help you better ^
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88293373
comment on: http://stackoverflow.com/a/50641227
has text: Hi Rakesh, tried with the case = False, but ended with empty dataframe. To help further this time - dprev = Avenue Victoria, Paris, France Is the comma is creating issue?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50624012
answer count: 1
downvote count: 0
tagged with: redhat
favorite count: 0
tagged with: linux
has answer: http://stackoverflow.com/a/68983012
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/93247471
tagged with: python
score: 2
upvote count: 2
type: Question
has body: I have upgraded my RHEL OS from 6.7 to 7.5. After upgrading, I found some issues when trying to run yum. Below are the details. # yum repolist There was a problem importing one of the Python modules required to run yum. The error leading to this problem was: /lib64/libc.so.6: version `GLIBC_2.14' not found (required by /lib64/libgcc_s.so.1) Please install a package which provides this module, or verify that the module is installed correctly. It's possible that the above module doesn't match the current version of Python, which is: 2.6.6 (r266:84292, Aug 9 2016, 06:11:56) [GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] If you cannot solve this problem yourself, please go to the yum faq at: http://yum.baseurl.org/wiki/Faq After getting this error, I just installed python2.7 and GLIBC 2.14. But when I am trying to install GLIBC 2.14 from my current GLIBC version 2.12, it is throwing some error. Below are the steps that I am using to install GLIBC 2.14: tar xvfz glibc-2.14.tar.gz cd glibc-2.14 mkdir build cd build ../configure --prefix=/opt/glibc-2.14 make sudo make install export LD_LIBRARY_PATH=/opt/glibc-2.14/lib:$LD_LIBRARY_PATH In step5, I am getting error. Below are the details: # ../configure --prefix=/opt/glibc-2.14 checking for forced unwind support... no configure: error: forced unwind support is required I am unaware of this error "unwind support is required".Please let me know how to setup/install forced unwind in Redhat 7.5.
tagged with: amazon-ec2
has title: GLIBC 2.14 installation error: forced unwind support is required - RHEL 7.5

http://stackoverflow.com/a/50645568
has body: Your problem lies in this line: b = a This doesn't do what you think it does. In particular, it does not make a copy of a. After the assignment, both b and a refer to the same object. Thus, any change to b is reflected in a also. One way to force a shall copy is to use the slice syntax: b = a[:]
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/88301609
answers question: http://stackoverflow.com/q/50645444
has comment: http://stackoverflow.com/comment/88301668
downvote count: 0
type: Answer

http://stackoverflow.com/comment/88329808
comment on: http://stackoverflow.com/q/50625454
score: 0
type: Comment
type: QuestionComment
has text: Out of curiosity which version of Django are you using?

http://stackoverflow.com/comment/88215115
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50602899
has text: I have tried script mentioned my post link. But format is different that what i want. Also i was wonder if there is any lib or built in function that does the same instead of doing ot through math
score: 0

http://stackoverflow.com/q/50601068
downvote count: 2
answer count: 1
favorite count: 0
upvote count: 3
tagged with: python
has answer: http://stackoverflow.com/a/50601575
has title: Why is slicing using "colon and comma" different than using a collection of indexes
tagged with: numpy-slicing
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88227430
has body: Why is slicing using "colon and comma" different than using a collection of indexes? Here is an example of what I expected to yield the same result but but it does not: import numpy as np a = np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]]) print(a[[0,1],[0,1]]) # Output # [[ 1 2 3] # [10 11 12]] print(a[:,[0,1]]) # Output # [[[ 1 2 3] # [ 4 5 6]] # [[ 7 8 9] # [10 11 12]]] Why are they not equivalent?
type: Question
score: 1
tagged with: numpy

http://stackoverflow.com/comment/88104233
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50546540
has text: `OrderedDict([('unit3', [1, 1, 1]), ('unit1', [1, 4, 3]), ('unit2', [2, 2, 2])])` is also a valid result, right?
type: Comment

http://stackoverflow.com/q/50697616
has title: Chainer - Train GoogLeNet on ImageNet subset
has body: I'm learning to use the deep learning framework Chainer, and I'm in trouble training a GoogLeNet on ImageNet. I use the given example and call it using: python2 train_imagenet.py --arch googlenet --batchsize 64 --epoch 10 --gpu 0 --mean ~/data/imagenet/ILSVRC2012_devkit_t12/data/mean_RGB_256x256.npy --out output/ --root ~/data/imagenet/dataset_sample_256x256/ --val_batchsize 8 ~/data/imagenet/lists/train_files_sample.txt ~/data/imagenet/lists/val_files_sample.txt I use an ImageNet subset of 5000 images, each image resized in 256x256 and converted to RGB when needed. My loss doesn't even slightly change, as shown in the log below. When I log the predicted class, it always ends up after a few iterations predicting always the same class (but this class changes when I run it again). I double-checked my dataset and everything seems fine, I use ImageNet label ids and my txt files contains pairs of path and label, one per line. epoch iteration main/loss validation/main/loss main/accuracy validation/main/accuracy lr 1 100 11.0533 0.00015625 0.01 2 200 11.0533 0.00078125 0.01 3 300 11.0533 0.00046875 0.01 5 400 11.0533 0.0009375 0.01 6 500 11.0531 0.000625 0.01 7 600 11.0532 0.00078125 0.01 8 700 11.0533 0.0009375 0.01 As it is the code from the official repo, I guess that something is wrong with my subset. Is my preprocessing right ? Is 5000 not enough (not to reach state-of-the-art, but to actually learn something) ? Thanks for any ideas of what can be wrong.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88410149
answer count: 0
tagged with: chainer
type: Question
score: 0
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/88410637

http://stackoverflow.com/q/50633153
has answer: http://stackoverflow.com/a/50633583
has title: How can I use a list of lists, or a list of sets, for the TfidfVectorizer?
tagged with: text-classification
type: Question
score: 3
upvote count: 3
answer count: 2
tagged with: scikit-learn
favorite count: 0
tagged with: python-3.x
tagged with: tfidfvectorizer
has answer: http://stackoverflow.com/a/75713289
type: UnansweredQuestion
tagged with: python
has body: I'm using the sklearn TfidfVectorizer for text-classification. I know this vectorizer wants raw text as input, but using a list works (see input1). However, if I want to use multiple lists (or sets) I get the following Attribute error. Does anyone know how to tackle this problem? Thanks in advance! from sklearn.feature_extraction.text import TfidfVectorizer vectorizer = TfidfVectorizer(min_df=1, stop_words="english") input1 = ["This", "is", "a", "test"] input2 = [["This", "is", "a", "test"], ["It", "is", "raining", "today"]] print(vectorizer.fit_transform(input1)) #works print(vectorizer.fit_transform(input2)) #gives Attribute error input 1: (3, 0) 1.0 input 2: Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sklearn/feature_extraction/text.py", line 1381, in fit_transform X = super(TfidfVectorizer, self).fit_transform(raw_documents) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sklearn/feature_extraction/text.py", line 869, in fit_transform self.fixed_vocabulary_) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sklearn/feature_extraction/text.py", line 792, in _count_vocab for feature in analyze(doc): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sklearn/feature_extraction/text.py", line 266, in tokenize(preprocess(self.decode(doc))), stop_words) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sklearn/feature_extraction/text.py", line 232, in return lambda x: strip_accents(x.lower()) AttributeError: 'list' object has no attribute 'lower'
downvote count: 0

http://stackoverflow.com/comment/92148857
type: QuestionComment
has text: Why are you using `@staticmethod`?
comment on: http://stackoverflow.com/q/50574738
score: 0
type: Comment

http://stackoverflow.com/q/50614069
tagged with: python
tagged with: pca
downvote count: 0
score: 1
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/50614299
upvote count: 1
answer count: 1
tagged with: scikit-learn
has title: T-SNE in Sklearn giving NaN or Inf data error
favorite count: 0
has body: I am trying to run t-sne from sklearn on a reduced dimensions data. To start with I have a tfidf matrix. Here is the code for the same. def tf_vectorizer(docs): """ Extract Term frequency vector for each document """ from sklearn.feature_extraction.text import TfidfVectorizer print("Extracting tfidf features for clustering...\n") tf_vec = TfidfVectorizer(max_df=0.95, min_df=2,norm='l2').fit(docs) print("Tf-idf features extracted!!\n") return tf_vec Then I am using TruncatedSVD to reduce the dimensions from 11K to 500. Here it is def reduce_dimensions(tfidf_data,n_components): """ This function will reduce the dimension of the dataset""" from sklearn.decomposition import TruncatedSVD svd=TruncatedSVD(n_components=n_components,random_state=42) svd_reduced_data=svd.fit_transform(tfidf_data) svd_reduced_data=svd_reduced_data.astype('float') #print("Explained Variance of all components {}".format(svd.explained_variance_ratio_)) print("Total variance explained {}".format(svd.explained_variance_ratio_.sum())) return svd_reduced_data I checked the output of svd_reduced_data to check if there is any NaN or Inf. np.isnan(svd_reduced_data).sum() 0 So this shows there are no missing values in this data. Now I pass this data of 500 dimensions to tsne to reduce it to 2 dimensions as follows: from sklearn.manifold import TSNE tsne=TSNE(n_components=n_components,n_iter=300,random_state=42) tsne_reduced_data=tsne.fit_transform(svd_reduced_data) And I get this error: /Users/anaconda/envs/dl/lib/python3.5/site-packages/scipy/linalg/misc.py in norm(a, ord, axis, keepdims) 127 """ 128 # Differs from numpy only in non-finite handling and the use of blas. --&gt; 129 a = np.asarray_chkfinite(a) 130 131 # Only use optimized norms if axis and keepdims are not specified. /Users/anaconda/envs/dl/lib/python3.5/site-packages/numpy/lib/function_base.py in asarray_chkfinite(a, dtype, order) 1231 if a.dtype.char in typecodes['AllFloat'] and not np.isfinite(a).all(): 1232 raise ValueError( -&gt; 123…
type: UnansweredQuestion

http://stackoverflow.com/a/64667946
has comment: http://stackoverflow.com/comment/114342958
has body: Make sure Python is in your system PATH. python -m pip install -u discord.py
answers question: http://stackoverflow.com/q/50686388
score: -1
downvote count: 1
type: Answer
upvote count: 0

http://stackoverflow.com/q/50689840
answer count: 0
type: UnansweredQuestion
has title: Tkinter modify root window from TopLevel() widget
type: Question
has comment: http://stackoverflow.com/comment/125463590
has comment: http://stackoverflow.com/comment/88389718
score: 0
tagged with: user-interface
has comment: http://stackoverflow.com/comment/88389552
tagged with: python
has body: I am new to Tkinter/OOP and would like some help, I am currently stuck making a gui for a application. The functionality i want is that when a new window using the TopLevel() widget is spawned the button used for it to become disabled, which i have achieved. However the problem is enabling it after the spawned window is closed. And in general how does one go about modifying the main tkinter root window from a TopLevel() widget using an OOP based approach. As i would like to do more stuff later on The code is as follows: from tkinter import * from tkinter import ttk class MainWindow: def __init__(self, top): _bgcolor = '#d9d9d9' # X11 color: 'gray85' _fgcolor = '#000000' # X11 color: 'black' _compcolor = '#d9d9d9' # X11 color: 'gray85' _ana1color = '#d9d9d9' # X11 color: 'gray85' _ana2color = '#d9d9d9' # X11 color: 'gray85' font10 = "-family {Segoe UI} -size 10 -weight normal -slant " \ "roman -underline 0 -overstrike 0" self.style = ttk.Style() if sys.platform == "win32": self.style.theme_use('winnative') self.style.configure('.', background=_bgcolor) self.style.configure('.', foreground=_fgcolor) self.style.configure('.', font="TkDefaultFont") self.style.map('.', background= [('selected', _compcolor), ('active', _ana2color)]) self.top=top self.top.geometry("214x96+462+349") self.top.title("Test") self.top.configure(background="#d9d9d9") self.top.configure(highlightbackground="#d9d9d9") self.top.configure(highlightcolor="black") self.top.resizable(0, 0) self.Btn_UI = Button(self.top) self.Btn_UI.place(relx=0.50, rely=0.21, height=24, width=100) self.Btn_UI.configure(activebackground="#d9d9d9") self.Btn_UI.configure(activeforeground="#000000") self.Btn_UI.configure(background="#d9d9d9") self.Btn_UI.configure(command=self.Btn_UI_fun) self.Btn_UI.configure(disabledforeground="#a3a3a3") self.Btn_UI.configure(foreground="#000000") self.Btn_UI.configure(highlightbackground="#d9d9d9") self.Btn_UI.configure(highlightcolor="black") self.Btn_UI.configure(pady="0") self.Btn_UI…
tagged with: tkinter

http://stackoverflow.com/comment/88095004
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50541892
has text: @Simon There's no error messages. It works. But I can see nothing. When I run the program, it finishes.
score: 1

http://stackoverflow.com/comment/88240597
has text: Unfortunately, there isn't enough information here for us to replicate your problem. This is usually an important step in determining a solution. Can you post some data we can use to verify your problem?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50615314
score: 3

http://stackoverflow.com/q/50662613
accepted answer: http://stackoverflow.com/a/50667225
has answer: http://stackoverflow.com/a/66560491
has comment: http://stackoverflow.com/comment/88335397
tagged with: python
tagged with: merge
answer count: 4
tagged with: append
has comment: http://stackoverflow.com/comment/88335590
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88335510
has comment: http://stackoverflow.com/comment/88335363
has comment: http://stackoverflow.com/comment/88335792
type: Question
linked to: http://stackoverflow.com/q/71362967
upvote count: 15
has body: I have a question to merge two columns into one in the same dataframe(start_end), also remove null value. I intend to merge 'Start station' and 'End station' into 'station', and keep 'duration' according to the new column 'station'. I have tried pd.merge, pd.concat, pd.append, but I cannot work it out. dataFrame of Start_end: Duration End station Start station 14 1407 NaN 14th &amp; V St NW 19 509 NaN 21st &amp; I St NW 20 638 15th &amp; P St NW. NaN 27 1532 NaN Massachusetts Ave &amp; Dupont Circle NW 28 759 NaN Adams Mill &amp; Columbia Rd NW Expected output: Duration stations 14 1407 14th &amp; V St NW 19 509 21st &amp; I St NW 20 638 15th &amp; P St NW 27 1532 Massachusetts Ave &amp; Dupont Circle NW 28 759 Adams Mill &amp; Columbia Rd NW Code i have so far: #start_end is the dataframe, 'start station', 'end station', 'duration' start_end = pd.concat([df_start, df_end]) This is what I attempted to: station = pd.merge([start_end['Start station'],start_end['End station']])
tagged with: dataframe
score: 15
has answer: http://stackoverflow.com/a/50662912
possible better answer: http://stackoverflow.com/a/50662858
tagged with: pandas
has answer: http://stackoverflow.com/a/50662858
has title: Merge two columns into one within the same dataframe
has answer: http://stackoverflow.com/a/50667225
downvote count: 0
has comment: http://stackoverflow.com/comment/88335417
favorite count: 0
has comment: http://stackoverflow.com/comment/88335460

http://stackoverflow.com/q/50665837
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50677071
tagged with: parallel-processing
has title: Using flask with joblib
type: Question
has body: While using flask, I came accross an issue where I could not spawn parallel jobs with joblib. I get a message : UserWarning: Multiprocessing backed parallel loops cannot be nested below threads, setting n_jobs=1 Is there a way to get joblib to actually run more than 1 job at a time when executed from within flask? Edit: I found https://github.com/joblib/joblib/issues/180 which says joblib cannot support nested parallelism. I am also willing to swap it out for another library if it can work maybe?
answer count: 1
tagged with: flask
tagged with: python
score: 0

keras
tags question: http://stackoverflow.com/q/50652209
tags question: http://stackoverflow.com/q/50599712
tags question: http://stackoverflow.com/q/50689494
tags question: http://stackoverflow.com/q/50577029
tags question: http://stackoverflow.com/q/50545103
tags question: http://stackoverflow.com/q/50564928
tags question: http://stackoverflow.com/q/50616456
tags question: http://stackoverflow.com/q/50597376
tags question: http://stackoverflow.com/q/50634986
tags question: http://stackoverflow.com/q/50663623
tags question: http://stackoverflow.com/q/50664699
tags question: http://stackoverflow.com/q/50542371
tags question: http://stackoverflow.com/q/50629620
tags question: http://stackoverflow.com/q/50669431
tags question: http://stackoverflow.com/q/50624596
tags question: http://stackoverflow.com/q/50686936
tags question: http://stackoverflow.com/q/50581917
tags question: http://stackoverflow.com/q/50659235
tags question: http://stackoverflow.com/q/50598857
tags question: http://stackoverflow.com/q/50659482
tags question: http://stackoverflow.com/q/50560463
tags question: http://stackoverflow.com/q/50596380
tags question: http://stackoverflow.com/q/50631867
tags question: http://stackoverflow.com/q/50608230
tags question: http://stackoverflow.com/q/50561487
tags question: http://stackoverflow.com/q/50558284
tags question: http://stackoverflow.com/q/50623737
tags question: http://stackoverflow.com/q/50645828
tags question: http://stackoverflow.com/q/50653128
tags question: http://stackoverflow.com/q/50696558
tags question: http://stackoverflow.com/q/50556812
tags question: http://stackoverflow.com/q/50551096
tags question: http://stackoverflow.com/q/50693322
tags question: http://stackoverflow.com/q/50605186
tags question: http://stackoverflow.com/q/50585569
tags question: http://stackoverflow.com/q/50682119
tags question: http://stackoverflow.com/q/50630123
tags question: http://stackoverflow.com/q/50615323
tags question: http://stackoverflow.com/q/50583772
tags question: http://stackoverflow.com/q/50618573
tags question: http://stackoverflow.com/q/50555434
tags question: http://stackoverflow.com/q/50544197
tags question: http://stackoverflow.com/q/50559586
tags question: http://stackoverflow.com/q/50584072
tags question: http://stackoverflow.com/q/50608080
tags question: http://stackoverflow.com/q/50697550
tags question: http://stackoverflow.com/q/50626288
tags question: http://stackoverflow.com/q/50542683
tags question: http://stackoverflow.com/q/50685576
tags question: http://stackoverflow.com/q/50559152
tags question: http://stackoverflow.com/q/50660092
tags question: http://stackoverflow.com/q/50560394
tags question: http://stackoverflow.com/q/50646426
tags question: http://stackoverflow.com/q/50589256
tags question: http://stackoverflow.com/q/50628586
tags question: http://stackoverflow.com/q/50571916
tags question: http://stackoverflow.com/q/50651996
tags question: http://stackoverflow.com/q/50545596
tags question: http://stackoverflow.com/q/50681143
tags question: http://stackoverflow.com/q/50571641
tags question: http://stackoverflow.com/q/50649794
tags question: http://stackoverflow.com/q/50649831
tags question: http://stackoverflow.com/q/50655291
tags question: http://stackoverflow.com/q/50567049
tags question: http://stackoverflow.com/q/50630849
tags question: http://stackoverflow.com/q/50662578
tags question: http://stackoverflow.com/q/50605059
tags question: http://stackoverflow.com/q/50589400
tags question: http://stackoverflow.com/q/50672583
tags question: http://stackoverflow.com/q/50552774
tags question: http://stackoverflow.com/q/50655884
tags question: http://stackoverflow.com/q/50568409
tags question: http://stackoverflow.com/q/50586687
tags question: http://stackoverflow.com/q/50672979
tags question: http://stackoverflow.com/q/50571245
tags question: http://stackoverflow.com/q/50593538
tags question: http://stackoverflow.com/q/50660763
tags question: http://stackoverflow.com/q/50678866
tags question: http://stackoverflow.com/q/50648271
tags question: http://stackoverflow.com/q/50590536

http://stackoverflow.com/q/50553605
upvote count: 3
tagged with: python
tagged with: sklearn-pandas
downvote count: 0
type: UnansweredQuestion
type: Question
score: 3
has title: Extract rule path of data point through decision tree with sklearn python
has answer: http://stackoverflow.com/a/60838437
has answer: http://stackoverflow.com/a/50556945
has body: I'm using decision tree model and I want to extract the decision path for each data point in order to understand what caused the Y rather than to predict it. How can I do that? Couldn't find any documentation.
answer count: 2
tagged with: decision-tree
favorite count: 0

http://stackoverflow.com/comment/88357803
type: Comment
comment on: http://stackoverflow.com/a/50674100
score: 1
type: AnswerComment
has text: For your second option, if the input is [A, A, A, B, B, A, A], should the output be [A, . . B . A .] or [A . . B . . .]?

http://stackoverflow.com/comment/88276791
type: QuestionComment
type: Comment
has text: Please add to your question the sys.path before calling to import scripts.UltraColor
score: 0
comment on: http://stackoverflow.com/q/50633220

http://stackoverflow.com/q/50623735
upvote count: 2
has title: the colormap is different using cv2.imshow and drawpixmap in PyQt5
type: Question
tagged with: colormap
has body: Currently, I need to show my gray image in pseudo color. I use the opencv2 to generate a pseudo colormap. However, I find the colormap showed in cv2 and QLabel is different. For cv2, the code is: import numpy as np import cv2 img = np.zeros((256,256),dtype=np.uint8) img[0:128,0:128] = 255 img[128:255,128:255] = 128 disImg = cv2.applyColorMap(img, cv2.COLORMAP_AUTUMN) cv2.imshow('test',disImg) cv2.waitKey() And the result is: Then, I use the same colormap to generate the pseudo color image, and display using drawpixmal, the code is: import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import numpy as np import cv2 class MyLabel(QLabel): def __init__(self): super(MyLabel, self).__init__() img = np.zeros((256,256),dtype=np.uint8) img[0:128,0:128] = 255 img[128:255,128:255] = 128 disImg = cv2.applyColorMap(img, cv2.COLORMAP_AUTUMN) QImg = QImage(disImg.data, disImg.shape[1], disImg.shape[0], disImg.strides[0], QImage.Format_RGB888) self.qimg = QImg def paintEvent(self, QPaintEvent): super(MyLabel, self).paintEvent(QPaintEvent) pos = QPoint(0, 0) source = QRect(0, 0, 256,256) painter = QPainter(self) painter.drawPixmap(pos, QPixmap.fromImage(self.qimg), source) class Window(QWidget): def __init__(self): super(Window, self).__init__() layout = QHBoxLayout(self) self.resize(300,300) self.label = MyLabel() layout.addWidget(self.label) if __name__ == '__main__': app = QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec_()) And, the result is: Why the colormap is different when I display the same image? In addition, the cv2.COLORMAP_AUTUMN should be: So, the image showed by cv2 is correct, and python drawpixmap give a wrong display. How to fix it?
has comment: http://stackoverflow.com/comment/88257292
tagged with: pyqt
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50623928
type: UnansweredQuestion
tagged with: python
tagged with: opencv
score: 2

http://stackoverflow.com/q/50591307
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/50591423
tagged with: python-requests
tagged with: http
type: Question
answer count: 2
tagged with: url
tagged with: beautifulsoup
has body: I am trying to use request.get(url) to get the response of a url from a server. The following code works for the url of the first page of a search result: r = requests.get("https://www.epocacosmeticos.com.br/perfumes") soup = BeautifulSoup(r.text) However, when I try to use the same code for the url of the second page of the the search result, which is "https://www.epocacosmeticos.com.br/perfumes#2", r = requests.get("https://www.epocacosmeticos.com.br/perfumes#2") soup = BeautifulSoup(r.text) it returns the response of the first page. It ignores the '#2' at the end of the URL. How can I get the response of the second page of a search result?
has title: request.get url of second page of a search result
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50591435

http://stackoverflow.com/comment/88231841
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50610831
has text: If possible, can you please provide some sample data to illustrate what you're trying to do?

http://stackoverflow.com/comment/88285128
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50630140
has text: sorry @Yusef BH i tried $('#datatable').DataTable({ data:data }); but nothing is displayed out on the datatable. I have checked that my serializer.data has return some results
score: 0

http://stackoverflow.com/comment/88351589
has text: Update your question to contain the latest code you're actually using.
comment on: http://stackoverflow.com/q/50670890
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88289083
type: QuestionComment
has text: As apparent from your output, add ["amount"] like coin_amount = [Portfolio.objects.filter(user = request.user, coin = key['coin']).values('amount')["amount"] for key in coin_sell_options] This will however give you a list of list.
comment on: http://stackoverflow.com/q/50638902
score: 0
type: Comment

http://stackoverflow.com/q/50564191
has answer: http://stackoverflow.com/a/50564827
accepted answer: http://stackoverflow.com/a/50564827
tagged with: python.net
upvote count: 3
favorite count: 0
has body: I am new to Python. I developed a C# library .Net Standard 2.0 and i tried to load this in Python using import clr by installing python .net package. The problem is that if I change the version of .net to 1.4 or lower then it works otherwise it show ModuleNotFound Error. Does anyone have idea of dealing with this problem? I don't want to change the version of my .net standard. import clr import sys assemblydir = r"C:\\Python" assemblypath = r"C:\\Python\Mylib.dll" sys.path.append(assemblydir) clr.FindAssembly(assemblypath) clr.AddReference("Mylib") from Mylib import Animal a = Animal() print (a.Get())
has title: Python .Net Not loading .Net Standard 2.0 dll
tagged with: python
type: AnsweredQuestion
score: 3
type: Question
tagged with: c#
answer count: 1
downvote count: 0

http://stackoverflow.com/a/50594207
downvote count: 0
has body: For the number of nations per founding year, you should group only by year. For example: df = pd.DataFrame([['c1', 1950], ['c1', 1950], ['c1', 1950], ['c2', 1960], ['c2', 1960], ['c2', 1960], ['c3', 1970], ['c3', 1970], ['c3', 1970], ['c4', 1960], ['c4', 1960], ['c4', 1960], ['c5', 1950], ['c5', 1950], ['c5', 1950]], columns=['country', 'year']) res = df.groupby('year')['country'].nunique().reset_index() print(res) year country 0 1950 2 1 1960 2 2 1970 1 Or, if you need add a count series to your original dataframe, use pd.DataFrame.transform: df['count'] = df.groupby('year')['country'].transform('nunique') print(df) country year count 0 c1 1950 2 1 c1 1950 2 2 c1 1950 2 ... 6 c3 1970 1 7 c3 1970 1 8 c3 1970 1 9 c4 1960 2 ... 13 c5 1950 2 14 c5 1950 2
type: Answer
answers question: http://stackoverflow.com/q/50594119
score: 7
upvote count: 7
accepted answer of: http://stackoverflow.com/q/50594119
type: AcceptedAnswer

http://stackoverflow.com/comment/88206008
comment on: http://stackoverflow.com/q/50598432
has text: and if in view function code is: a = [{"collectionName":"collection0", "collectionCaption":"col1"}, {"collectionName": "collection1", "collectionCaption": "col2"}, {"collectionName": "collection2", "collectionCaption": "col3"}, ] return render_template('index.html', collectionsNames=a) then index template show me the data
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50637809
has comment: http://stackoverflow.com/comment/88314201
downvote count: 0
has body: Use collections.Counter: from collections import Counter employees = [{'name': 'John', 'empID': '102', 'dpt': 'tech', 'title': 'programmer', 'salary': '75'}, {'name': 'Jane', 'empID': '202', 'dpt': 'tech', 'title': 'programmer', 'salary': '80'}, {'name': 'Joe', 'empID': '303', 'dpt': 'accounting', 'title': 'accountant', 'salary': '85'}] dpts = [x['dpt'] for x in employees] print(Counter(dpts)) # Counter({'tech': 2, 'accounting': 1})
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50637701
has comment: http://stackoverflow.com/comment/88285880
has comment: http://stackoverflow.com/comment/88436574

http://stackoverflow.com/q/50688051
tagged with: error-handling
has answer: http://stackoverflow.com/a/50688188
type: Question
linked to: http://stackoverflow.com/q/23294658
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88386081
has comment: http://stackoverflow.com/comment/88385990
answer count: 1
score: 0
accepted answer: http://stackoverflow.com/a/50688188
tagged with: python
has comment: http://stackoverflow.com/comment/88386056
has title: Python 3.Beginner confused with multiple error handling.i.e. Try and Except
has body: I'm trying to learn about Pythons error handling and I've currently come across the Try and Except statements. I have found myself stuck with a problem. I need a User to enter an number between 0-24. If a number is not entered (i.e a string), I need to use except to print "not a number". If a number is entered and it is not between 0-24 I need to raise another error and print " not in range 0-24" Otherwise print "Valid number. I've been playing around with the code and I have ended up here. error = False try: number = int(input("\nEnter an hour: ")) except ValueError: print("\nNot an number.") error = True while error == false: try: if number &lt;0 or number &gt;24: raise ValueError("number not between 0-24") else: print ("\nIts a number and its between 0-24") Please Help or point me in the right direction:)

http://stackoverflow.com/a/60358753
score: -4
downvote count: 4
answers question: http://stackoverflow.com/q/50552404
upvote count: 0
type: Answer
has body: may be the cause of the problem is that the version of pandas is too low, update the pandas to 1.0.1, it work. use the command as follows: pip install -U pandas

http://stackoverflow.com/comment/88212673
has text: I made a mistake, the `mysql.connect` is a property.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50594892
score: 0

http://stackoverflow.com/a/50635912
answers question: http://stackoverflow.com/q/50635777
has comment: http://stackoverflow.com/comment/88281873
type: AcceptedAnswer
has body: If you want to reverse a list, do as follows: # Solution 1 alist = random.sample(range(1, 100), 5) otherlist = list(reversed(alist)) # Solution 2 (My favourite) otherlist = alist[::-1] # Solution 3 otherlist = alist[:] otherlist.reverse() # Solution 4 otherlist = [] for i in range(len(alist)-1, -1, -1): otherlist.append(alist[i]) # Solution 5 counter = count2 = 0 alist, templist = [], [] while counter&lt;5: alist.append(random.randint(5,10)) print(alist[counter]) counter += 1 while counter &gt; 0: counter -= 1 templist.append(alist[counter]) print(alist[counter]) print("Real",templist[count2]) count2 += 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88281780
accepted answer of: http://stackoverflow.com/q/50635777
has comment: http://stackoverflow.com/comment/88317106
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/88337520
has comment: http://stackoverflow.com/comment/88288414
score: 1

http://stackoverflow.com/q/50695746
tagged with: python
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/50696147
has comment: http://stackoverflow.com/comment/88400959
has comment: http://stackoverflow.com/comment/88401241
answer count: 1
has title: Convert listdir() return to byte for decoding
linked to: http://stackoverflow.com/q/7784148
tagged with: encoding
has body: I have a list of dir with name encoded in 'gbk', for example: dirs |- b'\xb6\xb0'/ |- b'\xc1\xb1'/ |- b'\xc9\xdd'/ However, when I use os.listdir() is return a list of str, like below: ["b'\\xb6\\xb0'", "b'\\xc1\\xb1'", "b'\\xc9\\xdd'"] How can I cast the string to byte and decode it to get the original characters? I tried str.encode.decode but still not working. Thanks.
score: 2
accepted answer: http://stackoverflow.com/a/50696147
downvote count: 0
type: Question
tagged with: listdir
type: AnsweredQuestion

http://stackoverflow.com/comment/88223825
has text: It would be helpful to copy-paste the **entire** stack trace rather than provide a screenshot. Many terminals require CTRL+SHIFT+C for copy rather than just CTRL+C. Your problem is that fich references a file handle, and that handle is closed. To open the **file** again, do exactly what you did before: `with open("test.txt", "a") as fich:...`.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50607037
type: Comment

http://stackoverflow.com/comment/88293936
comment on: http://stackoverflow.com/q/50641240
score: 0
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/questions/10948589/choosing-the-correct-upper-and-lower-hsv-boundaries-for-color-detection-withcv/48367205#48367205

memory
tags question: http://stackoverflow.com/q/50601646
tag name: memory
type: Tag

pdfbox
tag name: pdfbox
type: Tag
tags question: http://stackoverflow.com/q/50576617

http://stackoverflow.com/a/50585359
score: 0
has body: def peliculasO(request, id, *args, **kwargs): peliculaa = Peliculas.objects.get(id=id) relacionar = Peliculas.objects.all() relacionarr = Peliculas.objects.filter(Q(tags__icontains=peliculaa.tags)) contexto = { 'peliculaa':peliculaa, 'relacionarr':relacionarr } return render(request, 'moviesingle.html', contexto) well in this view, i'm trying to send like it was a search but already defined the info that i wanna search, i mean there is not a form which send the value but through view the value is already given, so i can get for this way the queryset that i want... but when i call it through my template: {{relacionarr}} i just get a empty query and there are in my database objects with the same info
type: Answer
answers question: http://stackoverflow.com/q/50567369

http://stackoverflow.com/a/50614901
score: 1
has body: When you get to the edge of 4 and 5, you go through the neighbors of 5 when the code reaches for neighbor in self.graph[vertex]. The only neighbor of 5 is 4 and you then call the function recursively with 4 as the vertex. In the next call of the DFSHelper, the defaultdict adds an entry for 4 because it's missing. Just add your condition if vertex in self.graph before the for-loop to avoid this error.
accepted answer of: http://stackoverflow.com/q/50613281
answers question: http://stackoverflow.com/q/50613281
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0

http://stackoverflow.com/a/50603859
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50600811
has comment: http://stackoverflow.com/comment/88222216
type: AcceptedAnswer
downvote count: 0
has body: In most main window style applications you would use the menuBar() function provided in QMainWindow, adding QMenus to the menu bar and adding QActions to the pop-up menus. For a description of how to create Menu Bar, see the text of the code. Try it: from PyQt5.QtCore import Qt, QRect, QSize from PyQt5.QtWidgets import (QWidget, QPlainTextEdit, QTextEdit, QMainWindow, QAction, qApp) from PyQt5.QtGui import QColor, QPainter, QTextFormat, QKeySequence class QLineNumberArea(QWidget): def __init__(self, editor): super().__init__(editor) self.codeEditor = editor def sizeHint(self): return QSize(self.editor.lineNumberAreaWidth(), 0) def paintEvent(self, event): self.codeEditor.lineNumberAreaPaintEvent(event) class QCodeEditor(QPlainTextEdit): def __init__(self, parent=None): super().__init__(parent) self.lineNumberArea = QLineNumberArea(self) self.blockCountChanged.connect(self.updateLineNumberAreaWidth) self.updateRequest.connect(self.updateLineNumberArea) self.cursorPositionChanged.connect(self.highlightCurrentLine) self.updateLineNumberAreaWidth(0) def lineNumberAreaWidth(self): digits = 1 max_value = max(1, self.blockCount()) while max_value &gt;= 10: max_value /= 10 digits += 1 space = 3 + self.fontMetrics().width('9') * digits return space def updateLineNumberAreaWidth(self, _): self.setViewportMargins(self.lineNumberAreaWidth(), 0, 0, 0) def updateLineNumberArea(self, rect, dy): if dy: self.lineNumberArea.scroll(0, dy) else: self.lineNumberArea.update(0, rect.y(), self.lineNumberArea.width(), rect.height()) if rect.contains(self.viewport().rect()): self.updateLineNumberAreaWidth(0) def resizeEvent(self, event): super().resizeEvent(event) cr = self.contentsRect() self.lineNumberArea.setGeometry(QRect(cr.left(), cr.top(), self.lineNumberAreaWidth(), cr.height())) def highlightCurrentLine(self): extraSelections = [] if not self.isReadOnly(): selection = QTextEdit.ExtraSelection() lineColor = QColor(Qt.yellow).lighter(160) selection.format.setBackground(lineColor) sele…
accepted answer of: http://stackoverflow.com/q/50600811
type: Answer

http://stackoverflow.com/q/50658393
has title: Deepcopy causes "Class" has no attribute 'size'
has comment: http://stackoverflow.com/comment/88327110
tagged with: deep-copy
has body: I am currently trying to implement parallel execution of a process. For each of these processes, every process should create a copy of an object "A", and then proceed with this object. What I have is the following: from copy import deepcopy def some_A(): def wrapper_singlerun(_): return single_run(self, t_kernel, X, Y) pool = pathos.multiprocessing.Pool(4) all_responses = pool.map(wrapper_singlerun, 100) def single_run(self, t_kernel, X, Y): t_kernel = deepcopy(t_kernel) # &lt;&lt;&lt; This line fails ... Notice that the two functions are NOT within the same class! (the self is just supposed to be an object dictionary to be able to access fields from that object. These fields are never modified though). However, when I apply the above functions, I get the following error: self = &lt;bacode.tripathy.src.bilionis_refactor.t_kernel.TripathyMaternKernel object at 0x1a0e6f5ba8&gt; @property def param_array(self): """ Array representing the parameters of this class. There is only one copy of all parameters in memory, two during optimization. !WARNING!: setting the parameter array MUST always be done in memory: m.param_array[:] = m_copy.param_array """ if (self.__dict__.get('_param_array_', None) is None) or (self._param_array_.size != self.size): self._param_array_ = np.empty(self.size, dtype=np.float64) E AttributeError: 'TripathyMaternKernel' object has no attribute 'size' /Users/davidal/miniconda3/lib/python3.6/site-packages/paramz/core/parameter_core.py:349: AttributeError I used to get a similar error by pickling the object when using multiprocessing. However, I cannot quite understand why it happens this time. Do I need to copy the t_kernel object differently? Any ideas why the above function fails?
tagged with: python
answer count: 0
score: 0
type: UnansweredQuestion
tagged with: pass-by-reference
tagged with: multiprocessing
type: Question
tagged with: parallel-processing
has comment: http://stackoverflow.com/comment/88327342

http://stackoverflow.com/q/50654803
score: -2
downvote count: 2
tagged with: vector
has comment: http://stackoverflow.com/comment/88319888
answer count: 1
has comment: http://stackoverflow.com/comment/88320038
has comment: http://stackoverflow.com/comment/88320083
favorite count: 0
tagged with: xor
tagged with: matrix
has comment: http://stackoverflow.com/comment/88320001
has title: Xor multiple arrays in Python
tagged with: python
has answer: http://stackoverflow.com/a/50655109
accepted answer: http://stackoverflow.com/a/50655109
has comment: http://stackoverflow.com/comment/88319923
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/88319942
has body: I'd like to combine multiple arrays in a matrix to achieve an all 0 array (0,0,0,0,0) For example: I have this matrix where array[0] is the index of each array: [0,(0,1,0,1,0)] [1,(0,1,0,0,0)] [2,(0,0,1,1,0)] [3,(0,0,1,0,0)] [4,(0,0,1,0,0)] If I xor arrays 3 and 4 I got an all zeros arrays or I could xor arrays 0,1,2 and 4. I don't know if it exists any library in python to calculate these things o something like that. I've been looking for it days. Any ideas how to do it? I have tried numpy library and tried to do xor method for i in range(len(MODS)): num = [] for j in range(len(MODS[i][1])): if i+1 &lt; len(MODS): if xor(MODS[i][1][j],MODS[i+1][1][j]) == 0: num.append(0) continue else: break else: break The problem is that this method only compares pairs of arrays. I'm looking for any combinations of arrays which do the trick.
has comment: http://stackoverflow.com/comment/88319897
type: Question

http://stackoverflow.com/comment/88208821
type: QuestionComment
has text: Well that's an excellent point. It does so far but it must be just a matter of luck! Thanks for pointing that
type: Comment
comment on: http://stackoverflow.com/q/50599584
score: 0

http://stackoverflow.com/a/50647478
downvote count: 0
score: 4
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88354193
type: Answer
accepted answer of: http://stackoverflow.com/q/50641588
has body: TF can automatically create a tensor from a data frame as long as it has only one data type, in this case it seems to have different data types. Without literal_eval the code seems to work, as each of the features are string and not of mixed type: train = pd.read_csv("train.csv", names=CSV_COLUMN_NAMES, header=0, delimiter=",") Features,labels = train,train.pop('type') dataset = tf.data.Dataset.from_tensor_slices((dict(Features), labels)) iterator = dataset.make_initializable_iterator() next_element = iterator.get_next() with tf.Session() as sess: sess.run(iterator.initializer) print(sess.run(next_element)) print(sess.run(next_element)) Output: ({'y': b'[2, 3, 4]', 'x': b'[1, 2, 3]'}, b'A') ({'y': b'[0, 1, 2]', 'x': b'[2, 7, 9]'}, b'B') Based on this solution: (How to convert a Numpy 2D array with object dtype to a regular 2D array of floats ) if we convert the mixed object type to same (with np.vstack), it works. train['x'] = train['x'].apply(literal_eval) train['y'] = train['y'].apply(literal_eval) Features,labels = train,train.pop('type') dataset = tf.data.Dataset.from_tensor_slices(((np.vstack(Features['x']), np.vstack(Features['y'])), labels)) iterator = dataset.make_initializable_iterator() next_element = iterator.get_next() with tf.Session() as sess: sess.run(iterator.initializer) print(sess.run(next_element)) print(sess.run(next_element)) Output: ((array([1, 2, 3]), array([2, 3, 4])), b'A') ((array([2, 7, 9]), array([0, 1, 2])), b'B')
upvote count: 4
answers question: http://stackoverflow.com/q/50641588

http://stackoverflow.com/comment/88369260
comment on: http://stackoverflow.com/q/50679895
score: 0
type: Comment
type: QuestionComment
has text: this is why I said I need to compare `np.exp` for different values of `x`.

http://stackoverflow.com/a/50593205
accepted answer of: http://stackoverflow.com/q/50593062
upvote count: 2
answers question: http://stackoverflow.com/q/50593062
score: 2
has comment: http://stackoverflow.com/comment/88195869
has body: Here's one solution using itertools.chain and a list comprehension. This has no optimisation for repeated strings. I suggest you test with your data to see if performance is adequate. from itertools import chain res = [list(chain.from_iterable(map(dict_.get, i))) for i in strings] print(res) [[0.4, 0.3, 0.8, -0.1, 7.4, 4.3, 1.5, -1.6, 1.2, 4.23, 0.5, 0.9, 0.5, 1.7], [0.4, 0.3, 0.8, -0.1, 1.5, -1.6, 1.2, 7.4, 4.3], [0.4, 0.3, 0.8, -0.1, 7.4, 4.3, 1.5, -1.6, 1.2, 4.23, 0.5, 0.9, 0.5, 1.7, 1.5, 8.1], [0.4, 0.3, 0.8, -0.1, 1.5, -1.6, 1.2, 7.4, 4.3]]
has comment: http://stackoverflow.com/comment/88195888
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88195917
has comment: http://stackoverflow.com/comment/88195832
type: Answer

http://stackoverflow.com/q/50557484
has title: Pandas applying function to multiple dataframes in a list
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/50557720
accepted answer: http://stackoverflow.com/a/50557720
type: Question
tagged with: dataframe
has body: Applying a function on a list of dataframes, getting error "string indices must be integers, not str" The function works fine when applied individually on each dataframe. However returns error when applied on a list of dataframes. My data looks like below: data date center dt Cust Type 2017-09-20 AA I 2017-09-21 BB E 2017-09-25 BB I 2017-09-29 AA I Function being applied: def calc2(data): def naming(x_array): ww = ' '.join(str(n) for n in x_array) return(ww) dc = data['center'].unique() dt = data['dt'].unique() ct = data['Cust Type'].unique() key = [dc,dt,ct] key = map(naming,key) dc, dt, ct = key[0], key[1], key[2] date = data['date'] print(dc,dt,ct,date) dfs = ['df1','df2','df3'] map(calc2,dfs) Error: ----&gt; 6 dc = data['center'].unique() 7 dt = data['dt'].unique() 8 ct = data['Cust Type'].unique() TypeError: string indices must be integers, not str While works fine on individual dataset: calc2(df1) -- works What am I doing wrong?
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88126192

http://stackoverflow.com/comment/88259889
comment on: http://stackoverflow.com/a/50624564
type: AnswerComment
score: 0
type: Comment
has text: @jceg316 try doing somthing like `df['rank'] = 'nan'` `df['url'] = 'nan'`, sometimes pandas expects column to be already present in the dataframe

http://stackoverflow.com/q/50621008
has comment: http://stackoverflow.com/comment/88251917
type: UnansweredQuestion
has title: Number of Palindromic Slices in a string with O(N) complexity
has body: def solution(S): total = 0 i = 1 while i &lt;= len(S): for j in range(0, len(S) - i + 1): if is_p(S[ j: j + i]): total += 1 i += 1 return total def is_p(S): if len(S) == 1: return False elif S == S[::-1]: return True else: return False I am writing a function to count the number of Palindromic Slices(with length bigger than 1) in a string. The above code is in poor time complexity. Can someone help me to improve it and make it O(N) complexity? Edit: It is not duplicate since the other question is about finding the longest Palindromic Slices
has comment: http://stackoverflow.com/comment/88253143
type: Question
linked to: http://stackoverflow.com/q/3647453
tagged with: python
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50621687
tagged with: algorithm
has answer: http://stackoverflow.com/a/50622186

http://stackoverflow.com/a/50614299
has comment: http://stackoverflow.com/comment/88280890
downvote count: 0
has body: You also need to check with np.isinf() to ensure there are no infinite features.
type: Answer
has comment: http://stackoverflow.com/comment/88238801
upvote count: 1
has comment: http://stackoverflow.com/comment/88238750
score: 1
answers question: http://stackoverflow.com/q/50614069

http://stackoverflow.com/a/50674952
has comment: http://stackoverflow.com/comment/88359629
has comment: http://stackoverflow.com/comment/88359605
has comment: http://stackoverflow.com/comment/109286638
downvote count: 1
answers question: http://stackoverflow.com/q/50674857
upvote count: 9
type: Answer
has body: If it doesn't raise, it committed. If you look at the docs, you'll note that the with-statement is more or less equivalent to: connection = engine.connect() trans = connection.begin() try: r1 = connection.execute(table1.select()) connection.execute(table1.insert(), col1=7, col2='this is some data') trans.commit() except: trans.rollback() raise Regarding the comment: a with-statement is not, necessarily, a replacement for try/except in case you need exception handling – such as when you want to know if the transaction rolled back or not. If you have to perform additional cleanup or for example logging when a transaction rolls back, you'll still have to wrap the with-statement in a try/except, but you can be sure that the transaction has been dealt with before control passes from the block governed by the with-statement: try: with ...: ... except ...: # rolled back else: # committed You could also opt to reraise the error so that other parts can also handle their cleanup. Of course for example logging could be handled by another context manager as well: from contextlib import contextmanager @contextmanager def logger(log, error_msg="Oh woe!"): try: yield except: log.exception(error_msg) raise ... with logger(log), connection.begin(): r1 = connection.execute(table1.select()) connection.execute(table1.insert(), col1=7, col2='this is some data') In this case as you've noted in the comment a try/except has been eliminated, or hidden, by using a with-statement, in the spirit of PEP 343: This PEP adds a new statement "with" to the Python language to make it possible to factor out standard uses of try/finally statements.
score: 8

http://stackoverflow.com/a/50684183
accepted answer of: http://stackoverflow.com/q/50684086
type: AcceptedAnswer
downvote count: 0
has body: You can use, with cummax to set the condition to be counted after promo equal to 1 then use mask to eliminate the promo itself: df.groupby('product')\ .apply(lambda x: x.loc[x['Promo'].cummax().mask(x['Promo']==1,0) == 1, 'Purchase'].sum()) Output: product apple 0 banana 8 dtype: int64
answers question: http://stackoverflow.com/q/50684086
has comment: http://stackoverflow.com/comment/88382156
type: Answer
upvote count: 3
score: 3

http://stackoverflow.com/a/50653144
has comment: http://stackoverflow.com/comment/88316874
has comment: http://stackoverflow.com/comment/88316869
downvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/88334414
has body: gethostname generally just reports what /etc/hostname or equivalent has in it, and that can be just a made up name. gethostbyname tries to resolve that name, and unless it's also in something like /etc/hosts, which some systems set up to match, and it's not resolvable by your configured DNS servers, then you get an error. So you can try either fixing the name in /etc/hosts if it was there first under the old name, or you can ignore that and just use your host-name as-is. Remember, unless your public and private IP match that DNS result is useless anyway. What you probably want is to hit a service like Ipify to determine what your actual external IP is.
answers question: http://stackoverflow.com/q/50653103
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/88316980
has comment: http://stackoverflow.com/comment/88316858

http://stackoverflow.com/a/50552891
type: AcceptedAnswer
upvote count: 6
has body: from io import BytesIO client = docker.from_env() data = client.containers.run("deep_analize/show_exploit:1.0", ['Apache 1.3.42'], detach=True) sleep(5) file_json = data.get_archive('/wd/out.json') stream, stat = file_json file_obj = BytesIO() for i in stream: file_obj.write(i) file_obj.seek(0) tar = tarfile.open(mode='r', fileobj=file_obj) text = tar.extractfile('out.json') q = text.read() print(q)
type: Answer
downvote count: 0
score: 6
accepted answer of: http://stackoverflow.com/q/50552501
answers question: http://stackoverflow.com/q/50552501

http://stackoverflow.com/comment/88343196
type: QuestionComment
comment on: http://stackoverflow.com/q/50664853
score: 0
has text: Ugh... Looking further it looks like some of those methods are internal to the library. Though I think it might be a fair starting point for you to look through their code base and see if you can find something that *can* be used. I'm still fairly confident you need to include that static method
type: Comment

http://stackoverflow.com/q/50688660
score: 0
has body: I want to mock a python object -psycopg2 - to test my classes. When I print the object - dir(conn), I see the connect, extras, etc, all being listed. conn = mock.MagicMock(psycopg2.connect) Result: ['BINARY', 'Binary', 'DATETIME', 'DataError', 'DatabaseError', 'Date', 'DateFromTicks', 'Error', 'IntegrityError', 'InterfaceError', 'InternalError', 'NUMBER', 'NotSupportedError', 'OperationalError', 'ProgrammingError', 'ROWID', 'STRING', 'Time', 'TimeFromTicks', 'Timestamp', 'TimestampFromTicks', 'Warning', '__builtins__', '__doc__', '__file__', '__libpq_version__', '__name__', '__package__', '__path__', '__version__', '__warningregistry__', '_connect', '_ext', '_ipaddress', '_json', '_psycopg', '_range', 'apilevel', 'assert_any_call', 'assert_called', 'assert_called_once', 'assert_called_once_with', 'assert_called_with', 'assert_has_calls', 'assert_not_called', 'attach_mock', 'call_args', 'call_args_list', 'call_count', 'called', 'configure_mock', 'connect', 'extensions', 'extras', 'method_calls', 'mock_add_spec', 'mock_calls', 'paramstyle', 'reset_mock', 'return_value', 'side_effect', 'threadsafety', 'tz', 'warn'] Now, when I want to set the side_effect of the execute method return value. conn.cursor().execute().side_effect = psycopg2.DatabaseError I get this error: AttributeError: Mock object has no attribute 'cursor' New code:- pg = mock.MagicMock(psycopg2) print dir(pg()) print dir(pg.connect) pg.connect() Output AttributeError: Mock object has no attribute 'cursor'
tagged with: python
has comment: http://stackoverflow.com/comment/88387605
has title: Mocking class vs methods
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88387500
has answer: http://stackoverflow.com/a/50689018
accepted answer: http://stackoverflow.com/a/50689018
tagged with: python-mock
tagged with: mocking
answer count: 1
has comment: http://stackoverflow.com/comment/88387679

http://stackoverflow.com/comment/88324399
has text: You are right, I forgot to consider this path: "views-field views-field-field-start-date-text". thank you
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50656364

http://stackoverflow.com/q/50605424
score: 4
has comment: http://stackoverflow.com/comment/88220235
favorite count: 0
has answer: http://stackoverflow.com/a/67965853
upvote count: 5
tagged with: pandas
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88220285
answer count: 4
has answer: http://stackoverflow.com/a/50605531
accepted answer: http://stackoverflow.com/a/50605531
has title: Pandas: reverse Liker survey answers
has body: I have the following problem: I have a survey that contains a large number of answers to likert questions, like so: id | Q1 | Q2 | Q3 1 5 3 1 2 3 4 1 3 2 3 1 The problem is that not all questions are asked in 'the same direction'. So a answer of '5' in Q1 would indicate a positive answer. But a 5 in Q2 would mean a strongly negative answer. We are currently re-encoding all questions by hand (thus replacing all Q2 5's with 1's, etc) but I was wondering if there is a quicker way to solve this. I thought about dividing all answers by 5 and then subtracting 1, but that never gives me whole numbers. Math isn't really my strongpoint here, so I was wondering if someone here could help me out
possible better answer: http://stackoverflow.com/a/50605704
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50605704
has answer: http://stackoverflow.com/a/50605634
has comment: http://stackoverflow.com/comment/88220210
type: Question

http://stackoverflow.com/a/50623608
downvote count: 0
answers question: http://stackoverflow.com/q/50623552
has body: You need itertools.combinations_with_replacement() and vary the r. this isn't in your order as it is unclear if this is a requirement, e.g.: In []: from itertools import combinations_with_replacement as cwr nums = [1, 2, 3] [x for n in range(1, len(nums)+1) for x in cwr(nums, r=n)] Out[]: [(1,), (2,), (3,), (1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3), (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 2), (1, 2, 3), (1, 3, 3), (2, 2, 2), (2, 2, 3), (2, 3, 3), (3, 3, 3)] In []: from itertools import product [x for n in range(1, len(nums)+1) for x in product(nums, repeat=n)] Out[]: [(1,), (2,), (3,), (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3), (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 1), (1, 3, 2), (1, 3, 3), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 1), (2, 3, 2), (2, 3, 3), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 3, 1), (3, 3, 2), (3, 3, 3)]
type: Answer
has comment: http://stackoverflow.com/comment/88278506
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/88260459

http://stackoverflow.com/a/50633678
upvote count: 1
answers question: http://stackoverflow.com/q/50633016
has body: You'll need to import the animation module and define a function that changes the frame to show each image you captured. from matplotlib.animation import FuncAnimation def update(i): label = 'timestep {0}'.format(i) //Insert the data the frame here Eg:ax.imgshow(Image.open('A.png'), cmap="bone") ax.set_xlabel(label) return line, ax FuncAnimation(fig, update, frames=np.arange(0, 10), interval=200) plt.show() You can follow this handy guide: https://eli.thegreenplace.net/2016/drawing-animated-gifs-with-matplotlib/
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50633016
score: 1

http://stackoverflow.com/a/50636320
upvote count: 1
has body: Yes, you must have to install Service Pack 1 in order to make it installed. or you have to continue your stuff with Python 2.7. Download Service Pack 1 from the link suggested by @jerrycheng
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/50575512

http://stackoverflow.com/a/50689019
type: Answer
has body: The problem is your url_patterns url(r'^parties', PartyNumView), When this url your view not recive the pk argument it raise the exception
upvote count: 1
answers question: http://stackoverflow.com/q/50688737
downvote count: 0
score: 1

http://stackoverflow.com/a/50557275
score: 0
has body: If I understood your question correctly this should do the trick: toParse='aa bb first item ee ff' keywords=['test 1','first item','test two'] for x in keywords: res=toParse.find(x) if res&gt;=0: print('prefix='+toParse[0:res]) print('keyword='+x) print('suffix='+toParse[res+len(x)+1:]) break Gives this result: prefix=aa bb keyword=first item suffix=ee ff
has comment: http://stackoverflow.com/comment/88125434
answers question: http://stackoverflow.com/q/50557099
type: Answer

http://stackoverflow.com/comment/88248734
has text: I have updated OP to handle the case above!
comment on: http://stackoverflow.com/q/50618761
type: Comment
type: QuestionComment
score: 0

terminal-emulator
tag name: terminal-emulator
type: Tag
tags question: http://stackoverflow.com/q/50585963

http://stackoverflow.com/comment/88249478
comment on: http://stackoverflow.com/a/50619615
score: 0
type: AnswerComment
type: Comment
has text: @Mighty - added details for better explanation it.

http://stackoverflow.com/a/50556132
type: Answer
answers question: http://stackoverflow.com/q/50555948
score: 2
downvote count: 0
has body: In this case, you can get it from self.request.GET["articleid']. Note however this is not best practice in Django; you should write a URL pattern that includes the id directly, so that your URL would be /stories/100/.
has comment: http://stackoverflow.com/comment/88124537
upvote count: 2
has comment: http://stackoverflow.com/comment/88123240

http://stackoverflow.com/a/50673089
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/88356059
has comment: http://stackoverflow.com/comment/88355884
has comment: http://stackoverflow.com/comment/88356122
has comment: http://stackoverflow.com/comment/88355888
score: 4
has body: This can be done using single-nested loops, multiplying a string, and the usage of the input function. char = input("Enter the character you want to use to draw your square: ") width = int(input("Enter the width of your square: (insert value here): ")) height = int(input("Enter the height of your square: (insert value here): ")) for h in range(0,height): print(char * width) There is an even more efficient way of printing the desired shape in terms of code and time, involving just one line. Replace the loop with this line: print("\n".join([char * width for _ in range(height)])) Here is a test run of my program. The first way using a loop took 11908 microseconds, the second took just 4998 microseconds. Enter the character you want to use to draw your square: % Enter the width of your square: (insert value here): 10 Enter the height of your square: (insert value here): 3 %%%%%%%%%% %%%%%%%%%% %%%%%%%%%%
answers question: http://stackoverflow.com/q/50673065
has comment: http://stackoverflow.com/comment/88355901
type: Answer
has comment: http://stackoverflow.com/comment/88355874

http://stackoverflow.com/a/50589932
type: AcceptedAnswer
downvote count: 0
has body: import flask.ext.whatever is no longer supported in Flask 1.0. Flask-Autodoc's docs need to be updated. flask_autodoc should be imported directly: from flask_autodoc import Autodoc
score: 6
has comment: http://stackoverflow.com/comment/113930373
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/50589906
answers question: http://stackoverflow.com/q/50589906

http://stackoverflow.com/q/50609002
type: Question
tagged with: debugging
tagged with: visual-studio-code
has answer: http://stackoverflow.com/a/50609100
has comment: http://stackoverflow.com/comment/88227890
has title: TensorFlow debug: WARNING:tensorflow:Tensor._shape is private, use Tensor.shape instead. Tensor._shape will eventually be removed
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51165112
type: UnansweredQuestion
tagged with: python
has body: I'm new (obviously) to python, but not so new to TensorFlow I've been trying to debug my program using breakpoint, but everytime I try to check the content of a tensor in the variable view of my Visual Studio Code debugger, the content doesn't show I get this warning in the console: WARNING:tensorflow:Tensor._shape is private, use Tensor.shape instead. Tensor._shape will eventually be removed. I'm a bit confused on how to fix this issue. Do I have to wait for an update of TensorFlow before it works?
tagged with: tensorflow

http://stackoverflow.com/comment/88237326
score: 0
comment on: http://stackoverflow.com/q/50613665
type: Comment
type: QuestionComment
has text: Try importing `Config` into the file where your are trying to unpickle it.

http://stackoverflow.com/q/50610188
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50630208
has body: So I'm trying to make a game where there are 2 objects and am trying to make it so that my program knows when the 2 objects collide. if players[0].mask.overlap(players[1].mask, offset): print("collided")` My objects both rotate clockwise and counterclockwise and have masks both for the head and the body. (I have 2 images which are both the same size but one contains only the head and another contains only the body, in order to use mask.from_surface().) def turn(self, event): self.surface = self.ojSurface if event == 0: self.deg -= self.turnSpd elif event == 1: self.deg += self.turnSpd self.surface = pygame.transform.rotate(self.surface, self.deg) self.newPos = (self.pos[0] - self.surface.get_width() / 2, self.pos[1] - self.surface.get_height() / 2) self.mask = pygame.mask.from_surface(self.surface) However, what I find is when I try to check for collision when they are rotated the mask isn't in the same place as the image. It should update the mask every frame through the move function which is called every loop def move(self): self.pos[0] = pygame.mouse.get_pos()[0] self.pos[1] = pygame.mouse.get_pos()[1] self.newPos = (self.pos[0] - self.surface.get_width() / 2, self.pos[1] - self.surface.get_height() / 2) self.mask = pygame.mask.from_surface(self.surface) Faulty Hit Detection If you want to peruse what I have so far here it is: import pygame class Player: def __init__(self, pos,surface,screen): self.pos = [pos[0],pos[1]] self.newPos = (pos[0] - surface.get_width()/2, pos[1] - surface.get_height()/2) self.deg = 0 self.surface = surface self.ojSurface = surface self.screen = screen self.mask = pygame.mask.from_surface(self.surface) def turn(self, event): self.surface = self.ojSurface #clockwise if event == 0: self.deg -= 0.1 #counter clockwise elif event == 1: self.deg += 0.1 self.surface = pygame.transform.rotate(self.surface, self.deg) #resetting pos and mask self.newPos = (self.pos[0] - self.surface.get_width() / 2, self.pos[1] - self.surface.get_height() / 2) s…
tagged with: pygame
favorite count: 0
has comment: http://stackoverflow.com/comment/88252988
possible better answer: http://stackoverflow.com/a/50613886
accepted answer: http://stackoverflow.com/a/50630208
has comment: http://stackoverflow.com/comment/88269652
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50613886
type: AnsweredQuestion
score: 1
has title: Rotating Mask collision in Pygame
type: Question

http://stackoverflow.com/comment/88309583
comment on: http://stackoverflow.com/q/50648853
score: 0
type: Comment
has text: @PatrickArtner ok, so how can I tell which 'parts' each function call is requesting when it gets fed in? i.e. how can I tell what "part" the `StructuredLearner(md, StructuredModel(to_gpu(model)), opt_fn=optim.Adam)` call wants from the `md` object?
type: QuestionComment

http://stackoverflow.com/comment/88404938
type: AnswerComment
has text: Super, , use `df = df.fillna(0)`
comment on: http://stackoverflow.com/a/50696442
type: Comment
score: 0

http://stackoverflow.com/q/50662206
score: -1
type: UnansweredQuestion
downvote count: 1
has answer: http://stackoverflow.com/a/50662434
has comment: http://stackoverflow.com/comment/88334938
has comment: http://stackoverflow.com/comment/88336895
has title: python HTTP error 302
tagged with: urllib
type: Question
upvote count: 0
answer count: 1
favorite count: 0
has body: i keep getting an html 302 error however i am quite certain the error is coming from some code in here i just don't know where exactly and how to fix it. headers ={'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8','Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3','Accept-Encoding': 'gzip, deflate, sdch','Accept-Language': 'en-US,en;q=0.8','Connection': 'keep-alive'} req_obj = urllib.request.Request(url, method=method,headers=headers) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) response = opener.open(req_obj) json_resp = json.loads(response.read().decode('utf-8')) and the error I get it is HTTP Error 302: The HTTP server returned a redirect error that would lead to an infinite loop. The last 30x error message was: Found (False, &lt;HTTPError 302: 'The HTTP server returned a redirect error that would lead to an infinite loop.\nThe last 30x error message was:\nFound'&gt;) thanks in advance
tagged with: http://stackoverflow.com/tag/html
tagged with: python

http://stackoverflow.com/a/50574528
upvote count: 7
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 7
accepted answer of: http://stackoverflow.com/q/50572592
answers question: http://stackoverflow.com/q/50572592
has body: If you already go with RDD API you can just follow through bigrams = text_file.flatMap(lambda line: line.split(".")) \ .map(lambda line: line.strip().split(" ")) \ .flatMap(lambda xs: (tuple(x) for x in zip(xs, xs[1:]))) bigrams.map(lambda x: (x, 1)).reduceByKey(lambda x, y: x + y) Otherwise: from pyspark.sql.functions import explode ngram_df.select(explode("bigrams").alias("bigram")).groupBy("bigram").count()

http://stackoverflow.com/comment/88160591
type: AnswerComment
has text: Thank you for your answer, this does indeed appear to be correct. Now I'm curious as to why the former appears to give on average a better performance by about 0.007s, or ~16%. This is marginal, of course, but I would have expected one less function call to reduce the time even further.
comment on: http://stackoverflow.com/a/50575720
type: Comment
score: 0

http://stackoverflow.com/comment/88151928
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50570988
has text: Thanks. Did I complicate my code? is this the best approach?
score: 0

http://stackoverflow.com/comment/88209474
score: 0
has text: Thanks for taking the time to help out. Is there a way to optimize the code and make it work?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50599838

http://stackoverflow.com/comment/88296333
has text: Edit your post message using your fresh code. It allow to help you.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50640929

http://stackoverflow.com/a/50588945
has comment: http://stackoverflow.com/comment/88187301
has comment: http://stackoverflow.com/comment/88187249
has comment: http://stackoverflow.com/comment/88187439
has body: You are trying to convert 90.09. to a float. This occurs because statement s = str(x) + '.' converts 90.09 into a string and appends . to it. Since there are two . in this string, when we attempt to convert it to a float an exception is thrown, caught, and handled by returning -1. For the record this is why catching all exceptions is a bad idea. You should only catch the exceptions you expect and can handle.
type: Answer
answers question: http://stackoverflow.com/q/50588852
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/88187413
has comment: http://stackoverflow.com/comment/88187275
has comment: http://stackoverflow.com/comment/88187386
upvote count: 6

http://stackoverflow.com/q/50619532
has comment: http://stackoverflow.com/comment/88267004
has comment: http://stackoverflow.com/comment/88265213
score: 0
has comment: http://stackoverflow.com/comment/88265917
answer count: 0
tagged with: pyspark
type: UnansweredQuestion
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/88262309
has body: I have the following script set up: conf = SparkConf().setAppName("GetAif") sc = SparkContext(conf=conf) sqlContext = SQLContext(sc) schemaString = "c1 c2 id c3 c4 gender" fields = [StructField(field_name, StringType(), True) for field_name in schemaString.split()] custschema = StructType(fields) data_extract = sqlContext.read \ .format('com.databricks.spark.csv') \ .option("header", "true") \ .option("mode", "DROPMALFORMED") \ .option("delimiter", ',') \ .option("inferSchema", "false") \ .load('/data/dataset.csv', schema = custschema) \ .selectExpr("id", "gender) the end goal is to extract the gender and id variables in one data parse. I am fairly new to spark, so I am establishing that I want to minimize my operations. I have attempted using: sc.textFile(/dataset.txt) and a few operations thereafter, but that seemed to amplify the bad performance because of the number of operations. Is there any better method which is potentially be cleaner?
type: Question
has title: Parse specific columns with pyspark
tagged with: python
has comment: http://stackoverflow.com/comment/88262372

http://stackoverflow.com/comment/88173376
comment on: http://stackoverflow.com/a/50556601
type: Comment
score: 0
type: AnswerComment
has text: This is a technical explanation for how attribute lookup is conducted.But it does not explain the logic behind. Why class level descriptor is working whereas instance level is handled differently.

http://stackoverflow.com/q/50616403
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: raspbian
has comment: http://stackoverflow.com/comment/88244480
has title: Auto re connect to WiFi on connection drop using Python 3 on Raspbian
type: Question
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/88244442
has comment: http://stackoverflow.com/comment/88280125
has comment: http://stackoverflow.com/comment/88244775
score: 0
has comment: http://stackoverflow.com/comment/88246504
tagged with: unix
tagged with: python-3.x
has body: I've created an UI using RPi and used GPIO to collect data from a remote machine and send that data through the WiFi. I made all the scripting using Python 3 and i want to add a function or something to auto reconnect to a 'specified WiFi network'. I don't want to search for available networks, i just want to keep trying to reconnect to that one particular WiFi network. Like after every 'n' seconds, try to re connect. This network wouldn't have internet access btw, just trying to send data to a local server. Tried all similar scripts from all possible similar threads but to of no use. If someone could give lead, it would be great, thanks!

http://stackoverflow.com/comment/88176358
type: Comment
score: 0
type: AnswerComment
has text: mail.personalizations[0].add_substitution(Substitution("-name-", "Ajay")) I have added this comment and it works....thanks though...
comment on: http://stackoverflow.com/a/50579198

http://stackoverflow.com/comment/88335494
comment on: http://stackoverflow.com/a/50645249
has text: That approach was working for me before. Thanks though. Looking to solve it through pickle if it's possible.
type: Comment
score: 2
type: AnswerComment

http://stackoverflow.com/comment/88359990
score: 0
type: Comment
has text: on my environment, it does change, but the number of seconds between 2 changes is not always the same. site changed, 120 site changed, 60 site changed, 61 site changed, 156 site changed, 61 site changed, 119 site changed, 59 site changed, 58 site changed, 174 site changed, 73 site changed, 31 site changed, 31 site changed, 31 site changed, 15 site changed, 58 site changed, 58 site changed, 118 site changed, 23 site changed, 29 site changed, 9 site changed, 53 site changed, 31 site changed, 32 site changed, 30 site changed, 120 site changed, 60
type: QuestionComment
comment on: http://stackoverflow.com/q/50669307

http://stackoverflow.com/comment/88218298
has text: Where can I find which versions of chromedriver support which versions of chromium? Seems a bit weird that the most recent versions of both are not compatible with eachother :|
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50603997

http://stackoverflow.com/q/50642388
has comment: http://stackoverflow.com/comment/88300028
score: 1
has body: I created those data by the API of my Django/Django-Rest-Framework project. I using MySQL database. but there is a issue, in the database, the timezone is UTC, and my timezone is +8(Beijing Time) timezone. but when I query out the data, it still is the UTC time. How to standardizing this timezone? I surmise there are two way to do that, when store the data, timezone set to the +8. when query out the data, the time convert to +8 timezone. But both I don't know how to realize, who can tell me what's your best solution? my configurations in settings.py are bellow: LANGUAGE_CODE = 'zh-cn' TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_L10N = True USE_TZ = True
type: Question
linked to: http://stackoverflow.com/q/47135190
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/88300590
downvote count: 0
has title: Talk about the timezone in the Django when store in the MySQL database
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python

http://stackoverflow.com/a/50650288
has body: Change this line: for numbers in a: To: for i, numbers in enumerate(a): And then change how you print the indices: print("Number", n, "is located in the list and the position is:", (i+1)) Sample output: [1, 2, 2, 5, 5, 5, 6, 7, 8, 8, 8, 10, 10, 10, 10, 10, 11, 11, 16, 17, 17, 19, 19] What number are you looking for? 8 Number 8 is located in the list and the position is: 9 Number 8 is located in the list and the position is: 10 Number 8 is located in the list and the position is: 11
has comment: http://stackoverflow.com/comment/88311495
has comment: http://stackoverflow.com/comment/88311541
upvote count: 2
answers question: http://stackoverflow.com/q/50650250
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50650250
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/a/50597047
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/50596380
answers question: http://stackoverflow.com/q/50596380
has comment: http://stackoverflow.com/comment/88228472
downvote count: 0
score: 2
type: AcceptedAnswer
has body: If I understand your question correctly you would like to get the 128 dimensional encoded representation, from the convolutional autoencoder, for image comparison? What you could do is create a reference on the encoder part of the network, train the whole autoencoder and then encode the images with the weights of the encoder reference. Put this: self.autoencoder = autoencoder self.encoder = Model(inputs=self.autoencoder.input, outputs=self.autoencoder.get_layer('encoded').output) after autoencoder.compile() and create encodings with: encoded_img = self.encoder.predict(input)

http://stackoverflow.com/comment/88313250
has text: I see. Thanks Julien
type: Comment
comment on: http://stackoverflow.com/a/50596116
type: AnswerComment
score: 0

http://stackoverflow.com/a/50580580
has comment: http://stackoverflow.com/comment/88431301
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50580459
has body: You didn't mention anything about how the array and matrix are defined, it can be assumed that those are numpy matrix and array... Do you mean something like the following? import numpy as np from scipy.sparse import csr_matrix A = csr_matrix([[1, 2, 0], [0, 0, 3], [4, 0, 5]]) v = np.array([1, 0, 1]) print(A.dot(v)) if so take a look at here: https://docs.scipy.org/doc/scipy/reference/sparse.html
has comment: http://stackoverflow.com/comment/88172476
downvote count: 0

http://stackoverflow.com/a/50671343
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50671083
has body: In regards to the performance of Python vs Matlab I recommend looking at http://wiki.scipy.org/PerformancePython. Obviously speed is related to the problem needed to be solved, but I'd imagine for purely mathematical / physical calculations and simulations Matlab will have the upper hand (being, of course, designed for those purposes). With respect to your code, Python does have a variety of tools available to increase the performance, for example using generators, or, for mathematical applications, Numpy's (backended in C) ndarrays. If you are serious about high performance python you might also want to check out PyPy or Cython. Also I remember reading somewhere (will update if I find the link) that just by using function calls and python classes, code execution speeds up drastically since the bytecode can be more effectively interpreted. I'd also point you in the direction of this reply https://stackoverflow.com/a/16752469/9889462 as a starter for speeding up your code using generators. Hope this helps

http://stackoverflow.com/q/50650372
has answer: http://stackoverflow.com/a/50650397
type: AnsweredQuestion
favorite count: 0
has title: Python Error: Unexpected character after line continuation character
has comment: http://stackoverflow.com/comment/88311681
type: Question
tagged with: python
possible better answer: http://stackoverflow.com/a/50650553
accepted answer: http://stackoverflow.com/a/50650397
has answer: http://stackoverflow.com/a/50650553
has body: I am trying to create a dataframe to store reddit data: topics_dict = { "title":[],\ "score":[],\ "id":[], "url":[],\ -&gt; Error "comms_num": [],\ "created": [],\ "body":[]}
score: 0
answer count: 2
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88311664

http://stackoverflow.com/q/50688498
has answer: http://stackoverflow.com/a/50688671
tagged with: python
has title: Python 3 - Scrape Inner Div's Info with BS4
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/50688671
answer count: 1
tagged with: beautifulsoup
has body: I'm trying to scrape some website with beautifulsoup but i couldn't make it work. On the site there is main div i'm taking that div with this code : for divs in soup.find_all('div', {'class': 'row div-1'}): #I'm taking main div innerDivs = divs.find_all('div') #Taking inner div's in main div for inner in innerDivs: #loop for all inner divs print(inner) # I can print every inner div so it's working Here one inner div structure : I want to acces "title" and image-src but i don't know how. I tried 'inner.title' etc but i failed. Thanks for suggestions!
score: 0
tagged with: python-3.x

http://stackoverflow.com/comment/88312217
has text: @thisAaronMdev, you can add a specific method to your class: `def __str__():` and have it return whatever you want it to print, such as print all the fields in your class, or just say "this is a user. goodluck" if you want. Then when you call print(users[0]) it will print exactly what you want it to print.
comment on: http://stackoverflow.com/a/50650177
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50692000
type: AnsweredQuestion
score: 1
tagged with: group-by
tagged with: dataframe
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/50692069
downvote count: 0
has body: I have a pandas data frame df: df = pd.DataFrame(data = {'v1': ['b', 'b', 'c', 'a', 'd', 'c', 'd', 'c', 'f', 'e'], 'v2': ['a', 'a', 'd', 'b', 'c', 'e', 'c', 'd', 'g','c'], 'v3': [3.3, 2.9, 3.5, 4.7, 5.1, 1.1, 2.3, 3.4, 4.7, 6.1]}) v1 v2 v3 0 b a 3.3 1 b a 2.9 2 c d 3.5 3 a b 4.7 4 d c 5.1 5 c e 1.1 6 d c 2.3 7 c d 3.4 8 f g 4.7 9 e c 6.1 I want to generate result looks like: v1 v2 v3 0 b a 3.3 1 b a 2.9 3 a b 4.7 2 c d 3.5 4 d c 5.1 6 d c 2.3 7 c d 3.4 5 c e 1.1 9 e c 6.1 8 f g 4.7 i.e., stack rows with the same pairs of v1 and v2. v1 = a, v2 = b and v1 = b, v2 = a is not equal(we cannot swap v1 and v2) but they are regarded as in the same group. How can I make it? Any help appreciated!
favorite count: 0
tagged with: pandas-groupby
tagged with: pandas
tagged with: python
possible better answer: http://stackoverflow.com/a/50692086
has answer: http://stackoverflow.com/a/50692086
has answer: http://stackoverflow.com/a/50692069
upvote count: 1
has title: python pandas dataframe groupby put same group together

http://stackoverflow.com/q/50688704
answer count: 1
tagged with: time
type: UnansweredQuestion
tagged with: python
has title: Why is NTP's root_delay so different to my measured roundtrip?
has body: When getting a Network Time Protocol packet (NTP version 4, see here): from contextlib import closing from socket import socket, AF_INET, SOCK_DGRAM import struct, time start = time.time() with closing(socket(AF_INET, SOCK_DGRAM)) as s: s.sendto('\x23' + 47 * '\0', ('pool.ntp.org', 123)) # NTP v4, see RFC 5905 msg, address = s.recvfrom(1024) now = time.time() I usually get a roundtrip time now - start around 40 milliseconds. However, with format = "!4b4h9I" unpacked = struct.unpack(format, msg[0:struct.calcsize(format)]) livnmode, stratum, poll, precision = unpacked[0:4] print 'root_delay', unpacked[4] + float(unpacked[5]) / 2**16 # https://www.rfc-editor.org/rfc/rfc5905#page-13 print 'root_dispersion', unpacked[6] + float(unpacked[7]) / 2**16 print 'ref_id', unpacked[8] print 'ref_timestamp %.3f' % (unpacked[9] + float(unpacked[10]) / 2**32 - 2208988800L) print 'orig_timestamp %.3f' % (unpacked[11] + float(unpacked[12]) / 2**32) print 'recv_timestamp %.3f' % (unpacked[13] + float(unpacked[14]) / 2**32 - 2208988800L) print 'tx_timestamp %.3f' % (unpacked[15] + float(unpacked[16]) / 2**32 - 2208988800L I get a root_delay of 0.00056 seconds which seems unlikely to be true! (I don't think I have a ping of 0.5 ms to time server, roundtrip time... this is really too small) Question: how is exactly root_delay measured in NTP protocol? Note: The RFC 5905 states: Root Delay (rootdelay): Total round-trip delay to the reference clock, in NTP short format. The more I relaunch the script, it seems that the root_delay decreases (even if my local computer RTC time isn't updated by my Python script... so that's strange...) My parsing of root_delay seems to be correct, see https://www.rfc-editor.org/rfc/rfc5905#page-19: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |LI | VN |Mode | Stratum | Poll | Precision | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Root Delay | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Root …
linked to: http://stackoverflow.com/q/26937857
tagged with: ntp
type: Question
score: 0
has answer: http://stackoverflow.com/a/52865886

http://stackoverflow.com/a/50556734
has comment: http://stackoverflow.com/comment/89977913
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88136261
has comment: http://stackoverflow.com/comment/88135902
type: Answer
has body: You can perform this with an .annotate(..) this with a Count(..) on the locations_of_interest number: from django.db.models import Count matching_profiles = Profile.objects.filter( locations_of_interest__in=question.locations.all() ).annotate( locnom=Count('locations_of_interest') ) Now every matching_profiles instance, will have an attribute called locnom that contains the number of location of interests that matched with the filter. Note that Profiles without such locations, will not be in the queryset, and that every Profile will occur at most once. EDIT: counting multiple related non-overlapping (!) fields You can extend this approach by counting non-overlapping joins, by using distinct=True: from django.db.models import Count matching_profiles = Profile.objects.filter( locations_of_interest__in=question.locations.all(), industries_of_interest__in=question.industries.all() ).annotate( locnom=Count('locations_of_interest', distinct=True), indnom=Count('industries_of_interest', distinct=True) ) Note however that this approach scales typically then exponentially with the number of JOINs, so this is typically not scalable if you would add tens our hundreds of annotations.
has comment: http://stackoverflow.com/comment/89978238
score: 2
accepted answer of: http://stackoverflow.com/q/50555817
has comment: http://stackoverflow.com/comment/89979750
answers question: http://stackoverflow.com/q/50555817
has comment: http://stackoverflow.com/comment/88136014
upvote count: 2

http://stackoverflow.com/q/50672238
tagged with: python
has body: I am trying to run a python script.py that has the line: from reptile.signals import new_signals reptile is a python package (not sure if that's the correct terminology) that someone wrote. Later in the scripy.py, there is the line: var = new_signals.Timing(clock=True) Timing is obviously a function in the new_signals code if I understand correctly. I need to find this Timing function to change some things, but I'm having problems trying to locate it. Could someone explain to me how I track down the path please?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50672805
has comment: http://stackoverflow.com/comment/88355122
has comment: http://stackoverflow.com/comment/88354399
has title: How to find a package / function?
type: Question
has answer: http://stackoverflow.com/a/50672805
tagged with: function
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88354707
tagged with: package

http://stackoverflow.com/comment/88424209
has text: I tried but I am getting all the old values in col_C and col_A is displayed Blank
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50690697

http://stackoverflow.com/comment/88321636
has text: Then you can go for Solution 1 as the temp is a list which you can further intersect with another list.
type: AnswerComment
comment on: http://stackoverflow.com/a/50655598
score: 0
type: Comment

http://stackoverflow.com/comment/88111370
has text: It doesn't help if you paste 50 of those strings here. I do not understand what it is! Your question stated two simple links now you add "stuff" and talk about lenght. I don't get it
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50550173
type: Comment

http://stackoverflow.com/comment/88345029
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50666299
has text: That works! Thanks!!
score: 0

http://stackoverflow.com/comment/88340589
comment on: http://stackoverflow.com/q/50665262
score: 0
type: Comment
type: QuestionComment
has text: you can try the following: Create a mask of everything that is not pure white. Erode this mask. set every pixel that is not masked to pure white.

http://stackoverflow.com/q/50682056
has body: I recently rearranged some folders around and a python file I used to run is no longer working. When I try to run the file I get: Traceback (most recent call last): File "twitter_stream.py", line 9, in &lt;module&gt; from tweepy import Stream ImportError: No module named tweepy I don't understand why I no longer have tweepy installed because I just had it When I do a simple 'pip3 install tweepy' I get: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/bin/pip3", line 7, in &lt;module&gt; from pip import main ImportError: cannot import name main I'm not sure what happened here. Any help would be greatly appreciated
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/88375081
has comment: http://stackoverflow.com/comment/88374593
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/88373878
has comment: http://stackoverflow.com/comment/88375313
has comment: http://stackoverflow.com/comment/88375864
score: 0
has comment: http://stackoverflow.com/comment/88374668
has comment: http://stackoverflow.com/comment/88374193
has comment: http://stackoverflow.com/comment/88374022
has title: ImportError: cannot import name main

http://stackoverflow.com/comment/88509421
type: Comment
comment on: http://stackoverflow.com/a/50702671
has text: It is a good way to solve that, but i probably use watson-machine-learnig-client to delete old deployment and model and create new one
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88207811
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50598347
has text: Could you please indent it properly, rather post it as an answer. It would very helpful and clear to the audience.

http://stackoverflow.com/comment/88253623
has text: @Mohammad Does my answer work for you?, if it does work, please accept my answer
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50619573
score: 0

http://stackoverflow.com/a/53387483
upvote count: 7
downvote count: 0
answers question: http://stackoverflow.com/q/50655738
type: Answer
has body: I face this same issue. I just use this command that will help me. sudo apt install tesseract-ocr Note that this will only work on Ubuntu. sudo is a Unix exclusive command (Linux, Mac, Rasbian, etc.) while apt is Ubuntu specific.
score: 7

http://stackoverflow.com/comment/88363269
score: 0
comment on: http://stackoverflow.com/q/50676650
type: Comment
type: QuestionComment
has text: Possible duplicate of [How do I generate circular thumbnails with PIL?](https://stackoverflow.com/questions/890051/how-do-i-generate-circular-thumbnails-with-pil)

http://stackoverflow.com/comment/88213330
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50602078
has text: if i want to check the number of affected rows so i can know if its one movie that has been selected or more i do this?
type: Comment

http://stackoverflow.com/comment/88367607
score: 0
type: AnswerComment
type: Comment
has text: Oh god, I knew about the custom function and I totally forgot that. Well I tried returning direct Model.objects.all() at the get_representaiton. It says cant be JSON serializable.
comment on: http://stackoverflow.com/a/50678701

http://stackoverflow.com/a/50565951
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88141987
has comment: http://stackoverflow.com/comment/88142089
has comment: http://stackoverflow.com/comment/88142066
has comment: http://stackoverflow.com/comment/88142161
downvote count: 5
answers question: http://stackoverflow.com/q/50565800
score: -3
type: Answer
has body: You can convert pyspark dataframe to pandas dataframe and use Transpose function %pyspark import numpy as np from pyspark.sql import SQLContext from pyspark.sql.functions import lit dt1 = [[1,2,4,5,6,7]] dt = sc.parallelize(dt1).toDF() dt.show() dt.toPandas().transpose() Output: Other solution dt2 = [{"1":1,"2":2,"4":4,"5":5,"6":29,"7":8}] df = sc.parallelize(dt2).toDF() df.show() a = [{"name":i,"value":df.select(i).collect()[0][0]} for i in df.columns ] df1 = sc.parallelize(a).toDF() print(df1)
has comment: http://stackoverflow.com/comment/88147175
has comment: http://stackoverflow.com/comment/88166018
accepted answer of: http://stackoverflow.com/q/50565800
has comment: http://stackoverflow.com/comment/88166485
has comment: http://stackoverflow.com/comment/88154080
upvote count: 2

http://stackoverflow.com/q/50591609
tagged with: python
favorite count: 0
possible better answer: http://stackoverflow.com/a/50591919
has answer: http://stackoverflow.com/a/50591919
has answer: http://stackoverflow.com/a/50591644
upvote count: 1
has comment: http://stackoverflow.com/comment/88192586
has title: Python loop to check rows in a column is null then replace
type: Question
type: AnsweredQuestion
score: 1
answer count: 2
accepted answer: http://stackoverflow.com/a/50591644
downvote count: 0
has comment: http://stackoverflow.com/comment/88192576
tagged with: pandas
has body: I am attempting to get a Non null value for the LastName, but I am receiving an error. How can I resolve this? p.s I have 20 millions rows. dataframe: FirstName Middle LastName Tom Ju NaN Kity NaN Rob my attemp: for row in df: if row['LastName'].isnull() == True: row['real_lastName'] = row['Middle'] else: row['real_lastName'] = row['LastName'] i have the following error TypeError: string indices must be integers

http://stackoverflow.com/comment/88386292
type: QuestionComment
type: Comment
has text: Something like: https://stackoverflow.com/a/21494630/6304086
comment on: http://stackoverflow.com/q/50688189
score: 0

http://stackoverflow.com/a/50556962
downvote count: 0
answers question: http://stackoverflow.com/q/50556875
type: Answer
accepted answer of: http://stackoverflow.com/q/50556875
upvote count: 3
has body: Split the list into two with the old zip(*lst) transpose trick, then sort the 2nd list and zip them back together: lst = [(1, "z"), (2, "a"), (3, "b")] lst1, lst2 = zip(*lst) result = list(zip(lst1, sorted(lst2))) # lst1: (1, 2, 3) # lst2: ('z', 'a', 'b') # result: [(1, 'a'), (2, 'b'), (3, 'z')]
score: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/88218727
type: QuestionComment
comment on: http://stackoverflow.com/q/50603904
has text: its executed every time you import that package. put `logger.initialize()` somewhere inside main, where you actually want to initialize
score: 0
type: Comment

http://stackoverflow.com/comment/88345857
comment on: http://stackoverflow.com/a/50646584
type: AnswerComment
type: Comment
score: 0
has text: I am having a hard time locating the element of the candles. Everything seems to have its own element as far as indicators go but when it comes to the candle, the only element I can figure out is the whole canvas of the chart. How do i find the position of the candle element?

http://stackoverflow.com/q/50684170
has title: Find complicated substring with wildcards Python
has answer: http://stackoverflow.com/a/50684803
accepted answer: http://stackoverflow.com/a/50684803
type: Question
has comment: http://stackoverflow.com/comment/88378374
has body: I am trying to locate the position of an expression in a long string. The expression works as follows. It is given by any element of list1, followed by wildcard of 1 to 5 words (separated by spaces) and followed by any element of list2. For example: list1=["a","b"], list2=["c","d"] text = "bla a tx fg hg gfgf tzt zt blaa a bli blubb d muh meh muh d" should return "37" since that is where the expression ("a bli blubb d") is found. I looked into regex wildcards, but I struggle to put that together with different elements of the lists and also the variable length of the wild cards. Appreciate any advice!
answer count: 1
downvote count: 0
tagged with: string
tagged with: wildcard
favorite count: 0
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88378327
upvote count: 2

http://stackoverflow.com/comment/88230934
has text: Thanks, I'm testing the code, when I get what I want, I'm gonna order it. Let me try with your advices
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50610170

http://stackoverflow.com/a/50704969
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50671502
answers question: http://stackoverflow.com/q/50671502
upvote count: 2
type: AcceptedAnswer
has body: I fixed it : just required a better understanding of vectors ship starts off with acceleration and velocity both stated as vectors. self.position = vec(screenx / 2, screeny / 2) self.vel = vec(0, 0) self.acceleration = vec(0, -0.2) # The acceleration vec points upwards from the starting ship position rotating the ship rotates that vector in place self.acceleration.rotate_ip(self.angle_speed) self.angle += self.angle_speed self.image = pygame.transform.rotate(self.imageorig, -self.angle) self.rect = self.image.get_rect(center=self.rect.center) accelerating is this : self.vel += self.acceleration * self.enginepower * globaltimefactor updating position : self.position += self.vel self.rect.center = self.position I was making it harder than it needed to be, velocity needed to be constant until acted upon by the rotated acceleration vector. I didn't know how to add vectors together etc.
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/95631460

http://stackoverflow.com/q/50678090
upvote count: 3
downvote count: 3
has title: regex to match number followed by space followed by 2 char
has body: I have a requirement in my python app to match 2 to 7 digit number followed by a string with 2 chars in caps. Examples - 6892 NY, 12382 OP If these pattern appear anywhere in a line of text, need to add the two words(number and 2 chars) as one string to a list. Any insights how we can achieve this?
type: Question
accepted answer: http://stackoverflow.com/a/50678110
answer count: 1
score: 0
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50678110
tagged with: regex
type: AnsweredQuestion

http://stackoverflow.com/q/50639973
tagged with: macos
favorite count: 0
possible better answer: http://stackoverflow.com/a/56658280
tagged with: python-3.x
score: 12
type: Question
answer count: 2
has body: I think I have some issues with either Python and/or pip on my Mac. I have Python 2.7 installed globally and then I normally setup virtualenvs and install Python3.6.4 but in the last day or so Ive been getting problems with packages such as Fabric and SSH2 where I have either not been able to install them with various errors or with Fabric it throws when I try to import the package. Im now trying to remove Fabric and install Fabric3 and its throwing errors like this: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/Users/david/Documents/projects/uptimeapp/env/lib/python3.6/site-packages/Fabric3-1.14.post1.dist-info' Consider using the `--user` option or check the permissions. (env) Davids-MacBook-Air:uptimeapp david$ pip install fabric3 --user Can not perform a '--user' install. User site-packages are not visible in this virtualenv. If I do sudo pip install fabric then it installs but with this warning: The directory '/Users/david/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/david/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. But I thought it was not advised to pip install with sudo? These are the errors I get when I try to pip install ssh2-python ssh2/agent.c:569:10: fatal error: 'libssh2.h' file not found #include "libssh2.h" ^~~~~~~~~~~ 1 error generated. error: command 'clang' failed with exit status 1 ---------------------------------------- Command "/Users/david/Documents/projects/uptimeapp/env/bin/python3.6 -u -c "import setuptools, tokenize;__file__='/private/var/folders/bl/97vt48j97zd2sj05zmt4xst00000gn/T /pip-install-mpyq41q4/ssh2-python/setu…
tagged with: pip
tagged with: python
has title: Pip problems - Could not install packages due to an EnvironmentError
has answer: http://stackoverflow.com/a/50643145
accepted answer: http://stackoverflow.com/a/50643145
upvote count: 12
has answer: http://stackoverflow.com/a/56658280
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/50632209
upvote count: 2
has comment: http://stackoverflow.com/comment/88275110
has comment: http://stackoverflow.com/comment/88274827
has answer: http://stackoverflow.com/a/50632307
possible better answer: http://stackoverflow.com/a/50632304
has comment: http://stackoverflow.com/comment/88274590
has answer: http://stackoverflow.com/a/50632304
has answer: http://stackoverflow.com/a/50633539
answer count: 5
has title: Most computationally efficient way to build a Python list with repeating and iterating numbers like [0, 0, 0, 1, 1, 1, 2, 2, 2 . . . ,etc]
has comment: http://stackoverflow.com/comment/88274617
has comment: http://stackoverflow.com/comment/88353235
has body: I want to make an array that looks something like [0, 0, 0, 1, 1 , 1, 2, 2, 2, . . .etc] or [4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, . . . etc] There is something like segments = [i for i in range(32)] which will make [ 1, 2, 3, 4, 5, . . . etc] There are ways where I can call 3 separate sets of i in range(32) but I am looking to save computation by only calling it once. What's the most computationally efficient and programatically elegant way of making array like [0, 0, 0, 1, 1 , 1, 2, 2, 2, . . .etc]
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50632307
downvote count: 0
has comment: http://stackoverflow.com/comment/88274821
favorite count: 0
has comment: http://stackoverflow.com/comment/88274916
has answer: http://stackoverflow.com/a/50632316
linked to: http://stackoverflow.com/q/41772054
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/88275457
has comment: http://stackoverflow.com/comment/88274970
has comment: http://stackoverflow.com/comment/88274885
has comment: http://stackoverflow.com/comment/88274767
has answer: http://stackoverflow.com/a/50632272

http://stackoverflow.com/comment/88320323
comment on: http://stackoverflow.com/a/50646990
has text: Yes m is an integer and they are hermitian.
score: 0
type: AnswerComment
type: Comment

logistic-regression
tags question: http://stackoverflow.com/q/50671283
tags question: http://stackoverflow.com/q/50567008
tags question: http://stackoverflow.com/q/50590414
type: Tag
tags question: http://stackoverflow.com/q/50662425
tag name: logistic-regression
tags question: http://stackoverflow.com/q/50547709
tags question: http://stackoverflow.com/q/50544917
tags question: http://stackoverflow.com/q/50693445

http://stackoverflow.com/q/50648538
has comment: http://stackoverflow.com/comment/138830626
tagged with: python-typing
linked to: http://stackoverflow.com/q/44225788
has answer: http://stackoverflow.com/a/50648582
tagged with: mypy
type: AnsweredQuestion
upvote count: 5
has answer: http://stackoverflow.com/a/50650567
type: Question
has title: mypy set dictionary keys / interface
answer count: 2
score: 5
accepted answer: http://stackoverflow.com/a/50648582
possible better answer: http://stackoverflow.com/a/50650567
downvote count: 0
has body: Suppose I have a function which takes a dictionary as a parameter: def f(d: dict) -> None: x = d["x"] print(x) Can I specify that this dictionary must have the key "x" to mypy? I'm looking for something similar to interface from typescript, without changing d to a class. The reason I don't want to change d to a class, is because I am modifying a large existing codebase to add mypy type checking and this dictionary is used in many places. I would have to modify a lot of code if I had to change all instances of d["x"] to d.x.
favorite count: 0
tagged with: python

unit-testing
tags question: http://stackoverflow.com/q/50610557
tags question: http://stackoverflow.com/q/50576123
tags question: http://stackoverflow.com/q/50621689
tags question: http://stackoverflow.com/q/50643767
tags question: http://stackoverflow.com/q/50690373
tags question: http://stackoverflow.com/q/50689940
tags question: http://stackoverflow.com/q/50682674
tags question: http://stackoverflow.com/q/50685563
tags question: http://stackoverflow.com/q/50595750
tags question: http://stackoverflow.com/q/50580443
tags question: http://stackoverflow.com/q/50614437
tags question: http://stackoverflow.com/q/50592219
type: Tag
tags question: http://stackoverflow.com/q/50589552
tags question: http://stackoverflow.com/q/50544674
tags question: http://stackoverflow.com/q/50660497
tags question: http://stackoverflow.com/q/50691692
tag name: unit-testing
tags question: http://stackoverflow.com/q/50563741
tags question: http://stackoverflow.com/q/50603092
tags question: http://stackoverflow.com/q/50637346
tags question: http://stackoverflow.com/q/50568485

http://stackoverflow.com/a/50725432
type: Answer
has comment: http://stackoverflow.com/comment/88459473
score: 0
answers question: http://stackoverflow.com/q/50623188
has body: It's hard to understand what exactly don't work: The code you showed? If yes I'm guessing that it's "key_transformator" that is missing. It probably have a function that encode the key based on some algorithm. Maybe you trying to decrypt a file made by this code (is this a CTF challenge?): Even if you have the missing function you'll still need the original random key. If you have it you need to xor it with the first one you're file and then find a way to understand what was the next key

http://stackoverflow.com/q/50565080
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/50565730
tagged with: http://stackoverflow.com/tag/r
tagged with: arguments
tagged with: python
possible better answer: http://stackoverflow.com/a/50565730
accepted answer: http://stackoverflow.com/a/50565247
favorite count: 0
has body: Is there a way to make the first argument of a function optional? myFunction &lt;- function(a = NULL, b, c) { if(!is.null(a)) { d &lt;- a + c } else { d &lt;- b +c } return(d) } myFunction(1, 2) # Fails, because c is missing In a way, this is obvious, because the unnamed arguments are matched in the order they are given. But on the other hand, R could also try to look at the number of arguments given and deduce that it must be the optional argument which is missing. My example is in R, but the same principle is as far as I know true in Python.
upvote count: 1
has comment: http://stackoverflow.com/comment/88141466
has comment: http://stackoverflow.com/comment/88140282
tagged with: parameters
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/50565247
answer count: 2
tagged with: function
has title: Having first of unnamed arguments optional

event-handling
tag name: event-handling
tags question: http://stackoverflow.com/q/50689598
type: Tag

http://stackoverflow.com/q/50631393
has comment: http://stackoverflow.com/comment/88272814
has answer: http://stackoverflow.com/a/50631482
has answer: http://stackoverflow.com/a/60759947
tagged with: http://stackoverflow.com/tag/json
possible better answer: http://stackoverflow.com/a/50650321
type: Question
linked to: http://stackoverflow.com/q/14882138
has answer: http://stackoverflow.com/a/50631555
answer count: 6
upvote count: 3
has body: Say that I have a JSON file whose structure is either unknown or may change overtime - I want to replace all values of "REPLACE_ME" with a string of my choice in Python. Everything I have found assumes I know the structure. For example, I can read the JSON in with json.load and walk through the dictionary to do replacements then write it back. This assumes I know Key names, structure, etc. How can I replace ALL of a given string value in a JSON file with something else?
has answer: http://stackoverflow.com/a/50632306
accepted answer: http://stackoverflow.com/a/50632306
downvote count: 0
has answer: http://stackoverflow.com/a/50650321
favorite count: 0
has title: Python replace values in unknown structure JSON file
tagged with: python
has answer: http://stackoverflow.com/a/50631476
type: AnsweredQuestion
score: 3

featuretools
tag name: featuretools
type: Tag
tags question: http://stackoverflow.com/q/50636819

http://stackoverflow.com/a/50695777
downvote count: 0
has body: For a single series, I often prefer to map a series rather than merge or join (both also valid options, if used correctly). Note I assume you have already applied str conversion to all columns as appropriate. s = df2.set_index('Reporter')['Reporter Location'] df['Reporter Location'] = df['Reporter'].map(s) In general, there is no need for converting your series to dict or for using zip on pd.Series objects. Using zip with numpy arrays can be inefficient.
answers question: http://stackoverflow.com/q/50691189
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50691189
type: Answer
score: 2

http://stackoverflow.com/q/50676185
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/88433621
score: 2
upvote count: 2
has body: The process I am following is - Converting Avro to JSON Then converting JSON to CSV Is there any direct way to convert the Avro file to CSV?
tagged with: bigdata
has title: How to convert Avro file to CSV file in python?
type: Question
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/57241263
downvote count: 0

http://stackoverflow.com/q/50644641
has comment: http://stackoverflow.com/comment/88300316
answer count: 1
tagged with: variables
has comment: http://stackoverflow.com/comment/88299876
has comment: http://stackoverflow.com/comment/88300013
tagged with: angularjs
has comment: http://stackoverflow.com/comment/88300170
tagged with: python
type: UnansweredQuestion
tagged with: web-frontend
has title: AngularJS- how to change value of backend Python variable from AngularJS frontend function?
has comment: http://stackoverflow.com/comment/88299955
type: Question
tagged with: javascript
has body: I am currently working on a web based application, for which the back end has been developed using Django & Python, and the front end has been developed using AngularJS. There is a form on one of the pages in the front end, which the user can use to export data that has been recorded & stored in the back end to a spreadsheet. All of the data recorded in the back end is 'time sensitive', and at present, there is only one time zone set in the back end (UTC). I want to 'create' settings for adding multiple new time zones, so that the data recorded can be exported in different time zones. The time zone is set in project/apps/appAbc/abc/settings.py with: class Production(Settings): ... TIME_ZONE = 'UTC' ... The 'Export' form has a number of fields (preset, type of data, sort data by quantity/ period, file type to export to), and I have just added a 'Timezone' drop down to it: ... and in Pages/directive.js, I have added multiple timezones to the ulTimezonePicker controller: .directive('ulTimezonePicker', function() { return { ... controller: function ($scope) { $scope.options = [{label: 'UTC', value: 0}, // Add in other timezones {label: 'GMT', value: 1}, {label: 'BST', value: 2}, ]; ... ... }) The selectTimezone() function that is called by the ul-timezone-picker field on the form is defined in project/libs/front/app/scripts/app/pages/exportCtrl.js with: angular.module('app.pages').controller('ExportCtrl', function(...) { ... $scope.selectTimezone = function(option){ if(option) { $scope.timezone = option; if(option.label != $scope.presetTimezone) { $scope.presetTimezone = undefined; } } }; ... } } So, my question is, how do I get the selectTimezone() function to actually change the value of the TIME_ZONE variable defined in settings.py? I tried declaring an instance of the variable within the function with: Production.TIME_ZONE = $scope.timezone; But when I do this, and view the page that has the form on it in a browser, the browser console gives me an error stating: Ref…
has answer: http://stackoverflow.com/a/50644812
score: 0

http://stackoverflow.com/comment/88164296
comment on: http://stackoverflow.com/a/50557133
has text: @dejsdukes this means that your data is not a valid JSON data.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50688017
has comment: http://stackoverflow.com/comment/88385778
has comment: http://stackoverflow.com/comment/88385836
upvote count: 0
answer count: 1
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50688114
score: -1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88385841
has body: I have a Python program which has a variable access_token in class1. In the constructor it is set to self.access_token = "". I want to update it from class2 to the token value. I've tried calss1.access_token = token_value but it remains unchanged. What am I doing wrong?
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88385920
has title: Update a variable from a different class
has answer: http://stackoverflow.com/a/50688114
type: Question

http://stackoverflow.com/a/50622887
score: 1
accepted answer of: http://stackoverflow.com/q/50622587
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50622587
type: Answer
upvote count: 1
has body: The type of self.A is a numpy array, which is mutable. This means that when you change self.A, matrix will be changed as well. If you want matrix to be equal to the value of self.A at the moment of the assignment, and for it not to be changed after, you need to make a copy: matrix = numpy.copy(self.A)

http://stackoverflow.com/comment/88323023
has text: You want to compare the `x` of a human object (i.e. `human1.x`) and not of the entire class: `def checkpos(self, human): if (self.x-human.x)**2<2: pass` and then call this for all pairs `alien1.checkpos(human1)` ... You can - for now - not call `Human.x` but only `human1.x` for any created `Human` called `human1`
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50656121
type: Comment

twilio
tag name: twilio
type: Tag
tags question: http://stackoverflow.com/q/50682248

http://stackoverflow.com/q/50585496
score: 1
upvote count: 1
tagged with: gevent
type: Question
downvote count: 0
answer count: 1
tagged with: flask
has body: I am trying to run multiple concurrent downstream requests using gevent in my flask application. I have: import gevent from gevent import monkey monkey.patch_all(thread=False) from flask import Flask, request, g app = Flask(__name__, static_folder='static') and the following code: def f1(self): @copy_current_request_context def _test(t): time.sleep(t) r = requests.get( 'https://webhook.site/d14a41a6-9c6a-4da0-bbe6-3cc660daea3d', params=dict(word='test') ) return r.status_code jobs = [gevent.spawn(_test, 5), gevent.spawn(_test, 10)] results = [job.value for job in gevent.joinall(jobs)] return None If the second _test is taking longer than the first one I am getting a Popped wrong app context error. If I add another method like: @copy_current_request_context def _test_bis(t): from random import randint time.sleep(t) r = requests.get( 'https://webhook.site/d14a41a6-9c6a-4da0-bbe6-3cc660daea3d', params=dict(word='test') ) return r.status_code and use it like that: jobs = [gevent.spawn(_test_bis, 5), gevent.spawn(_test, 10)] I don't have any error. Any idea how I could work around that issue?
favorite count: 0
has title: Popped wrong app context when using gevent.spawn
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51334609

least-squares
tags question: http://stackoverflow.com/q/50644572
tags question: http://stackoverflow.com/q/50587012
tag name: least-squares
type: Tag

http://stackoverflow.com/q/50552644
tagged with: python
tagged with: valueerror
has body: Running the following code import pandas as pd import matplotlib.pylab as plt df1=pd.read_csv("/Users/ee1.xlsx") Getting an error back as ValueError: too many values to unpack I can't figure out what I'm doing wrong. Going out of my mind to trying to resolve this. I'm running Spyder python 2.7 in Anaconda
type: UnansweredQuestion
tagged with: dataframe
has title: Reading excel/CSV into python
tagged with: import
type: Question
has answer: http://stackoverflow.com/a/50552658
answer count: 1
score: 0

http://stackoverflow.com/a/58504113
answers question: http://stackoverflow.com/q/50557234
has body: If you are looking for the solution of following error ERROR: Could not install packages due to an EnvironmentError: [WinError 5] Acces s is denied: 'D:\softwares\spider\Lib\site-packages\libmysql.dll' Consider using the --user option or check the permissions. The solution: You should add --user if you find an access-denied error. pip install --user mysql-connector-python paste this command into cmd and solve your problem
upvote count: 1
downvote count: 1
score: 0
type: Answer

http://stackoverflow.com/a/50592161
answers question: http://stackoverflow.com/q/50592013
upvote count: 1
has body: ':.*\.(\d+)(\w&gt;\w)' :.*\. looks for : and any character (since your example has both 'g' and 'm') up to the period before the area we want to capture. First Group: (\d+) matches 1 or more digits. Second Group: (\w&gt;\w) matches word character followed by &gt; followed by word character
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/88163482
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50576540
has text: You first should get correct picture for a simpler problem - no drag. Therefore set `c = 0` and check what you get. And then you will realize that `z[3] = -g/m` (which you define as `z[3] = acceleration in y direction`) **makes no sense at all**: your acceleration is proportional to `g` (already an acceleration) divided by mass!
score: 0

http://stackoverflow.com/q/50649875
favorite count: 0
tagged with: python-3.x
has title: Mapping arbitrary length list to fixed length, preserving frequency and position of internal results (as much as possible)
type: Question
tagged with: python
has body: BACKSTORY: Getting data together to feed into a neural network; starts as a document (long string); gets split into sentences, sentences are reduced to 1 or 0 depending on if they have a feature (in this case, class of word) or not. The catch is that documents have different numbers of sentences, so it can't be a 1-1 between sentences and input neurons; you have to train to a fixed number of neurons (unless I'm missing something). So, I'm working on an algo to map arrays to a fixed size, while preserving the frequency and position of those 1's in the array as much as possible (as that's what the NN is making its decisions off of. CODE: say we're aiming for a fixed length of 10 sentences or neurons, and need to be able to handle arrays of smaller and larger size. new_length = 10 short = [1,0,1,0,0,0,0,1] long = [1,1,0,0,1,0,0,0,0,1,0,0,1] def map_to_fixed_length(arr, new_length): arr_length = len(arr) partition_size = arr_length/new_length res = [] for i in range(new_length): slice_start_index = int(math.floor(i * partition_size)) slice_end_index = int(math.ceil(i * partition_size)) partition = arr[slice_start_index:slice_end_index] val = sum(partition) res.append([slice_start_index, slice_end_index, partition]) if val &gt; 0: res.append(1) else: res.append(0) return res Not very pythonic probably. Anyways, the issue is that this is ommits certain index-slices. For example, the last index of short is omitted, and due to the rounding various indexes get omitted as well. This is a simplified version of what I've been working on, which is mainly just adding if-statements to address all the gaps this leaves. But is there a better way to do this? Something a bit more statistically sound? I was looking through numpy but all the resize functions are just padding with zeros or something pretty arbitrarily.
has answer: http://stackoverflow.com/a/50650341
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/50703675
tagged with: algorithm
possible better answer: http://stackoverflow.com/a/50703675
has comment: http://stackoverflow.com/comment/88310851
accepted answer: http://stackoverflow.com/a/50650341
has comment: http://stackoverflow.com/comment/88311352
has comment: http://stackoverflow.com/comment/88313478
type: AnsweredQuestion
score: 2
downvote count: 0

http://stackoverflow.com/q/50607990
has body: I've a task to parse Cisco ACE config. I'm using python textFSM module. This template should parse "serverfarm " part of the config: Value Required Serverfarm_name (\S+) Value load_balance_method (\S+) Value probe_name (\S+) Value List rserver_name (\S*) Start ^serverfarm\s+host\s+$Serverfarm_name ^\s+predictor\s+$load_balance_method ^\s+probe\s+$probe_name ^\s+rserver\s+$rserver_name -&gt; RServer RServer ^\s+rserver\s+$rserver_name -&gt; Continue.Record ^\s+inservice Part of the Cisco ACE config: ...... serverfarm host SF-TEST1-3.8083 predictor hash address source probe TEST-3.8083 rserver lala_server438 inservice rserver lala_server439 inservice serverfarm host SF-TEST1-4.8084 predictor hash address source probe TEST-4.8084 rserver lala_server438 inservice rserver lala_server439 inservice serverfarm host SF-TEST1-5.8085 predictor hash address source probe TEST-5.8085 rserver lala_server438 inservice rserver lala_server439 inservice ...... After running ace.py script I don't have desired result as a textFSM table : $ ./ace.py --- [2018-05-30 16:47:52.892697] --- Start Timestamp --- --- [+0.000116 sec] --- Parse: ./textFSM/ace_serverfarm_template.textfsm --- ['Serverfarm_name', 'load_balance_method', 'probe_name', 'rserver_name'] ['SF-TEST1-3.8083', 'hash', 'TEST-3.8083', ['lala_server438', 'lala_server439']] Write 1 records What is my error in the template file? How to change it in order to parse every serverfarm. (I've only first record as a result)?
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/64056956
tagged with: python
tagged with: python-textfsm
type: Question
has answer: http://stackoverflow.com/a/50610095
has title: python-textFSM parse multiple line config
score: 0

http://stackoverflow.com/q/50649830
score: 4
upvote count: 4
has body: I'm writing some Python code that's being checked with pylint with the docparams extension. This requires documenting function parameters in their docstrings. I have a tendency to try to decompose functions as much as possible and end up with lots of functions that call other functions - often sharing many of the same parameters. This can lead to lots of redundant (copy-pasted) documentation in the docstrings. Is there a recommended way of dealing with this type of situation?
has answer: http://stackoverflow.com/a/50649904
answer count: 1
downvote count: 0
tagged with: docstring
favorite count: 0
type: UnansweredQuestion
tagged with: pylint
tagged with: python
has title: Reducing redundancy in Python doc-strings while using pylint docparams
type: Question

http://stackoverflow.com/q/50627218
favorite count: 0
has body: I recently started using Python and I have no idea how to do this exercise, I know arange works like a=np.arange(start,stop,step), but how do I enter my own variables ? Here is the exercise i have to do: Using the arange function, create a Numpy table consisting of 20 consecutive multiples of the number 2
has comment: http://stackoverflow.com/comment/88264578
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88264585
has comment: http://stackoverflow.com/comment/88264553
tagged with: python
upvote count: 0
type: Question
has comment: http://stackoverflow.com/comment/88264673
type: AnsweredQuestion
has title: Numpy arange of 2^x
score: -2
accepted answer: http://stackoverflow.com/a/50628192
has comment: http://stackoverflow.com/comment/88264790
has comment: http://stackoverflow.com/comment/88264769
has comment: http://stackoverflow.com/comment/88264489
tagged with: numpy
has comment: http://stackoverflow.com/comment/88264518
downvote count: 2
has comment: http://stackoverflow.com/comment/88264849
has answer: http://stackoverflow.com/a/50628192
answer count: 1
has comment: http://stackoverflow.com/comment/88264568

http://stackoverflow.com/comment/99345477
type: AnswerComment
type: Comment
has text: This is code for reading CSV file from AWS S3 path store it with Parquet format with partition in AWS S3 path.
score: 1
comment on: http://stackoverflow.com/a/56371671

http://stackoverflow.com/a/50558168
has comment: http://stackoverflow.com/comment/88127480
type: Answer
has body: I am a beginner but I don’t think it will work to use a.remove, since removing an item from the list will screw up the indexing for future items. It’s a better solution to create a new list and append items that don’t contain ‘VOST’.
answers question: http://stackoverflow.com/q/50558056
score: 0

http://stackoverflow.com/q/50547519
tagged with: telnet
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/68786058
type: Question
tagged with: telnetlib
has body: I've been trying to write a code that allows me to get a file from a telnet server and I want to if we can include variables in telnet write function. Here is my code. import telnetlib import sys import getpass host = "192.168.1.1" tn = telnetlib.Telnet(host, "23") tn.write((" \n").encode('ascii')) tn.write((" \n").encode('ascii')) tn.write(("terminal length 1000 \n").encode('ascii')) tn.write(("terminal width 24 \n").encode('ascii')) tn.write(("""copy command-output "show tech all" tftp 192.168.1.10 test.txt \n""").encode('ascii')) tn.write(("exit \n").encode('ascii')) tn.write(("exit \n").encode('ascii')) tn.write(("y").encode('ascii')) print (tn.read_all()) This the command that is being sent and it should be in a single string. copy command-output "show tech all" tftp 192.168.1.10 test.txt Instead of test.txt I want to make it host.txt For example in the above code host == 192.168.1.1, so essentially the file name should be 192.168.1.1.txt, is this possible?
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
has title: how do I add a variable into the telnet write command
has comment: http://stackoverflow.com/comment/88107779
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/50651988
has body: A ttk.Treeview without the tree part can be used to display a table: tree = ttk.Treeview(master, columns=('Position', 'Name', 'Score'), show='headings') Then set the column labels with tree.heading(&lt;column&gt;, text="Label") and add rows with tree.insert("", "end", values=(&lt;position&gt;, &lt;name&gt;, &lt;score&gt;)) The first argument is the item's parent, since you want a table, all items have the same parent, the root "". The second argument is the position of the new item in the tree. Full example: import tkinter as tk from tkinter import ttk def show(): tempList = [['Jim', '0.33'], ['Dave', '0.67'], ['James', '0.67'], ['Eden', '0.5']] tempList.sort(key=lambda e: e[1], reverse=True) for i, (name, score) in enumerate(tempList, start=1): listBox.insert("", "end", values=(i, name, score)) scores = tk.Tk() label = tk.Label(scores, text="High Scores", font=("Arial",30)).grid(row=0, columnspan=3) # create Treeview with 3 columns cols = ('Position', 'Name', 'Score') listBox = ttk.Treeview(scores, columns=cols, show='headings') # set column headings for col in cols: listBox.heading(col, text=col) listBox.grid(row=1, column=0, columnspan=2) showScores = tk.Button(scores, text="Show scores", width=15, command=show).grid(row=4, column=0) closeButton = tk.Button(scores, text="Close", width=15, command=exit).grid(row=4, column=1) scores.mainloop() You can find more details about the Treeview widget here.
upvote count: 24
score: 24
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50625306

http://stackoverflow.com/comment/88402785
comment on: http://stackoverflow.com/a/50696442
type: AnswerComment
score: 0
type: Comment
has text: df1['ID'] = df1['ID'].mask(df['ID'].duplicated(), '') what is df here?

http://stackoverflow.com/a/50991144
downvote count: 0
answers question: http://stackoverflow.com/q/50635449
type: AcceptedAnswer
has body: It looks like you wound up with a Windows-native Python on your system's PATH environment variable that is being inserted somehow even before Cygwin's /bin paths, so tox is finding and trying to run that Python instead of Cygwin's Python. In general you shouldn't use the Windows Python from Cygwin unless there's a very specific reason to do so. From the comments, you mentioned you have TortoiseHG installed. I don't know exactly how TortoiseHG works on Windows, but as Mercurial is written in Python, TortoiseHG must either come with a Python interpreter, or at least use any Python interpreter it finds on Windows (possibly using a virtualenv), so if TortoiseHG has a PATH entry make sure it's still after your Cygwin {/,/usr/,/usr/local/}bin.
accepted answer of: http://stackoverflow.com/q/50635449
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/88399994
type: Comment
has text: looks good, thanks. I'll just wait a bit to see if there is a more elegant solution and mark your solution if not. Just note the `ix` has been deprecated, so it will be better to use `loc`
type: AnswerComment
comment on: http://stackoverflow.com/a/50695018
score: 0

http://stackoverflow.com/q/50687324
linked to: http://stackoverflow.com/q/46168132
type: Question
linked to: http://stackoverflow.com/q/11348953
accepted answer: http://stackoverflow.com/a/50707579
answer count: 1
tagged with: macos
tagged with: python-3.x
has body: I am trying to use SetFile to change MacOS file creation and modification date (see here). My problem is somewhat similar to this one but even by following the advice there I can't get it to work and get an error 1 in return (bad syntax) Here is the code: file_t = obj.decided_stamp.strftime('%m/%d/%Y %H:%M:%S') # Use SetFile to change creation and modification date cmd = ['SetFile', '-d', '-m', '{0}{1}{0}'.format('\'', file_t), '{0}{1}{0}'.format('\'', obj.path)] try: check_output(cmd, shell=True) except Exception as e: logger.warning('Error {} on {} using {}'.format(e, obj.path, cmd)) If I take away the shell=True I get error 2 (other error), using shell gives be the error 1. Here is an example of warning print I get: 2018-06-04 21:06:06 main[84988] WARNING Error Command '['SetFile', '-d', '-m', &quot;'01/13/2017 14:55:55'&quot;, &quot;'/Volumes/Images/2017-01-12 Conference/2017-01-13 14.55.55.jpg'&quot;]' returned non-zero exit status 2. on /Volumes/Images/2017-01-12 Conference/2017-01-1314.55.55.jpg using ['SetFile', '-d', '-m', &quot;'01/13/2017 14:55:55'&quot;, &quot;'/Volumes/Images/2017-01-12 Conference/2017-01-13 14.55.55.jpg'&quot;] Any idea what I am doing wrong there ? Thanks
tagged with: python
has title: Subprocess check_output not working with SetFile (Mac)
type: AnsweredQuestion
tagged with: subprocess
score: 0
has answer: http://stackoverflow.com/a/50707579

http://stackoverflow.com/comment/88346172
type: Comment
comment on: http://stackoverflow.com/a/50667396
score: 0
type: AnswerComment
has text: Thanks but suppose my calculation should be sum(value/index) so probably using yours udf funcrtion I should return some kind of reduce(add,)?

http://stackoverflow.com/comment/88193953
has text: @Alpit Anand , do not provide the complete script, but just relevant part
comment on: http://stackoverflow.com/q/50591612
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50572080
upvote count: 2
has body: You can also only add on columns b and c. df"b", "c" += np.where(df"b", "c" &gt; 0, 0.01, 0) We use np.where to fill in 0 as to bypass np.nan in the data. Anton vBR has an elegant way to select columns one need.
has comment: http://stackoverflow.com/comment/88153748
answers question: http://stackoverflow.com/q/50571570
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/50570334
favorite count: 0
has answer: http://stackoverflow.com/a/50570529
has answer: http://stackoverflow.com/a/50570478
tagged with: python
has answer: http://stackoverflow.com/a/50570547
answer count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50570473
possible better answer: http://stackoverflow.com/a/50570547
has title: Rotation of the numbers-python
linked to: http://stackoverflow.com/q/986006
type: Question
has body: To find the rotations of a number I wrote a code like def rotation(N): A=[] for i in range(len(N)): y=N.pop(0) N.append(y) A.append(N) return A K=[1,9,7] r=rotation(K) print(r) but it gives me an output like: A=[[1, 9, 7], [1, 9, 7], [1, 9, 7]] but it should be A=[[1,9,7],[9,7,1],[7,1,9]] and I didnt understand why this happens thanks
score: 5
upvote count: 5
linked to: http://stackoverflow.com/q/9696495
has answer: http://stackoverflow.com/a/50570473
downvote count: 0

plot
tags question: http://stackoverflow.com/q/50624643
tags question: http://stackoverflow.com/q/50576224
tags question: http://stackoverflow.com/q/50657903
tags question: http://stackoverflow.com/q/50696080
tags question: http://stackoverflow.com/q/50680753
tags question: http://stackoverflow.com/q/50608053
tags question: http://stackoverflow.com/q/50603077
tags question: http://stackoverflow.com/q/50629537
tags question: http://stackoverflow.com/q/50658806
tags question: http://stackoverflow.com/q/50689123
tag name: plot
tags question: http://stackoverflow.com/q/50668453
tags question: http://stackoverflow.com/q/50550772
tags question: http://stackoverflow.com/q/50543965
tags question: http://stackoverflow.com/q/50621257
tags question: http://stackoverflow.com/q/50627827
tags question: http://stackoverflow.com/q/50553698
tags question: http://stackoverflow.com/q/50626458
tags question: http://stackoverflow.com/q/50653410
tags question: http://stackoverflow.com/q/50605601
tags question: http://stackoverflow.com/q/50654981
tags question: http://stackoverflow.com/q/50561839
tags question: http://stackoverflow.com/q/50612340
tags question: http://stackoverflow.com/q/50662685
tags question: http://stackoverflow.com/q/50547708
type: Tag
tags question: http://stackoverflow.com/q/50555367
tags question: http://stackoverflow.com/q/50590900
tags question: http://stackoverflow.com/q/50590212
tags question: http://stackoverflow.com/q/50604214
tags question: http://stackoverflow.com/q/50662831
tags question: http://stackoverflow.com/q/50602569
tags question: http://stackoverflow.com/q/50693223
tags question: http://stackoverflow.com/q/50601505
tags question: http://stackoverflow.com/q/50599141

http://stackoverflow.com/comment/88315756
comment on: http://stackoverflow.com/q/50652473
has text: @BurhanKhalid I have provided a sample of the raw data in a response above. I trust this is what you are referring to. I used PyPDF2 .extractText() to read
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50673330
type: Answer
answers question: http://stackoverflow.com/q/50671528
score: 0
has body: I like to use the cycle function from itertools for this purpose: from itertools import cycle from turtle import Turtle, Screen COLORS = ["pink", "navy blue", "red", "forest green", "cyan", "magenta"] def main(): t = Turtle(visible=False) t.speed('fastest') color_iter = cycle(COLORS) squaredesign(t, color_iter) def squaredesign(t, color_iter): x = 100 y = 100 for _ in range(10): t.pencolor(next(color_iter)) t.penup() t.goto(x, y) t.pendown() t.goto(x - x - x, y) t.goto(x - x - x, y - y - y) t.goto(x, y - y - y) t.goto(x, y) x -= 10 y -= 10 screen = Screen() main() screen.mainloop() It never runs out of colors as it just starts over from the beginning after it reaches the end. The modulus operator (%) is another approach you can use to solve this problem: from turtle import Turtle, Screen COLORS = ["pink", "navy blue", "red", "forest green", "cyan", "magenta"] def main(): t = Turtle(visible=False) t.speed('fastest') color_index = 0 squaredesign(t, color_index) def squaredesign(t, color_index): x = 100 y = 100 for _ in range(10): t.pencolor(COLORS[color_index]) t.penup() t.goto(x, y) t.pendown() t.goto(x - x - x, y) t.goto(x - x - x, y - y - y) t.goto(x, y - y - y) t.goto(x, y) x -= 10 y -= 10 color_index = (color_index + 1) % len(COLORS) screen = Screen() main() screen.mainloop() Which avoids the additional import.

http://stackoverflow.com/a/50661348
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/88438145
score: 4
has body: Thanks for the quick answer raratiru! It brought me on the idea to look into the code of the django-embed-video app itself. I fiddled around with it a bit and now it works just how I wanted it to work. The relevant code is: videos.html {% load embed_video_tags %} {% for v in videos %} {% video v.video as my %} {% endvideo %} {% endfor %}
answers question: http://stackoverflow.com/q/50655843
type: Answer

http://stackoverflow.com/comment/88278481
type: QuestionComment
has text: @ALollz Sure -- but I pay the same overhead when n=10. Costs are increasing significantly as the size of the map table increases. This is not right.
comment on: http://stackoverflow.com/q/50633939
score: 0
type: Comment

http://stackoverflow.com/q/50698291
has body: Let us assume I have the following models class Blog(models.Model): user = models.ForeignKey(User, null=False, on_delete=models.CASCADE) class Post(models.Model): blog = models.ForeignKey(Blog, null=False, on_delete=models.CASCADE) post = models.TextField() The problem is that creating a Post will let me set the blog id to anything (that exists). That means that I am able to create a Post object that has a relation to a Blog object that the user does not "own". However, there are easy and documented ways to prevent the user from accessing objects via the GET method, that are forbidden to them, by filtering the queryset and using check_object_permissions. Example: class PostViewSet(viewsets.ModelViewSet): serializer = PostSerializer def get_queryset(self): return Post.objects.filter(blog__user=self.request.user) def check_object_permissions(self, request, obj): if obj.user != request.user: raise exceptions.PermissionDenied() super().check_object_permissions(request, obj) How do I solve my above issue and prevent creating relations to forbidden objects the smartest/correct way in Django REST framework?
type: Question
has answer: http://stackoverflow.com/a/50698467
tagged with: django-rest-framework
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50698467
has title: Prevent create/update foreign key that refers to forbidden objects in Django rest framework
tagged with: django
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/88393134
has text: Getting this `RuntimeWarning: '<' not supported between instances of 'str' and 'int', sort order is undefined for incomparable objects` while doing type caste to `str` for empty line by `df = df.append(pd.DataFrame([np.nan] * len(df.columns))).astype(str)`
comment on: http://stackoverflow.com/a/50599390
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/50619004
answers question: http://stackoverflow.com/q/50617490
downvote count: 0
score: 4
type: Answer
has comment: http://stackoverflow.com/comment/88247995
has body: Why it doesn't print the file_name alone? It's because that is the filename. Amazon S3 is a flat object storage service. It does not support folders/directories. However, it does allow / characters in Keys ('filenames'). There are also various calls that can treat the / characters as delimiters for the purpose of listing 'sub-directories' (that really don't exist). For example, you could do this with the AWS Command-Line Interface (CLI): aws s3 mb my-bucket aws s3 cp foo s3://my-bucket/folder1/folder2/foo When you go to list the bucket, it will act as though folder1 and folder2 exist. It also looks like the folders were created, but they weren't. They are merely provided to act like traditional hierarchical directories. You could then issue this command: aws s3 rm s3://my-bucket/folder1/folder2/foo The foo file will be deleted and the folders will disappear too! This is because they never existed. Hence, the answer to your question: The Key (filename) is the full path of the object because paths don't actually exist. It's just a name. If you wish to 'avoid' it, you will need to manipulate the strings. This can be done quite easily in Python, eg: print(obj['Key'].rsplit('/', 1)[-1])
upvote count: 4
has comment: http://stackoverflow.com/comment/88248205
has comment: http://stackoverflow.com/comment/88247862

http://stackoverflow.com/comment/88333129
has text: That's what I mean tho. I tried doing that and it was all jumbled. Is there some table setting when I post?
score: 0
comment on: http://stackoverflow.com/q/50661460
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88327117
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50657977
has text: openpyxl is your best bet then, though I'm not sure of the exact code: https://openpyxl.readthedocs.io/en/stable/#

http://stackoverflow.com/comment/88195143
comment on: http://stackoverflow.com/q/50592764
score: 0
type: Comment
has text: @abarnert - I'll leave it to you to advocate!
type: QuestionComment

http://stackoverflow.com/a/50627790
answers question: http://stackoverflow.com/q/50627686
has body: Use str.replace, you don't need matching groups at all. df.address.str.replace(r'\d+\/\d+', '') 0 580 Broadway Street 1 85 Grand Street Name: address, dtype: object
type: AcceptedAnswer
downvote count: 0
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/88266244
has comment: http://stackoverflow.com/comment/88266209
has comment: http://stackoverflow.com/comment/88265962
accepted answer of: http://stackoverflow.com/q/50627686
upvote count: 3

http://stackoverflow.com/q/50556214
type: Question
has comment: http://stackoverflow.com/comment/88123852
tagged with: arrays
has answer: http://stackoverflow.com/a/50556448
has title: Get the absolute difference between elements of a circular array
has comment: http://stackoverflow.com/comment/88124085
score: 0
has answer: http://stackoverflow.com/a/50556587
answer count: 2
has comment: http://stackoverflow.com/comment/88123878
has comment: http://stackoverflow.com/comment/88123696
has comment: http://stackoverflow.com/comment/88123736
favorite count: 0
has comment: http://stackoverflow.com/comment/88123892
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88123668
has body: Let's say I have a array like l = [1, 3, 4, 5, 6, 8] where the nth element represents the distance between the nth and n+1th object. I want to find the distance between any two objects, and I used this code for this: def dis(l_list, index1, index2, mylist): m = mylist.index(index1) n = mylist.index(index2) i=0 j=0 if n &gt; m: while n &gt;= m: i = i + mylist[m] m = m + 1 elif n &lt; m: while n &lt;= m: i = i + mylist[n] n = n + 1 else: return(0) j = mylist[n] % l_mylist print(abs(i - j)) l_mylist = input() l_mylist = int(l_mylist) mylist = [] mylist = list(map(int, input().split())) i,j = input().split() i, j=int(i), int(j) dis(l_mylist, i, j, mylist) but I am still getting the wrong output. Can anyone please point out where I am wrong?
has comment: http://stackoverflow.com/comment/88123617
has comment: http://stackoverflow.com/comment/88123918
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/50654514
tagged with: emacs
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50657579
has title: emacs ipython autoclear buffer after executing
type: Question
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50657579
has body: I'm fairly new to Emacs and finally figured out how to set up python environment. I'm using elpy and iPython as python shell interpreter. My question is as follows: After I press C-c C-c, the buffer on the right shows the executed result. The red box is the code being executed and the blue box is the executed result returned from python. My questions are: Is there a way only showing the result? And every time after the script being executed, how to set the buffer on the right only showing the current result, ie, clear previous executed results? Thanks.

http://stackoverflow.com/comment/88213004
has text: @ajinkygadewar It cannot be the same issue: at least the error message should now say something about `flask_login`, not `flask.ext.login`.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50601738
type: AnswerComment

http://stackoverflow.com/q/50601927
answer count: 1
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88213574
has title: ValueError when I try to run my deep neural network
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/50604002
has body: I am following this tutorial: Training and Testing on our Data for Deep Learning The code is: import tensorflow as tf #from tensorflow.examples.tutorials.mnist import input_data import pickle import numpy as np train_x,train_y,test_x,test_y = create_feature_sets_and_labels('pos.txt','neg.txt') n_nodes_hl1 = 1500 n_nodes_hl2 = 1500 n_nodes_hl3 = 1500 n_classes = 2 batch_size = 100 hm_epochs = 10 x = tf.placeholder('float') y = tf.placeholder('float') hidden_1_layer = {'f_fum':n_nodes_hl1, 'weight':tf.Variable(tf.random_normal([len(train_x[0]), n_nodes_hl1])), 'bias':tf.Variable(tf.random_normal([n_nodes_hl1]))} hidden_2_layer = {'f_fum':n_nodes_hl2, 'weight':tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])), 'bias':tf.Variable(tf.random_normal([n_nodes_hl2]))} hidden_3_layer = {'f_fum':n_nodes_hl3, 'weight':tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])), 'bias':tf.Variable(tf.random_normal([n_nodes_hl3]))} output_layer = {'f_fum':None, 'weight':tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])), 'bias':tf.Variable(tf.random_normal([n_classes])),} # Nothing changes def neural_network_model(data): l1 = tf.add(tf.matmul(data,hidden_1_layer['weight']), hidden_1_layer['bias']) l1 = tf.nn.relu(l1) l2 = tf.add(tf.matmul(l1,hidden_2_layer['weight']), hidden_2_layer['bias']) l2 = tf.nn.relu(l2) l3 = tf.add(tf.matmul(l2,hidden_3_layer['weight']), hidden_3_layer['bias']) l3 = tf.nn.relu(l3) output = tf.matmul(l3,output_layer['weight']) + output_layer['bias'] return output def train_neural_network(x): prediction = neural_network_model(x) cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=prediction,logits=y) ) optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost) with tf.Session() as sess: sess.run(tf.initialize_all_variables()) for epoch in range(hm_epochs): epoch_loss = 0 i=0 while i &lt; len(train_x): start = i end = i+batch_size batch_x = np.array(train_x[start:end]) batch_y = np.array(train_y[start:end]) _, c = ses…
score: 0
tagged with: deep-learning

http://stackoverflow.com/a/54523401
upvote count: 7
type: AcceptedAnswer
has body: Assuming the rest of your code is good, change the following line of code: self.setWindowFlags(Qt.WindowStaysOnTopHint) to the following line of code: self.setWindowFlags(QtCore.Qt.Window | QtCore.Qt.CustomizeWindowHint | QtCore.Qt.WindowStaysOnTopHint) Link to an answer explaining why the code change above is required for the Qt.WindowStaysOnTop flag to work.
type: Answer
downvote count: 0
score: 7
answers question: http://stackoverflow.com/q/50631443
accepted answer of: http://stackoverflow.com/q/50631443

http://stackoverflow.com/a/50742259
has comment: http://stackoverflow.com/comment/88555075
has body: PyCUDA may not be compatible with WSGI web server contexts. You could possibly make it work if you use some kind of message queue like Celery, where the HTTP request places a job on the queue and the worker on the other side of the queue runs the CUDA program. Edit: A quick and easy way would be to use Python Subprocess check_output function In the web request: subprocess.check_output(['python', 'cudaFlask.py'])
type: Answer
has comment: http://stackoverflow.com/comment/88513780
answers question: http://stackoverflow.com/q/50601029
score: 0

http://stackoverflow.com/comment/88411660
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50698885
has text: Thanks so much. I followed your approach and am getting this error: `sqlalchemy.exc.ArgumentError: Relationship Account.created_by could not determine any unambiguous local/remote column pairs based on join condition and remote_side arguments. Consider using the remote() annotation to accurately mark those elements of the join condition that are on the remote side of the relationship.` Do I have to specify the join manually? Or is it that `foreign_keys` is only being recognised in one direction?
type: Comment

http://stackoverflow.com/q/50630569
has title: Pandas select consistent changes without iteration
favorite count: 0
has comment: http://stackoverflow.com/comment/88272758
answer count: 3
has body: I have a dataframe that looks like this: In [9]: d = pd.DataFrame({'place': ['home', 'home', 'home', 'home', 'office', 'office', 'office', 'home', 'office', 'home', 'office', 'home', 'office', 'home'], 'person': ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'c', 'c'], 'other_stuff': ['f', 'g', 'd', 'q', 'w', 'r', 's', 't', 'u', 'v', 'w', 'l', 'm', 'n']}) In [7]: d place other_stuff person 0 home f a 1 home g a 2 home d a 3 home q a 4 office w a 5 office r a 6 office s a 7 home t b 8 office u b 9 home v c 10 office w c 11 home l c 12 office m c 13 home n c There are only two place categories in my data: home and office. I want to select the rows of this dataframe that correspond to all person who have "permanent transitions" in the place column. i.e., I want to select only the persons who have changes in their place and don't change back. In this example dataframe, I want to select all rows corresponding to person a and person b, but not person c. The desired output is: place other_stuff person 0 home f a 1 home g a 2 home d a 3 home q a 4 office w a 5 office r a 6 office s a 7 home t b 8 office u b I plan to groupby on the column person, and then write a function to apply to each group of observations. My dataframe has about 60 million rows and 700,000 unique persons, so I do not want to use any kind of iteration. I'm not sure how to write a function that will select the correct rows without iterating through each group of person observations.
tagged with: python
has comment: http://stackoverflow.com/comment/88272207
upvote count: 2
tagged with: select
downvote count: 1
has answer: http://stackoverflow.com/a/50630784
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88271195
score: 1
has answer: http://stackoverflow.com/a/50630725
possible better answer: http://stackoverflow.com/a/50630756
has comment: http://stackoverflow.com/comment/88271202
type: Question
tagged with: pandas-groupby
has answer: http://stackoverflow.com/a/50630756
has comment: http://stackoverflow.com/comment/88271435
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50630725

http://stackoverflow.com/comment/88157793
type: QuestionComment
comment on: http://stackoverflow.com/q/50574173
has text: What does your input look like, with respect to the output shown?
score: 0
type: Comment

http://stackoverflow.com/a/50611456
downvote count: 0
has comment: http://stackoverflow.com/comment/88347294
type: Answer
upvote count: 2
has body: In some ways, an answer to this question is no different than general guidelines for safe programming: Check and sanitise code early, for every function Maintain relevant unit tests. Yes, this may sound like extra overhead, but the reality is you're probably already doing such checks and tests by hand anyway, so it's good practice to put it down on paper and formalise / automate the process. E.g., while you may have never expected a matrix output specifically, any unit test that checked your output is the expected array would have failed reliably. You might also want to have a look at specialised testing tools that are specific to scientific code, e.g. the Hypothesis package One thing that is specific to numpy is the handling of Floating Errors; the default simply 'prints' a warning statement to stdout, which can be missed easily (and does not cater for proper exception handling workflows). You can convert this functionality to throw proper warnings / exceptions that you can capture, via the numpy.seterr method -- e.g. numpy.seterr(all='raise').
answers question: http://stackoverflow.com/q/50609329
has comment: http://stackoverflow.com/comment/88347377
score: 2

http://stackoverflow.com/q/50619859
answer count: 1
has body: I'm trying to build my own dataset for the object detection tutorial from tensorflow, my code is here: import tensorflow as tf import os from PIL import Image from resizeimage import resizeimage from object_detection.utils import dataset_util flags = tf.app.flags flags.DEFINE_string('output_path', '', 'Path to output TFRecord') FLAGS = flags.FLAGS def create_tf_example(label_and_data_info): # TODO START: Populate the following variables from your example. height = 200 # Image height width = 200 # Image width filename = 'asc.0.jpg' # Filename of the image. Empty if image is not from file encoded_image_data = None # Encoded image bytes image_format = b'jpg' # b'jpeg' or b'png' xmins = [] # List of normalized left x coordinates in bounding box (1 per box) xmaxs = [] # List of normalized right x coordinates in bounding box # (1 per box) ymins = [] # List of normalized top y coordinates in bounding box (1 per box) ymaxs = [] # List of normalized bottom y coordinates in bounding box # (1 per box) classes_text = ['Ascaris'] # List of string class name of bounding box (1 per box) classes = [1] # List of integer class id of bounding box (1 per box) # TODO END tf_label_and_data = tf.train.Example(features=tf.train.Features(feature={ 'image/height': dataset_util.int64_feature(height), 'image/width': dataset_util.int64_feature(width), 'image/filename': dataset_util.bytes_feature(filename), 'image/source_id': dataset_util.bytes_feature(filename), 'image/encoded': dataset_util.bytes_feature(encoded_image_data), 'image/format': dataset_util.bytes_feature(image_format), 'image/object/bbox/xmin': dataset_util.float_list_feature(xmins), 'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs), 'image/object/bbox/ymin': dataset_util.float_list_feature(ymins), 'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs), 'image/object/class/text': dataset_util.bytes_list_feature(classes_text), 'image/object/class/label': dataset_util.int64_list_feature(classes), })) return …
has comment: http://stackoverflow.com/comment/88250370
has comment: http://stackoverflow.com/comment/88250042
tagged with: object-detection
has title: Issue creating my own dataset for the object detection tutorial from Tensorflow
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/50632015
type: UnansweredQuestion
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/88250982
tagged with: tensorflow
type: Question

http://stackoverflow.com/q/50604463
has answer: http://stackoverflow.com/a/50604725
upvote count: 2
type: UnansweredQuestion
tagged with: pip
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/88218332
tagged with: dockerfile
type: Question
answer count: 2
has title: How to split pip install into steps in Dockerfile?
has body: In my Dockerfile I have: FROM python:3.6-alpine RUN apk add --no-cache --virtual .fetch-deps \ zlib-dev \ jpeg-dev \ geoip-dev ENV PYTHONUNBUFFERED 1 RUN mkdir /src WORKDIR /src ADD requirements.txt /src/ RUN pip install -r requirements.txt If there are any problems with downloading or installing the dependencies in requirements.txt when I start the build again pip install downloads everything again. What are the best practices for Dockerfile in this case? Is it necessary to split requirements? Use separate volumes? Or is there an instruction other then RUN that is dedicated just for such cases?
tagged with: docker
has answer: http://stackoverflow.com/a/50605335
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/50549922
type: Answer
answers question: http://stackoverflow.com/q/50548531
has comment: http://stackoverflow.com/comment/88111645
upvote count: 1
has comment: http://stackoverflow.com/comment/88111609
has body: As you have mentioned, you are using XPATH , I would suggest you to use CSS_SELECTOR over XPATH. This is the code you can try out : send_button = driver.find_element_by_css_selector('a.button.button--simple.button--primary') send_button.click() UPDATE : CSS selectors perform far better than Xpath and it is well documented in Selenium community. Here are some reasons, Xpath engines are different in each browser, hence make them inconsistent. IE does not have a native xpath engine, therefore selenium injects its own xpath engine for compatibility of its API. Hence we lose the advantage of using native browser features that WebDriver inherently promotes. For more you refer this SO Link : XPATH VS CSS_SELECTOR
has comment: http://stackoverflow.com/comment/88111661
has comment: http://stackoverflow.com/comment/88111597
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88111395
score: 1
has comment: http://stackoverflow.com/comment/88111575
has comment: http://stackoverflow.com/comment/88111679
accepted answer of: http://stackoverflow.com/q/50548531
has comment: http://stackoverflow.com/comment/88111633

http://stackoverflow.com/comment/88216902
comment on: http://stackoverflow.com/a/50603089
type: AnswerComment
score: 0
type: Comment
has text: print(np.array(list(train_img_array[0]))) [[[255 255 255 0] [255 255 255 0] [255 255 255 0] ..., [255 255 255 0] [255 255 255 0] [255 255 255 0]] ...

http://stackoverflow.com/comment/88379089
type: QuestionComment
has text: so you want to make a new dict of `id:child`
comment on: http://stackoverflow.com/q/50684578
score: 0
type: Comment

http://stackoverflow.com/comment/88291411
type: Comment
has text: What is the exception details? Please update your question with complete stack trace
type: QuestionComment
comment on: http://stackoverflow.com/q/50640686
score: 1

http://stackoverflow.com/comment/88358191
score: 0
type: Comment
has text: Something like this
comment on: http://stackoverflow.com/a/50674229
type: AnswerComment

http://stackoverflow.com/q/50614758
answer count: 2
has title: Creating tables in MySQL based on the names of the columns in another table
has answer: http://stackoverflow.com/a/50614897
tagged with: sql
has comment: http://stackoverflow.com/comment/88267692
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50614897
has comment: http://stackoverflow.com/comment/88245676
has body: I have a table with ~133M rows and 16 columns. I want to create 14 tables on another database on the same server for each of columns 3-16 (columns 1 and 2 are `id` and `timestamp` which will be in the final 14 tables as well but won't have their own table), where each table will have the name of the original column. Is this possible to do exclusively with an SQL script? It seems logical to me that this would be the preferred, and fastest way to do it. Currently, I have a Python script that "works" by parsing the CSV dump of the original table (testing with 50 rows), creating new tables, and adding the associated values, but it is very slow (I estimated almost 1 year to transfer all 133M rows, which is obviously not acceptable). This is my first time using SQL in any capacity, and I'm certain that my code can be sped up, but I'm not sure how because of my unfamiliarity with SQL. The big SQL string command in the middle was copied from some other code in our codebase. I've tried using transactions as seen below, but it didn't seem to have any significant effect on the speed. import re import mysql.connector import time # option flags debug = False # prints out information during runtime timing = True # times the execution time of the program # save start time for timing. won't be used later if timing is false start_time = time.time() # open file for reading path = 'test_vaisala_sql.csv' file = open(path, 'r') # read in column values column_str = file.readline().strip() columns = re.split(',vaisala_|,', column_str) # parse columns with regex to remove commas and vasiala_ if debug: print(columns) # open connection to MySQL server cnx = mysql.connector.connect(user='root', password='&lt;redacted&gt;', host='127.0.0.1', database='measurements') cursor = cnx.cursor() # create the table in the MySQL database if it doesn't already exist for i in range(2, len(columns)): table_name = 'vaisala2_' + columns[i] sql_command = "CREATE TABLE IF NOT EXISTS " + \ table_name + "(`id` B…
tagged with: mysql
type: Question
has answer: http://stackoverflow.com/a/50614867
accepted answer: http://stackoverflow.com/a/50614867
score: 0

http://stackoverflow.com/q/50569247
has title: Rewrite functions in pywb without code source changing
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/50837051
tagged with: python-3.x
tagged with: python
has body: I'm new in python development and I'm using PYWB library for replaying web archives (warc files). I would like to modify a function in pywb/warcserver/index but without modifying the code source. The idea is to modify some features while keeping the original code source. It will be useful to update the code source without loosing changes. How can this be possible in pywb with python. The function to rewrite in the indexsource.py file is load_index Thanks
type: UnansweredQuestion
score: 0

http://stackoverflow.com/a/50675280
answers question: http://stackoverflow.com/q/50675248
upvote count: 2
type: Answer
score: 1
downvote count: 1
has body: This line: return "Perimeter = %s" %(side1 + side2 + side3) should be: return "Perimeter = %s" %(self.side1 + self.side2 + self.side3) To return the value of member variables in python, self. must be before the member. This is why self is one of the required parameters for member methods. In many other languages such as C#, the passing of self is implied, so you don't have to manually write it into the code.

http://stackoverflow.com/a/50638500
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50637877
has body: Thanks to @John Perry, who reminded me of the fact that style shouldn't prevail over functionality, I came up with the following simple solution: import os from collections import defaultdict listOfRelevantFiles = defaultdict(list) for targetFile in os.listdir('Z:/data'): if '.jpg' in targetFile or '.json' in targetFile: listOfRelevantFiles[targetFile.split('.')[0]].append(targetFile) print(listOfRelevantFiles)
type: Answer

http://stackoverflow.com/comment/88261452
type: AnswerComment
has text: I think your comment is related to Omid's answer, isn't it?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50623118

http://stackoverflow.com/comment/88418208
comment on: http://stackoverflow.com/a/50697109
type: AnswerComment
has text: There is no correlation between the timesteps that an LSTM can learn to improve the result.
score: 0
type: Comment

http://stackoverflow.com/comment/88121300
has text: Could you explain yourself better, do you want to change all the QLabels at the same time or before what action do you want to change each QLabel?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50554791

http://stackoverflow.com/q/50630849
answer count: 1
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/88278444
has answer: http://stackoverflow.com/a/68691990
tagged with: deep-learning
downvote count: 0
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has body: In training of deep neural network, how can tf.keras.layers.ActivityRegularization be used to regularize output? In my code, output have very large value. So I tried to regularize it. So for my last dense layers, I tried: output = tf.layers.dense(inputs=dropout_dense1, units=NUM_OUTPUTS, kernel_initializer=tf.truncated_normal_initializer, activity_regularizer = tf.keras.layers.ActivityRegularization()) But no regularization effect is observed in output (still very large). I tried all kinds of combination of parameters (default is tf.keras.layers.ActivityRegularization(L1=0, L2=0)), but it seems that it doesn't have any effect.
score: 1
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/88275188
has title: How does `tf.keras.layers.ActivityRegularization` work and how to use it correctly?
upvote count: 1

http://stackoverflow.com/q/50694192
type: UnansweredQuestion
has title: how to count no of red pixels in an image using python open cv?
tagged with: python
has answer: http://stackoverflow.com/a/50694471
downvote count: 2
tagged with: image-processing
upvote count: 1
has body: I'm Currently working on a project in which I need to count the no of red,blue,green,yellow,orange and violet pixels present in an image. As I am new to opencv I can't find any method that could solve my issues...
type: Question
tagged with: opencv
has answer: http://stackoverflow.com/a/50694413
has comment: http://stackoverflow.com/comment/88400150
score: -1
has comment: http://stackoverflow.com/comment/88400138
answer count: 2
has comment: http://stackoverflow.com/comment/88397880
has comment: http://stackoverflow.com/comment/88399360
favorite count: 0

http://stackoverflow.com/comment/88284916
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50637311
has text: Showing these empty []; what i can do further?
score: 0

http://stackoverflow.com/comment/88412790
type: QuestionComment
has text: `df.loc[something]` may return a Series or a DataFrame. If `something` appears multiple times in the index, the result is a DataFrame.
score: 1
comment on: http://stackoverflow.com/q/50698180
type: Comment

http://stackoverflow.com/comment/88267418
type: AnswerComment
type: Comment
has text: i did not have that idea, just wanted a simple one...that is why. Basically the order in list 1 is fixed and second list should fit into the order of first list as sorted
score: 0
comment on: http://stackoverflow.com/a/50619329

http://stackoverflow.com/q/50634594
answer count: 0
upvote count: 2
tagged with: django
type: Question
has body: I have a problem and would like a help! I have a django application, which is on an apache server. It was running normally until you upgraded to django 2.0.5. The application is served with cherrypy and apache. Where apache does the reverse proxy role. When I type the address, it removes the targeting created by apache. For example: The domain is "www.example.com" and the application is located at "www.example.com/app". When entering the address of the application in the browser, it redirects to the login page, but removing "/app/", thus making "www.example.com/security/enter", when it should be "www.example.com/app/security/enter". If I manually put the "/app/" system works normally, server the static files and everything else, but when requesting a new page, it always removes the "/app/", forcing it to manually put to work. Below is the template I used to get the application up and running: File app.conf in /etc/httpd/conf.d/: &lt;VirtualHost *:*&gt; ServerName example.com ProxyPreserveHost On ProxyPass /app/ http://example.com:8000/ ProxyPassReverse /app/ http://example.com:8000/ &lt;/VirtualHost&gt; File cps.py (cherrypy script): #!/opt/app/env/bin python # -*- coding: utf-8 -*- import os os.environ["DJANGO_SETTINGS_MODULE"] = "app.settings" import cherrypy import django django.setup() from django.conf import settings from django.core.handlers.wsgi import WSGIHandler class DjangoApplication(object): HOST = "0.0.0.0" PORT = 8000 def mount_static(self, url, root): config = { 'tools.staticdir.on': True, 'tools.staticdir.dir': root, 'tools.expires.on': True, 'tools.expires.secs': 86400 } cherrypy.tree.mount(None, url, {'/app/': config}) def run(self): cherrypy.config.update({ 'server.socket_host': self.HOST, 'server.socket_port': self.PORT, 'engine.autoreload_on': False, 'log.screen': True }) self.mount_static(settings.STATIC_URL, settings.STATIC_ROOT) cherrypy.log("Load application app") cherrypy.tree.graft(WSGIHandler()) cherrypy.engine.start() cherrypy.engine.blo…
has title: How to serving a django with Apache and Cherrypy
tagged with: apache
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: cherrypy
score: 2

http://stackoverflow.com/comment/88240357
comment on: http://stackoverflow.com/q/50615201
has text: Are you sure that your `pip` and your `python` are both from the same Python version? For example, one common thing macOS users run into is that they install a second Python, which is lower on the PATH than the pre-installed Apple Python, so `python` runs Apple's Python, but Apple's Python doesn't come with pip, so `pip` installs packages for the other Python.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88135325
type: Comment
type: QuestionComment
has text: @filippo did you use the same command? I'm using Anaconda / Python 3.6.4 / Windows 10
comment on: http://stackoverflow.com/q/50561111
score: 0

http://stackoverflow.com/comment/88519420
type: Comment
has text: thx a lot,I have never thought about if unconstrained maximum with in constrained region then we don't need to put the constraints on the method,by using Matlab function fmincon() I find the optima value very easily
comment on: http://stackoverflow.com/a/50725642
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88344812
has text: See [mcve] or possibly [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples).
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50667397
type: Comment

http://stackoverflow.com/comment/88124549
has text: Those are not working, Do you have other ideas?
comment on: http://stackoverflow.com/q/50556352
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88184992
has text: What is the URL you are trying to access?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50587781
type: Comment

plotly
tags question: http://stackoverflow.com/q/50642170
tags question: http://stackoverflow.com/q/50689557
type: Tag
tags question: http://stackoverflow.com/q/50579783
tags question: http://stackoverflow.com/q/50546071
tags question: http://stackoverflow.com/q/50690947
tags question: http://stackoverflow.com/q/50668357
tags question: http://stackoverflow.com/q/50584736
tags question: http://stackoverflow.com/q/50597139
tags question: http://stackoverflow.com/q/50634131
tag name: plotly
tags question: http://stackoverflow.com/q/50587634
tags question: http://stackoverflow.com/q/50543965
tags question: http://stackoverflow.com/q/50633040
tags question: http://stackoverflow.com/q/50546971
tags question: http://stackoverflow.com/q/50648743
tags question: http://stackoverflow.com/q/50627827
tags question: http://stackoverflow.com/q/50655677
tags question: http://stackoverflow.com/q/50575659
tags question: http://stackoverflow.com/q/50633829
tags question: http://stackoverflow.com/q/50584924

http://stackoverflow.com/a/50617268
type: Answer
has comment: http://stackoverflow.com/comment/88244718
has comment: http://stackoverflow.com/comment/88245450
has body: About your SQL statement : First of all, do you have a schema called radio_parameter and does your query have access to that schema..? literal derived from variable abc.iloc[i,1] has prefixes as a. or b.. In this case make sure the column name derived from that parameter is right for both tables aliased as a or b. OR literal derived from variable abc.iloc[i,1] has no prefix at one location which may cause ambiguity. some backslash (\) characters are seen in the SQL, are you sure that usage is right.
score: 0
answers question: http://stackoverflow.com/q/50616632

http://stackoverflow.com/a/50564083
has comment: http://stackoverflow.com/comment/88139021
accepted answer of: http://stackoverflow.com/q/50563950
has body: There is no assurance that os.getcwd() will be the same in every environment. It depends on how the process was spawned. If you want the directory in which the executable is located, you might get a better result using os.path.dirname(__file__) or os.path.dirname(sys.executable).
answers question: http://stackoverflow.com/q/50563950
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88138796
type: Answer

http://stackoverflow.com/comment/88360827
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50674818
type: Comment
has text: C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\ProgramData\Oracle\Java\javapath;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Windows\NSSAppLogs\FW-JetBrains-PyCharm Community Edition-2017.3-3264-171.4694.38;C:\Program Files\Python36;C:\Program Files\Python36\Scripts;

http://stackoverflow.com/q/50618925
has comment: http://stackoverflow.com/comment/88249001
has comment: http://stackoverflow.com/comment/88251589
has comment: http://stackoverflow.com/comment/88255299
has title: Why Is my code not running in Python IDES
has body: I have two sets of codes and I have just started learning Python for my needs: Have two different IDEs (PyCharm Comm Edn) and PyDev, Have Tried with both, The 2nd set runs successfully however 1st set doesn't, have compare both sets of code they don't differ much except for string quotes and indentation. 1st Set Of Code: class Car: def __init__(self): self.speed = 0 self.odometer = 0 self.time = 0 def say_state(self): print("I'm going {} kph".format(self.speed)) def accelerate(self): self.speed += 5 def brake(self): self.speed -= 5 def step(self): self.odometer += self.speed self.time += 1 def average_speed(self): return self.odometer / self.time if __name__ == '__main__': my_car = Car() print("I am a Car") while True: action = input("What Should I Do" "[A]ccelerate, [B]rake show [O]dometer" "Or Show average [S]peed").upper() if action not in "ABOS" or len(action) != 1: print("I DOnt Know how to do that") continue if action == 'A': my_car.accelerate() elif action == 'B': my_car.brake() elif action == 'O': print("My Car has driven {} Kilometers".format(my_car.odometer)) elif action == 'S': print("The Car average speed was {} Kilometers".format(my_car.average_speed())) my_car.step() my_car.say_state() 2nd Set Of Code: class Car: def __init__(self): self.speed = 0 self.odometer = 0 self.time = 0 def say_state(self): print("I'm going {} kph!".format(self.speed)) def accelerate(self): self.speed += 5 def brake(self): self.speed -= 5 def step(self): self.odometer += self.speed self.time += 1 def average_speed(self): return self.odometer / self.time if __name__ == '__main__': my_car = Car() print("I'm a car!") while True: action = input("What should I do? [A]ccelerate, [B]rake, " "show [O]dometer, or show average [S]peed?").upper() if action not in "ABOS" or len(action) != 1: print("I don't know how to do that") continue if action == 'A': my_car.accelerate() elif action == 'B': my_car.brake() elif action == 'O': print("The car has driven {} kilometers".format(my_car.odomet…
has comment: http://stackoverflow.com/comment/88255801
type: Question
has comment: http://stackoverflow.com/comment/88247674
has comment: http://stackoverflow.com/comment/88252002
has comment: http://stackoverflow.com/comment/88248902
has comment: http://stackoverflow.com/comment/88248249
favorite count: 0
has comment: http://stackoverflow.com/comment/88254443
has comment: http://stackoverflow.com/comment/88247799
tagged with: python
has comment: http://stackoverflow.com/comment/88250386
has comment: http://stackoverflow.com/comment/88247921
has comment: http://stackoverflow.com/comment/88255076
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/88247840
score: 0
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/88252842

http://stackoverflow.com/comment/88169113
type: Comment
has text: You can use pandas `groupby` and `sum` methods.
type: QuestionComment
comment on: http://stackoverflow.com/q/50579925
score: 0

http://stackoverflow.com/q/50671868
tagged with: pyqt
answer count: 1
has comment: http://stackoverflow.com/comment/88353578
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88353439
upvote count: 2
has answer: http://stackoverflow.com/a/50671932
has body: I am trying to write a PyQt5 application. All the list items in list variables are LineEdit objects of a form. On calling a reset function, I wish to set them to specific values for which I am trying to write a for loop instead of hard coding. However, I cant use the list items in variables as objects as they are object attributes in other file and doing self.eval(variables[i]).setText(default_0_values[i]) does't work, since eval is not an attribute of self. However, if I run self.nGASLineEdit.setText(2) it works. But I cant seem to be able to automate it and I'm stuck. Need a work around this. from PyQt5 import QtCore,QtGui,QtWidgets,uic variables=[ 'nGASLineEdit','nDELTALineEdit','iMIPLineEdit','nDVECLineEdit','nSEEDLineEdit','eSTARTLineEdit','eTHRMLineEdit','eCUTLineEdit','nGAS1LineEdit','nGAS2LineEdit','nGAS3LineEdit','nGAS4LineEdit','nGAS5LineEdit','nGAS6LineEdit','fRAC1LineEdit','fRAC2LineEdit','fRAC3LineEdit','fRAC4LineEdit','fRAC5LineEdit','fRAC6LineEdit','tEMPLineEdit','tORRLineEdit','eFIELDLineEdit','bMAGLineEdit','bTHETALineEdit','iWRITELineEdit','iPENLineEdit','dETEFFLineEdit','eXCWGHTLineEdit','kGASLineEdit','lGASLineEdit','lCMPLineEdit','lRAYLineEdit','lPAPLineEdit','lBRMLineEdit','iECASCLineEdit' ] default_0_values=[ 2,100,5,1,0,1.0,1.5,2.0, 2 ,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ] class Window(QtWidgets.QMainWindow): def __init__(self): super(Window,self).__init__() uic.loadUi('main.ui',self) self.pushButton_2.clicked.connect(lambda: self.reset()) def select_func(self,func_name): return func_name def reset(self): global variables global default_0_values for i in range(len(variables)): self.eval(variables[i]).setText(default_0_values[i]) if __name__=='__main__': import sys app=QtWidgets.QApplication(sys.argv) window=Window() window.show() sys.exit(app.exec()) UI file in .ui format UI file in .py format
tagged with: python
type: AnsweredQuestion
score: 2
tagged with: pyqt5
type: Question
has title: Call function via for loop with functons as a list of strings
accepted answer: http://stackoverflow.com/a/50671932
tagged with: function

http://stackoverflow.com/comment/88311565
score: 0
has text: so what you want is the colors to be `np.abs(week-26)` instead of `week`, but you don't want to change the values. Can you at least show a plot or something of what is going on now and what you expect?
comment on: http://stackoverflow.com/q/50649556
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88302096
type: QuestionComment
comment on: http://stackoverflow.com/q/50645645
has text: ['', '{[{language.name}]} {[{language.percentage}]}%', '', '', '', '', ''] ------------------- ['', '{[{degree.name}]} {[{degree.percentage}]}%', '', '', '', '', ''] -------------------
score: 0
type: Comment

http://stackoverflow.com/q/50614727
has answer: http://stackoverflow.com/a/50615001
tagged with: dbf
answer count: 1
linked to: http://stackoverflow.com/q/37470111
favorite count: 0
accepted answer: http://stackoverflow.com/a/50615001
tagged with: python
has comment: http://stackoverflow.com/comment/88247523
has body: I have been given an ambiguous task of automating a data extraction from various Visual FoxPro tables. There are several pairs of .DBF and .CDX files. With the Python dbf package, I seem to be able to work with them. I have two files, an ABC.DBF and an ABC.CDX. I can load the table file using, &gt;&gt;&gt; import dbf &gt;&gt;&gt; table = dbf.Table('ABC.DBF') &gt;&gt;&gt; print(table[3]) 0 - table_key : '\x00\x00\x04' 1 - field_1 : -1 2 - field_2 : 0 3 - field_3 : 34 4 - field_ 4 : 2 ... &gt;&gt;&gt; It's my understanding that .cdx files are indexes. I suspect that corresponds to the table_key field. According to the author, dbf can read indexes: I can read IDX files, but not update them. My day job changed and dbf files are not a large part of the new one. – Ethan Furman May 26 '16 at 21:05 Reading is all I need to do. I see that four classes exist, Idx, Index, IndexFile, and IndexLocation. These seem like good candidates. The Idx class reads in a table and filename, which is promising. &gt;&gt;&gt; index = dbf.Idx(table, 'ABC.CDX') I'm not sure how to make use of this object, though. I see that it has some generators, backward and forward, but when I try to use them I get an error &gt;&gt;&gt; print(list(index.forward())) dbf.NotFoundError: 'Record 67305477 is not in table ABC.DBF' How does one associate the .cdx index file to the .dbf table?
type: AnsweredQuestion
score: 3
upvote count: 3
has title: Python DBF: How to associate a .cdx index with a .dbf table
tagged with: visual-foxpro
type: Question
downvote count: 0

http://stackoverflow.com/q/50670470
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88350712
tagged with: inheritance
tagged with: docstring
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50743385
score: 2
has comment: http://stackoverflow.com/comment/88350783
has body: I am subclassing a class with a large number of methods and long docstrings. If I call the IPython help function I see all the help of the original class. I guess this is expected, is there a way to suppress this? I'd like to see only the methods I redefined. mymodule.py is: import matplotlib.axes class MySubclass(matplotlib.axes.Axes): pass If I do in IPython: import mymodule help(mymodule) The printout is huge because it contains all of the "Methods inherited from matplotlib.axes._axes.Axes:" which is megabytes of text because it lists the docstrings of all the methods of the class.
possible better answer: http://stackoverflow.com/a/50670998
upvote count: 2
has answer: http://stackoverflow.com/a/50670998
has comment: http://stackoverflow.com/comment/88350750
type: AnsweredQuestion
has title: Suppress "Methods inherited by base class" in subclass docstring
tagged with: ipython
has answer: http://stackoverflow.com/a/50743385
has comment: http://stackoverflow.com/comment/88350680
type: Question

http://stackoverflow.com/comment/88235369
has text: What's interesting is why the child processes aren't printing from 0 to 4. Something is killing them after the main process exits, but not immediately.
type: QuestionComment
comment on: http://stackoverflow.com/q/50612655
score: 0
type: Comment

http://stackoverflow.com/a/50564248
accepted answer of: http://stackoverflow.com/q/50564209
has body: Without using any modules. Use str.strip to remove brackets and then use str.split Ex: x = "['good', 'bad', 'something', 'another']" x = map(str.strip, x.strip("[]").replace("'", "").split(",")) Output: ['good', 'bad', 'something', 'another']
upvote count: 1
has comment: http://stackoverflow.com/comment/88139281
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50564209

http://stackoverflow.com/a/50543017
answers question: http://stackoverflow.com/q/50542636
has body: Maybe pandas.get_dummies can be helpful. You can just do : import pandas as pd dummies = pd.get_dummies(X_data, columns=[col1, col2], drop_first=True) Does that help you ? FInd the doc here : https://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html
downvote count: 0
has comment: http://stackoverflow.com/comment/88112230
type: Answer
has comment: http://stackoverflow.com/comment/88101383
score: 1
upvote count: 1

http://stackoverflow.com/q/50604740
has answer: http://stackoverflow.com/a/50605071
upvote count: 6
downvote count: 6
type: AnsweredQuestion
has body: I have a list of lists of lists like the following: rep = [[[1, 3, 5, 3, 7, 43], [6, 5, 2, 56, 4, 12], [5, 2, 5, 2, 5, 7, 1]], [[5, 3, 7, 3, 21], [6, 2, 5, 2,1, 6, 2], [78, 2, 65, 2, 6, 2], [78, 2, 65, 2, 6, 2]]] And a list of lists indicating the desired count of repeats count = [[5, 2, 5], [5, 2, 4, 5]] As you can see, the length of each element in count is identical to the length of each of the lists within rep. I want to use count to repeat the inner most lists in rep. For example, the output should look like: out = [[[1, 3, 5, 3, 7, 43], [1, 3, 5, 3, 7, 43], [1, 3, 5, 3, 7, 43], [1, 3, 5, 3, 7, 43], [1, 3, 5, 3, 7, 43], [6, 5, 2, 56, 4, 12], [6, 5, 2, 56, 4, 12], [5, 2, 5, 2, 5, 7, 1], [5, 2, 5, 2, 5, 7, 1], [5, 2, 5, 2, 5, 7, 1], [5, 2, 5, 2, 5, 7, 1] [5, 2, 5, 2, 5, 7, 1]], [[5, 3, 7, 3, 21], [5, 3, 7, 3, 21], [5, 3, 7, 3, 21], [5, 3, 7, 3, 21], [5, 3, 7, 3, 21], [6, 2, 5, 2,1, 6, 2], [6, 2, 5, 2,1, 6, 2], [78, 2, 65, 2, 6, 2], [78, 2, 65, 2, 6, 2], [78, 2, 65, 2, 6, 2], [78, 2, 65, 2, 6, 2], [78, 2, 98, 2, 6, 2], [78, 2, 98, 2, 6, 2], [78, 2, 98, 2, 6, 2], [78, 2, 98, 2, 6, 2], [78, 2, 98, 2, 6, 2]]] How can I do this?
possible better answer: http://stackoverflow.com/a/50604924
has answer: http://stackoverflow.com/a/50604924
type: Question
has answer: http://stackoverflow.com/a/50605146
has comment: http://stackoverflow.com/comment/88219115
has comment: http://stackoverflow.com/comment/88218857
score: 0
answer count: 3
has title: Repeat values in list of list of lists based on count in list of lists
accepted answer: http://stackoverflow.com/a/50605146
favorite count: 0
tagged with: python

http://stackoverflow.com/q/50543666
favorite count: 0
has comment: http://stackoverflow.com/comment/88098565
tagged with: http://stackoverflow.com/tag/csv
score: -3
tagged with: python
has body: Hi can someone please tell me why i have an invalid syntax that appear in the last line exactly in the second " this is a script that iterates through the CSV file and converts everything to the decimal ASCII equivalent. Thank you import csv with open('C:\Users\user\Desktop\log_transformed_truncated.csv', 'w') as outfile: c = csv.writer(outfile) counter = 0 with open('C:\Users\user\Desktop\log.csv','rb') as f: for row in csv.reader(f, delimiter=';'): counter = counter + 1 mod_row = [] if counter != 1: for cell in row: mod_row.append(sum(bytearray(cell))) else: for cell in row: mod_row.append(cell) c.writerow(mod_row) print "processed {} rows".format(counter)
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88098613
downvote count: 3
accepted answer: http://stackoverflow.com/a/50543729
tagged with: error-handling
type: Question
has comment: http://stackoverflow.com/comment/88098493
linked to: http://stackoverflow.com/q/19457227
has comment: http://stackoverflow.com/comment/88098553
upvote count: 0
answer count: 1
has title: I didn't find my erroe anywhere
has answer: http://stackoverflow.com/a/50543729

http://stackoverflow.com/comment/88211409
has text: @yeputons But when i return "filename1" it says that filename1 is not defined in gui
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50600998
score: 0

http://stackoverflow.com/q/50625541
answer count: 2
has answer: http://stackoverflow.com/a/50625914
favorite count: 0
possible better answer: http://stackoverflow.com/a/50625646
tagged with: python-3.x
tagged with: python
upvote count: 4
type: AnsweredQuestion
downvote count: 0
tagged with: pytest
has body: Assume this sample code: def test_foo(): dict = load_dict() try: value = dict[foo][bar] except KeyError: print('missing foo or bar') If it raises KeyError because either foo or bar doesn't exist, the test will not fail because the exception is captured. If I add a raise SystemExit(1), it fails, prints the message and shows all the traceback. My question is, how can I tell pytest that if a KeyError occurred it means the test failed, so that I don't need to raise a SystemExit?
type: Question
has answer: http://stackoverflow.com/a/50625646
accepted answer: http://stackoverflow.com/a/50625914
has title: How to print a message after capturing an exception in pytest
score: 4

http://stackoverflow.com/a/50675709
answers question: http://stackoverflow.com/q/50675667
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: I think need create list of DataFrames, concat together and then write to file: dfs1 = [] for fl in file_list: df = pd.read_excel(working_folder + fl) dfs1.append(df[df.ARRIVAL.between(20170101, 20170131)] ) pd.concat(dfs1).to_excel('201701-1.xlsx', index = False) What should be simplify by list comprehension: file_list = ["Jan.xlsx", "Feb.xlsx", "Mar.xlsx"] dfs1 = [pd.read_excel(working_folder + fl).query('20170101 &gt;= ARRIVAL &gt;=20170131') for fl in file_list] pd.concat(dfs1).to_excel('201701-1.xlsx', index = False)
accepted answer of: http://stackoverflow.com/q/50675667

http://stackoverflow.com/comment/88366515
has text: I am not sure there is an easy way to do so for now (except by manually searching in `i` for the values in `idx`). There's an [issue](https://github.com/pytorch/pytorch/issues/7416) covering this problem.
type: QuestionComment
comment on: http://stackoverflow.com/q/50666440
type: Comment
score: 1

http://stackoverflow.com/a/50667953
type: Answer
has body: Pomegranate is a tool that can give you the state labels (or probabilities) for the sequence that you model using HMM. Pomegranate can figure out the Start Probabilities, Transition Probabilities, and Emission Probabilities for you given that you give us initial transition probabilities, emission probabilities based on your domain knowledge of the problem. This is a good starting point for HMM using Pomegranate.
score: 0
answers question: http://stackoverflow.com/q/50660261
has comment: http://stackoverflow.com/comment/88346444

readprocessmemory
tag name: readprocessmemory
tags question: http://stackoverflow.com/q/50654548
type: Tag

http://stackoverflow.com/q/50610455
has comment: http://stackoverflow.com/comment/88230869
duplicate of: http://stackoverflow.com/q/19151
downvote count: 0
tagged with: string-operations
tagged with: string
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88230769
has body: The join() method for srings seems to work just fine for lists of strings and other built-in iterables. However, when I define my own iterables, join() cooperate. How can be write an iterable which join() is happy to have? class IterATOR: # iter-ATOR def __init__(self): self.x = 0 def __next__(self): self.x += 1 if self.x &gt; 4: raise StopIteration() return 'hello world' class IterABLE: # iter-ABLE def __iter__(self): return IterATOR() print(30 * '#', 'BEGIN TEST ONE', 30 * '#') gable = IterABLE() gator = iter(gable) try: while True: print(next(gator)) except StopIteration as exc: print(exc) print(30 * '#', 'BEGIN TEST TWO', 30 * '#') gable = IterABLE() for elem in gable: print(elem) print(30 * '#', 'BEGIN TEST THREE', 30 * '#') lyst = [str(x) for x in range(0, 5)] # tcs: test cases tcs = [lyst, IterABLE(), iter(IterABLE()), IterATOR(), lyst, iter(lyst)] for tc in tcs: # for test case in test cases: try: print(type(tc).__name__.ljust(20), end ='') merged_str = ''.join(tc) print(" was a success:".ljust(20), repr(merged_str)) except Exception as exc: print(" was a failure:".ljust(20), str(exc)) The output for test three is: ############################## BEGIN TEST THREE ############################## list was a success: '01234' IterABLE was a failure: 'IterATOR' object is not iterable IterATOR was a failure: can only join an iterable IterATOR was a failure: can only join an iterable list was a success: '01234' list_iterator was a success: '01234'
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/19151
answer count: 0
tagged with: join
score: 1
has title: How can we use custom iterables with string.join()?
upvote count: 1
type: Question

http://stackoverflow.com/q/50667026
type: Question
score: 3
accepted answer: http://stackoverflow.com/a/50667199
answer count: 1
downvote count: 0
has title: Why are widget.winfo_rootx() and widget.winfo_rootx() always 0 in tkinter?
favorite count: 0
tagged with: python-3.x
tagged with: python
has body: Here is my code: from tkinter import * root = Tk() a = Button(text=str(1)) a.place(x=100, y=100) widget_x, widget_y = a.winfo_rootx(), a.winfo_rooty() print(widget_x, widget_y) root.mainloop() The output is always 0 0. Why is this and how can I fix it?
type: AnsweredQuestion
tagged with: tkinter
has answer: http://stackoverflow.com/a/50667199
upvote count: 3

http://stackoverflow.com/q/50697256
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88403578
tagged with: python
has comment: http://stackoverflow.com/comment/88403688
has body: I want to hint that for B-instance .duplicate_itself() returns B-instance, not A-instance. class A: def duplicate_itself(self) -&gt; 'WHAT SHOULD I WRITE HERE?' return self.__class__() class B(A): pass BTW I am using PyCharm, so feel free to write an answer if you know some PyCharm specific solution
has answer: http://stackoverflow.com/a/50697467
type: AnsweredQuestion
tagged with: pycharm
score: 1
tagged with: type-hinting
upvote count: 1
accepted answer: http://stackoverflow.com/a/50697467
type: Question
has comment: http://stackoverflow.com/comment/88403761
downvote count: 0
answer count: 1
has title: How to hint base class function that returns an instance of derived class it is called from?

http://stackoverflow.com/q/50542864
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
has body: I have to use an older scipy version, which can not extrapolate. In scipy 1.1.0 the extrapolation is working as expected, giving proper results. Since I cannot use this in my application I want to use numpy polyfit. but the results are different, while interpolation from scipy and bisect results are the same.. class InterExtraPolate(object): def __init__(self, x_list, y_list): if any(y - x &lt;= 0 for x, y in zip(x_list, x_list[1:])): raise ValueError("x_list must be in strictly ascending order!") self.x_list = map(float, x_list) self.y_list = map(float, y_list) def __getitem__(self, x): from scipy import interpolate f=interpolate.interp1d(self.x_list,self.y_list, fill_value='extrapolate') return f(x) class npInterExraPolate(object): def __init__(self, x_list, y_list): import numpy as np if any(y - x &lt;= 0 for x, y in zip(x_list, x_list[1:])): raise ValueError("x_list must be in strictly ascending order!") self.x_list = map(float, x_list) self.y_list = map(float, y_list) self.fit=np.polyfit(self.x_list,self.y_list, 1) def __getitem__(self, x): import numpy as np f=np.poly1d(self.fit) return f(x) ##Main ie = InterExtraPolate([1, 2.5, 3.4, 5.8, 6], [2, 4, 5.8, 4.3, 4]) npie = npInterExraPolate([1, 2.5, 3.4, 5.8, 6], [2, 4, 5.8, 4.3, 4]) my_xl = [0.5,1.1,6.3] print ie[my_xl] print npie[my_xl] ==== How can I make the numpy polyfit/poly1d results equal to the scipy extrapolate results?
tagged with: scipy
type: Question
tagged with: numpy
answer count: 2
has title: Python Numpy polyfit results differ from SciPy interpolate
has answer: http://stackoverflow.com/a/50542998
has answer: http://stackoverflow.com/a/50566131
downvote count: 0
tagged with: extrapolation

http://stackoverflow.com/comment/88315164
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50652196
has text: I was trying curl -X POST http://127.0.0.1:8000 -d '{"Foo":"bar"}' is that not correct?
type: Comment

http://stackoverflow.com/a/50561012
downvote count: 1
has comment: http://stackoverflow.com/comment/88132507
answers question: http://stackoverflow.com/q/50560767
type: Answer
score: 2
has body: Use a combination of islice and cycle: from itertools import islice, cycle print(list(islice(cycle(range(1, 5)), 6))) # [1, 2, 3, 4, 1, 2]
upvote count: 3

http://stackoverflow.com/q/50557795
type: UnansweredQuestion
tagged with: flask
has comment: http://stackoverflow.com/comment/88129536
has comment: http://stackoverflow.com/comment/88127481
tagged with: apache
answer count: 0
has body: I am new to Python, have experience with serves and apache in general. And so, I am working with this Python-based application, web parser, I guess. It's using Flask with its builtin webserver Werkzeug... while on a VPS it worked great as is, but moving to a multi-process (+ multi-thread) dedicated server I've run into problems. First of all it's the message from Flask to move to a production WSGI server and drop Werkzeug... And second, the program refused to start with more than 1 process (can have a number of processes as a parameter), saying that I cannot have both multi-threaded and multi-process environments (with Werkzeug, right?)... I was able to start the app with 1 process as a parameter, and it would work and only use 1 process, and eventually start lagging from too many requests... And so, I've read a few articles and tried to do the move to apache WSGI. as instructed, I did the following steps... created a folder /var/www/app-server, then created APPNAME.wsgi file with following code and placed it in that folder: import sys sys.path.insert(0, '/var/www/app-server') from APPNAME.server import app as application went to apache config and added the following code: ServerName server.name WSGIDaemonProcess APPNAME user=apache group=apache threads=5 WSGIScriptAlias / /var/www/app-server/APPNAME.wsgi WSGIProcessGroup APPNAME WSGIApplicationGroup %{GLOBAL} WSGIScriptReloading On Require all granted saved and restarted apache, added firewall port, etc.. So, now NOTHING basically has changed, and although it is working, it is still using only 1 process, although now I don't need to tell it to do so via parameters... and of course now it's the httpd process. same everything as before, just 1 process under "different name". I am very lost now, didn't I do things correctly? Or is there another piece of software needed in-between Python app and apache, like gunicorn or something? So, this wasn't a good solution for me, and I ended up going into the Python source code …
has title: Python app move to Apache WSGI - enabling Multi-Process
has comment: http://stackoverflow.com/comment/88129023
has comment: http://stackoverflow.com/comment/88128331
type: Question
has comment: http://stackoverflow.com/comment/88130783
tagged with: python
has comment: http://stackoverflow.com/comment/88128373
tagged with: mod-wsgi
score: 0
linked to: http://stackoverflow.com/q/2505541
duplicate of: http://stackoverflow.com/q/2505541
tagged with: wsgi

http://stackoverflow.com/q/50670103
has title: python singleton code
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50670176
has body: Here is an example of singleton in python. One thing I don't understand is I think the _instance in class is always set to None, therefore the "if not cls._instance" should always true, therefore, there is no need for the if statement. I know I am wrong, please help me where I missed. class Singleton(object): _instance = None # Keep instance reference # why do this???? If do this, the "if not .." state follow is always true, right? def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = object.__name__(cls, *args, **kwargs) return cls._instance Update My confusion is: Why the 2nd time you call Singleton(), the _instance = None is not triggered? Whereas it is triggered 1st call?
score: 1
has answer: http://stackoverflow.com/a/50670132
type: Question
answer count: 2
favorite count: 0
has comment: http://stackoverflow.com/comment/88350008
downvote count: 3
tagged with: python
upvote count: 4

http://stackoverflow.com/comment/88321225
comment on: http://stackoverflow.com/a/50655283
type: AnswerComment
score: 0
type: Comment
has text: may be I am not able to follow but it would help if you can be a bit elaborate. sum(axis = 1) is sum of each row . Why do you say it is "sum of columns"?

http://stackoverflow.com/a/57528809
has body: The requested feature is not called a border in Tkinter. It is called a highlight. To get the above request, set highlightbackground="black" and highlightthickness=1. (The border is the empty space reserved around the frame) Additional information is available in documentation.)
has comment: http://stackoverflow.com/comment/116069429
type: Answer
upvote count: 27
downvote count: 0
answers question: http://stackoverflow.com/q/50691267
has comment: http://stackoverflow.com/comment/122609632
score: 27

http://stackoverflow.com/comment/88260962
comment on: http://stackoverflow.com/q/50613755
score: 0
type: Comment
type: QuestionComment
has text: My plan is automation, so i can not manually change the tag everytime. The link however, helps solves my problem with the xmlstarlet cmd utility. Thanks :)

http://stackoverflow.com/a/58711233
has body: Those running flask for the first time ..This works well for windows find the location of your folder use cmd please 'mine is cd /users/hp/Desktop' cd /users/hp/Desktop&gt;set FLASK_APP=hello.py --&gt;file name cd /users/hp/Desktop&gt;set FLASK_ENV=development cd /users/hp/Desktop&gt;flask run
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/50574293
downvote count: 0
type: Answer

http://stackoverflow.com/q/50547774
has answer: http://stackoverflow.com/a/50549790
favorite count: 0
type: UnansweredQuestion
tagged with: localization
tagged with: django
has title: How to format a number in django and respect localization
score: 3
downvote count: 0
type: Question
has body: I wrote a custom filter like this which calls this method in a util file: def util_format_number(value): return "{:,.1f}".format(value) The idea is to only show one decimal place...but when used inside a template it won't give me a localized number like I have configured in settings: LANGUAGE_CODE = 'es-es' USE_I18N = True USE_L10N = True USE_THOUSAND_SEPARATOR = True DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3 The desired result would be 23.444.523,3 My actual filter looks like this: @register.filter def format_number(value): return util_format_number(value) I want to be able to use the formatter not only in templates, but inside view code where I create custom graphs (that I later print in the templates). Any hints? Best regards and thanks in advance.
upvote count: 3
answer count: 1
tagged with: python

http://stackoverflow.com/comment/88155020
type: QuestionComment
type: Comment
has text: Thabks that confused me! Tried your ammended url - managed to stop the error message by puttinng `json.dumps(content)` but translate returns the same json object! Which is not what is needed.
comment on: http://stackoverflow.com/q/50572358
score: 0

http://stackoverflow.com/comment/88242002
has text: Double-check that all of the tuples in `listToSave` have the same number of items, and that is equal to the number of `%s` in the query.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50615717

http://stackoverflow.com/q/50676948
linked to: http://stackoverflow.com/q/4257394
has body: I've a 2 dimensional numpy array (Classification Model's probability output). Now I want to extract the index of top 3 values for each nested array. E.g. x = np.array([[1, 2, 3, 5, 6, 8], [4, 5, 6, 9, 10, 1]], np.int32) What I want is [[5, 4, 3] [4, 3, 2]] Without using loop
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/40574071
has comment: http://stackoverflow.com/comment/88366023
has comment: http://stackoverflow.com/comment/88363734
answer count: 0
has comment: http://stackoverflow.com/comment/88365197
has title: Get top N values from each sub-array from 2D numpy array
type: Question
duplicate of: http://stackoverflow.com/q/40574071
has comment: http://stackoverflow.com/comment/88365969
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/88363564

http://stackoverflow.com/q/50569970
score: 1
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88149901
tagged with: python
tagged with: java
tagged with: javafx
upvote count: 1
type: Question
has title: Launching python script from javafx app
has answer: http://stackoverflow.com/a/50570165
has body: I want to launch some python scripts from a javafx app. To launch the scripts I use this code : private String executeCommand(String command) { StringBuffer output = new StringBuffer(); Process p; try { System.out.println(command); p = Runtime.getRuntime().exec(command); p.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = reader.readLine())!= null) { output.append(line + "\n"); } } catch (Exception e) { e.printStackTrace(); } return output.toString(); } public void launchCommand(String inputDir, String outputDir) { String command = ".\\venv\\Scripts\\python.exe ./test.py -i " + inputDir + " -o " + outputDir; String output = this.executeCommand(command); System.out.println(output); } The problem is the script is launch by the javafx graphical thread so the line p.waitFor(); will lock the javafx thread and so my gui stops responding... I dont know how solve this problem... Thank you in advance for your help !
answer count: 1
downvote count: 0

http://stackoverflow.com/a/50674432
score: 0
has comment: http://stackoverflow.com/comment/88358790
type: Answer
has comment: http://stackoverflow.com/comment/88358708
accepted answer of: http://stackoverflow.com/q/50674381
has comment: http://stackoverflow.com/comment/88358925
has body: In line 3, there is a "while", so line 4 must be indented. Line 4 and 5 are not correctly written either. Pycharm may be wrong sometimes, but rarely. As a beginner, you should first verify your code before thinking the tool is wrong.
answers question: http://stackoverflow.com/q/50674381
type: AcceptedAnswer

http://stackoverflow.com/comment/88223456
has text: when i run this script, chrome browser stills pulls up
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50606929

http://stackoverflow.com/a/50663735
score: 0
has body: Solution 1 python3 -m pip install xxx # for example: python3.7 -m pip install requests Solution 2 virtualenv --python=python3.7 venv source venv/bin/activate pip install requests Solution 3 pipenv --python 3.7 # python3 -m pip install pipenv --user pipenv shell pipenv install requests
type: Answer
answers question: http://stackoverflow.com/q/50662711

http://stackoverflow.com/q/50595173
tagged with: python
has answer: http://stackoverflow.com/a/50595279
type: Question
has body: I have 2 pandas dataframes which look like below. Data Frame 1: Section chainage_from chainage_to Frame R125R002 10.133 10.138 1 R125R002 10.138 10.143 2 R125R002 10.143 10.148 3 R125R002 10.148 10.153 4 R125R002 10.153 10.158 5 Data Frame 2: Section Chainage 1 2 3 4 5 6 7 8 R125R002 10.133 0 0 1 0 0 0 0 0 R125R002 10.134 1 0 1 0 0 0 0 0 R125R002 10.135 0 0 1 0 0 0 0 0 R125R002 10.136 0 0 1 0 0 0 0 0 R125R002 10.137 0 0 1 0 0 0 0 0 R125R002 10.138 0 0 1 0 0 0 0 0 R125R002 10.139 0 0 1 0 0 0 0 0 R125R002 10.14 5 0 1 0 0 0 0 0 R125R002 10.141 1 0 1 0 0 0 0 0 R125R002 10.142 0 0 1 0 0 0 0 0 R125R002 10.143 0 0 1 0 0 0 0 0 R125R002 10.144 0 0 1 0 0 0 0 0 R125R002 10.145 0 0 1 0 0 0 0 0 R125R002 10.146 0 0 1 0 0 0 0 0 R125R002 10.147 0 0 1 0 0 0 0 0 R125R002 10.148 0 0 1 0 0 0 0 0 R125R002 10.149 0 0 1 0 0 0 0 0 R125R002 10.15 0 0 1 0 0 0 0 0 R125R002 10.151 0 0 1 0 0 0 0 0 R125R002 10.152 0 0 1 0 0 0 0 0 R125R002 10.153 0 0 1 0 0 0 0 0 required output dataframe: Section Chainage Frame 1 2 3 4 5 6 7 8 R125R002 10.133 1 1 0 1 0 0 0 0 0 R125R002 10.138 2 0 0 1 0 0 0 0 0 R125R002 10.143 3 6 0 1 0 0 0 0 0 R125R002 10.148 4 0 0 1 0 0 0 0 0 R125R002 10.153 5 0 0 1 0 0 0 0 0 Dataframe 2 has the increment of 1 m intervals while dataframe 1 has the increment of 5 m. I would like to merge dataframe 2 to dataframe 1 between chainage_from and chainage_to and apply group by. Groupby for column 1 is sum, column 2 max, colum3 to 8 average. In SQL, I would link section between 2 frames and apply between the condition for the chainage from and to and then add groupby. Is there any way to achieve this in pandas.
upvote count: 0
score: -2
has title: pandas merge and groupby
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/50595259
duplicate of: http://stackoverflow.com/q/50580408
favorite count: 0
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/comment/88241052
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50615580
score: 1
has text: Technically, interpolation is a special implementation of the modulo operator for strings. I always thought it was a bit counter-intuitive, but you get used to it.

http://stackoverflow.com/a/51814444
score: 0
answers question: http://stackoverflow.com/q/50586097
has body: Did you restart the instance after you added machine learning services? "Advanced Analytics Extensions" is referring to the machine learning services feature (R and Python integration). It seems like the system can't detect that the feature is installed. If you are using SSMS, you can use these rdl reports to check configuration/configure your instance: https://github.com/Microsoft/sql-server-samples/tree/master/samples/features/r-services/ssms-custom-reports Try R Services - Configuration.rdl or R Services - Configure Instance.rdl. Add the reports to the server name in SSMS Object Explorer.
type: Answer

http://stackoverflow.com/comment/88262422
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50626137
has text: I have never had any instance of me trying to parse a foreign language in python, but it is most likely because python can't read any encoding for those characters.

http://stackoverflow.com/a/50661456
accepted answer of: http://stackoverflow.com/q/50660685
has comment: http://stackoverflow.com/comment/88335016
answers question: http://stackoverflow.com/q/50660685
score: 0
has comment: http://stackoverflow.com/comment/88335740
has comment: http://stackoverflow.com/comment/88333985
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88334960
has comment: http://stackoverflow.com/comment/88335481
has comment: http://stackoverflow.com/comment/88335203
has comment: http://stackoverflow.com/comment/88334101
type: Answer
has body: In the kv file, use either on_leave or on_pre_leave event at InputScreen: to clear the text (entry.text). Screen Manage » API » Events Events: on_pre_leave: () &nbsp;&nbsp;&nbsp;&nbsp;Event fired when the screen is about to be removed: the leaving animation is started. on_leave: () &nbsp;&nbsp;&nbsp;&nbsp;Event fired when the screen is removed: the leaving animation is finished. Snippets ScreenManagement: id: screen_manager transition: FadeTransition() MainScreen: id: main_screen name: "main" manager: screen_manager numberSet1: input_screen.number1 numberSet2: input_screen.number2 numberSet3: input_screen.number3 InputScreen: id: input_screen name: "input" manager: screen_manager textIdToReturn: main_screen.textName on_leave: root.ids.input_screen.key_board.ids.entry.text = '' ... &lt;InputScreen&gt;: key_board: key_board Note kv file - ObjectProperty and ids key_board: key_board Indicates that an ObjectProperty called key_board is pointing (hooked up) to the KeyBoardGridLayout's id, key_board. entry It is an id and a weakref to TextInput widget. entry.text It is referencing the value of TextInput's text. entryText: entry.text entryText is a property of KeyBoardGridLayout. If the widget doesn’t have a property with the given name, an ObjectProperty will be automatically created and added to the widget. entryText is assigned the value of entry.text
has comment: http://stackoverflow.com/comment/88334269
has comment: http://stackoverflow.com/comment/88334633

http://stackoverflow.com/a/50610834
has comment: http://stackoverflow.com/comment/113777247
answers question: http://stackoverflow.com/q/50609986
score: 34
has comment: http://stackoverflow.com/comment/113777434
has comment: http://stackoverflow.com/comment/113777373
has body: Your question has many aspects so I will try to be detailed in my answer and also this answer will be continuously updated because this type of questions are often asked but they are solutions for a specific case so I am going to take the liberty of giving it a general approach and be specific in the possible scenarios. QML to Python: Your method works because the type conversion in python is dynamic, in C++ it does not happen. It works for small tasks but it is not maintainable, the logic must be separated from the view so it should not be dependent. To be concrete, let's say that the printed text will be taken by the logic to perform some processing, then if you modify the name of the signal, or if the data does not depend on ApplicationWindow but on another element, etc. then you will have to change a lot connection code. The recommended as you indicate is to create a class that is responsible for mapping the data you need your logic and embed it in QML, so if you change something in the view you just change the connection: Example: main.py import sys from PySide2.QtCore import QObject, Signal, Property, QUrl from PySide2.QtGui import QGuiApplication from PySide2.QtQml import QQmlApplicationEngine class Backend(QObject): textChanged = Signal(str) def __init__(self, parent=None): QObject.__init__(self, parent) self.m_text = "" @Property(str, notify=textChanged) def text(self): return self.m_text @text.setter def setText(self, text): if self.m_text == text: return self.m_text = text self.textChanged.emit(self.m_text) if __name__ == '__main__': app = QGuiApplication(sys.argv) backend = Backend() backend.textChanged.connect(lambda text: print(text)) engine = QQmlApplicationEngine() engine.rootContext().setContextProperty("backend", backend) engine.load(QUrl.fromLocalFile('main.qml')) if not engine.rootObjects(): sys.exit(-1) sys.exit(app.exec_()) main.qml import QtQuick 2.10 import QtQuick.Controls 2.1 import QtQuick.Window 2.2 ApplicationWindow { title: qsTr("Test")…
has comment: http://stackoverflow.com/comment/105552950
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/113777789
has comment: http://stackoverflow.com/comment/127564686
has comment: http://stackoverflow.com/comment/88245373
type: Answer
has comment: http://stackoverflow.com/comment/111537745
has comment: http://stackoverflow.com/comment/127587208
has comment: http://stackoverflow.com/comment/105554231
accepted answer of: http://stackoverflow.com/q/50609986
upvote count: 35

http://stackoverflow.com/q/50629537
type: Question
tagged with: matplotlib
has body: I am using plotnine in python 2 (but would be happy for a solution using matplotlib or any other plotting package). I have a function (slightly simplified below) with 4 arguments. I want to plot a grid of heatmaps, with "super axes" varying two of the parameters, and each heatmap varying the other two. A bit like this: I came up with this code: from plotnine import ggplot, aes, facet_grid, geom_tile import pandas as pd import itertools def fun((i, j, n, p)): if n &gt; j: return 1 if (p**(3*n)) &gt; ((p+i)**(3*(n-j))) else 0 return -1 ilist, jlist, nlist, plist = range(1,10), range(1,9), range(8,10), range(4,6) rows = itertools.product(ilist, jlist, nlist, plist) df = pd.DataFrame(list(rows)) df.columns = ['i','j','n','p'] df['fun'] = df.apply(fun, axis=1) (ggplot(df, aes('factor(i)', 'factor(j)')) + geom_tile(aes(fill='fun')) + facet_grid('n ~ p', labeller='label_both')) This produces the following: This (more or less) has the form I am going for, but the heatmaps seem wrong. (EDIT: I discovered the error was in the definition of fun, not in the plotting - see my answer).
score: 0
has answer: http://stackoverflow.com/a/50646223
answer count: 1
tagged with: plotnine
type: UnansweredQuestion
tagged with: python
tagged with: plot
tagged with: heatmap
has title: Plotting a function with 4 arguments in a grid of heatmaps

http://stackoverflow.com/a/72938945
has body: Based on a lot of reading up I've been able to do, something like tfidf_matcher worked well for me. Returns the best k matches. Also, it's easily 1000x faster than Fuzzywuzzy.
type: Answer
answers question: http://stackoverflow.com/q/50583871
score: 0
has comment: http://stackoverflow.com/comment/128854228

http://stackoverflow.com/a/79470943
has body: Consider turning the sparse matrix to a single numpy.ndarray first, due to this warning: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at /Users/runner/work/pytorch/pytorch/pytorch/torch/csrc/utils/tensor_new.cpp:278.) If your computer has enough memory to do that, then the following is the easiest way to convert a scipy coo_matrix to pytorch sparse tensor: from scipy.sparse import coo_matrix coo = coo_matrix((3, 4), dtype = "int8") coo_sparse_t = torch.tensor(coo.toarray()).to_sparse_coo() coo_sparse_t Output: tensor(indices=tensor([], size=(2, 0)), values=tensor([], size=(0,)), size=(3, 4), nnz=0, dtype=torch.int8, layout=torch.sparse_coo)
has comment: http://stackoverflow.com/comment/140153984
score: 0
answers question: http://stackoverflow.com/q/50665141
type: Answer
has comment: http://stackoverflow.com/comment/140154929

drf-queryset
type: Tag
tags question: http://stackoverflow.com/q/50676008
tag name: drf-queryset

http://stackoverflow.com/q/50635449
has answer: http://stackoverflow.com/a/50991144
accepted answer: http://stackoverflow.com/a/50991144
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/88953245
has comment: http://stackoverflow.com/comment/88953329
type: Question
has comment: http://stackoverflow.com/comment/88288255
has title: why is `tox` installing packages in system Python directory in Windows?
tagged with: tox
answer count: 1
tagged with: cygwin
favorite count: 0
upvote count: 3
tagged with: windows
has comment: http://stackoverflow.com/comment/88288291
has comment: http://stackoverflow.com/comment/88976710
has body: I am new to tox, but my understanding is that it creates local virtual environments for each testing environment. However, it seems whenever I run tox it first installs the package to the system Python installation and then installs any dependencies there too. Here is the simplest example I can show: My tox.ini is simply: [tox] envlist = py27 [testenv] commands = pytest deps = pytest Then the following series of commands show pytest is not installed, but at the end of the tox run, it is installed in the system python path: &gt; which pytest which: no pytest in (/cygdrive/c/Program Files (x86.... &gt; tox [... lots of output ...] ___________________________________ summary ___________________________________ py27: commands succeeded congratulations :) Then, &gt; which pytest /cygdrive/c/Python27/Scripts/pytest Additionally, I see the package I'm testing is also installed in the system python directory. Shouldn't tox be generating a virtual environment locally? I see there is a .tox/py27 directory that gets created, but it looks like a Linux-style installation with a bin directory instead of Scripts. Is this the expected behavior of tox?
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88314606

http://stackoverflow.com/a/50566150
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: I believe need map: df_CF['Income']=df_CF['Months'].map(df_data.set_index('TTS')['REV']).fillna(df_CF['Months']) print (df_CF) Income Months 0 0.0 0 1 1.0 1 2 2.0 2 3 3.0 3 4 4.0 4 5 5.0 5 6 6.0 6 7 7.0 7 8 8.0 8 9 150000.0 9 10 10.0 10 11 11.0 11 12 200000.0 12 13 13.0 13 14 14.0 14 15 250000.0 15 16 16.0 16 17 17.0 17 18 18.0 18 19 19.0 19 20 20.0 20 21 21.0 21 22 22.0 22 23 23.0 23
accepted answer of: http://stackoverflow.com/q/50566056
answers question: http://stackoverflow.com/q/50566056

http://stackoverflow.com/comment/88235906
has text: That's exactly correct. However, maybe I don't understand how zip works but doesn't `zip([1,2,3], [4,5,6])` return `[(1, 4), (2, 5), (3, 6)]` which is not the output I want. Or are you suggesting using zip in combination with product in order to 'append' the random numbers in a sense?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50610112

http://stackoverflow.com/q/50579547
has body: What I know is: # -*- coding: utf-8 -*- It is used to declare the encoding of a Python source file, once I set the encoding name, Python parser will interpret the file using the given encoding. I call it "file encoding"; from __future__ import unicode_literals I'm doing my tasks using Python2.7, and I use from __future__ import unicode_literals to change the default type of string from "str" to "unicode". I call it "string encoding"; sys.setdefaultencoding('utf8') But sometimes, I get an error in Django, for example, I stored Chinese in admin, then I visited the releated pages UnicodeEncodeError at /admin/blog/vulpaper/29/change/ 'ascii' codec can't encode characters in position 6-13: ordinal not in range(128) ....the more error information The string that could not be encoded/decoded was: emcms外贸网站管理系统 for this problem, I will write sys.setdefaultencoding('utf8') in Django settings file to solve it. But Actually, I don't know the tech detail of the above. What make me confused is: 1. Since I set the python source file encoding, why should I set the string encoding to ensure my string's encoding is my favorite encoding? What's the different between "file encoding" and "string encoding"? 2. Since I set the "file encoding" and "string encoding", why do UnicodeEncodeError still happen?
has comment: http://stackoverflow.com/comment/88199974
tagged with: encoding
score: 2
downvote count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/3828723
has answer: http://stackoverflow.com/a/51839539
tagged with: utf-8
favorite count: 0
has comment: http://stackoverflow.com/comment/88168501
has title: What's the different between "# -*- coding: utf-8 -*-" ，"from __future__ import unicode_literals" and "sys.setdefaultencoding("utf8")"
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/88168273
tagged with: django
tagged with: python
answer count: 1

http://stackoverflow.com/comment/88302170
type: QuestionComment
comment on: http://stackoverflow.com/q/50628586
has text: You can then reshape it back to correct shape when sending the model to RNN, train them, calculate scores and pass the scores back to GridSearchCV
score: 0
type: Comment

http://stackoverflow.com/comment/88354399
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50672238
type: Comment
has text: Have you already installed the `reptile` module? Then you can examine its code and docs. If not, you'll have to search the net for something similar. A starting point is the source of this `script.py`. With a name like that, I suspect `reptile` is a module written specifically for some tutorial or blog. I don't find anything like it on `pypi`.

http://stackoverflow.com/q/50553262
tagged with: opencv
answer count: 0
type: Question
tagged with: python-3.5
has comment: http://stackoverflow.com/comment/88117416
has title: how to delete particular images from folder using exception handling in python3
has comment: http://stackoverflow.com/comment/88129200
score: 0
has body: I have 500 images in a folder. I want to delete unreadable images using exception handling in python. When i am using : os.remove() then I am getting an error message : [WinError 3] The system cannot find the path specified: '-coast-ocean-horizon-sky-sunrise-sunset-dawn-atmosphere-plane-dusk-vehicle-flight-island-yellow-shadows-colors-holidays-hot-reflections-the-mediterranean-sea-sunset-sun-aegean-sea-atmosphere-of-earth-484653.jpg' " since this -coast-ocean-horizon-sky-sunrise-sunset-dawn-atmosphere-plane-dusk-vehicle-flight-island-yellow-shadows-colors-holidays-hot-reflections-the-mediterranean-sea-sunset-sun-aegean-sea-atmosphere-of-earth-484653.jpg') is the first image that is unreadable when iterating over the loop, how do I solve it?
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/50688669
score: 1
answers question: http://stackoverflow.com/q/50687623
upvote count: 1
has body: IIUYC, here is my aproach to this problem: import pandas as pd from datetime import datetime df = pd.DataFrame( [ [datetime(2016, 1, 1), 1000, 5], [datetime(2016, 1, 1), 1001, 1], [datetime(2016, 1, 2), 1000, 1], [datetime(2016, 1, 2), 1001, 1], [datetime(2016, 1, 3), 1000, 1], [datetime(2016, 1, 3), 1001, 5], [datetime(2016, 1, 4), 1000, 1], [datetime(2016, 1, 4), 1001, 1], ], columns=['date', 'spatial_pixel', 'column_A'] ) df # date spatial_pixel column_A # 0 2016-01-01 1000 5 # 1 2016-01-01 1001 1 # 2 2016-01-02 1000 1 # 3 2016-01-02 1001 1 # 4 2016-01-03 1000 1 # 5 2016-01-03 1001 5 # 6 2016-01-04 1000 1 # 7 2016-01-04 1001 1 def sum_days_in_row_with_condition(g): sorted_g = g.sort_values(by='date', ascending=True) condition = sorted_g['column_A'] &lt; 2 sorted_g['days-in-a-row'] = condition.cumsum() - condition.cumsum().where(~condition).ffill().astype(int) return sorted_g (df.groupby('spatial_pixel') .apply(sum_days_in_row_with_condition) .reset_index(drop=True)) # date spatial_pixel column_A days-in-a-row # 0 2016-01-01 1000 5 0 # 1 2016-01-02 1000 1 1 # 2 2016-01-03 1000 1 2 # 3 2016-01-04 1000 1 3 # 4 2016-01-01 1001 1 1 # 5 2016-01-02 1001 1 2 # 6 2016-01-03 1001 5 0 # 7 2016-01-04 1001 1 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88388493
accepted answer of: http://stackoverflow.com/q/50687623

http://stackoverflow.com/q/50680685
has comment: http://stackoverflow.com/comment/88380695
type: UnansweredQuestion
tagged with: pyodbc
has answer: http://stackoverflow.com/a/50681622
has title: Accessing oracle database through python
type: Question
linked to: http://stackoverflow.com/q/17115632
has comment: http://stackoverflow.com/comment/88381148
has answer: http://stackoverflow.com/a/57693010
tagged with: odbc
score: 0
has comment: http://stackoverflow.com/comment/88536562
answer count: 2
has comment: http://stackoverflow.com/comment/88392404
has comment: http://stackoverflow.com/comment/88378476
tagged with: oracle-database
tagged with: python
has body: I have spent almost last 48 hours trying almost all solutions available. My final resort is: I can access the database through Oracle SQL developer. Now I want to call the queries in python using pyodbc. But I keep getting this error: My code looks like this : import pyodbc oracledriver = '{xyxzz}' oracleuid = 'abcd' oraclepwd = 'abcd' oracleConn = pyodbc.connect(DRIVER=oracledriver, UID=oracleuid, PWD=oraclepwd, DBQ=oracledbq) Error : &lt;i&gt; InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') &lt;i&gt; I think the problem is with setting up database or something? Please help me with possible issues. Something on the lines of tsanames? (may be) Edit : When I try to get DSN file : I get this pop up : a connection could not be made using the file data source parameters entered Further info : All the info I have is : &lt;property name="URL" value="jdbc:oracle:thin:@abcd:1522/abcd" /&gt; &lt;property name="user" value="12345" /&gt; &lt;property name="password" value="12345" /&gt; I started using a different approach using sql alchemy. It looks to be working. But when I try to execute the query, i receive an error. Code and error follows : from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session import cx_Oracle engine = create_engine('oracle://user:pwdd@localhost:1521/dbname') connection = engine.connect() Session = scoped_session(sessionmaker(bind=engine)) s = Session() result = s.execute('select * from strategy_group_decode;') The error is : DatabaseError: (cx_Oracle.DatabaseError) DPI-1047: 64-bit Oracle Client library cannot be loaded: "C:\OraHome_2\oci.dll is not the correct architecture". See https://oracle.github.io/odpi/doc/installation.html#windows for help (Background on this error at: http://sqlalche.me/e/4xp6) Thank you in advance.

http://stackoverflow.com/a/50569440
has body: Python doesn't support exponentiation (and other math operations) for tuples. While it's possible to have code like this: print (1, 2) * 3 # produces (1, 2, 1, 2, 1, 2) print (1, 2) + (1, 2) # produces (1, 2, 1, 2) it's not a vector computations on the entire tuple. It's just a syntactic sugar for tuples concatenation. Also it seems that the snippet has a few typos/bugs. The line self.args=[Point(*args) for p in args] should be rather self.args=[Point(*p) for p in args] Class LineString doesn't have move() method. And the distance() calculation should be slightly changed (notice that I replaced - with + in the formula): return math.sqrt((p1.x - p2.x)**2 + (p1.y - p2.y)**2)
upvote count: 1
answers question: http://stackoverflow.com/q/50569394
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/comment/88105203
score: 0
type: AnswerComment
has text: The line=' '.join(edit) is giving error **TypeError: sequence item 3: expected str instance, int found** . Can you explain this part little bit
type: Comment
comment on: http://stackoverflow.com/a/50547199

http://stackoverflow.com/q/50617477
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88244803
has answer: http://stackoverflow.com/a/50617726
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/379906
has answer: http://stackoverflow.com/a/50618632
has answer: http://stackoverflow.com/a/50620437
linked to: http://stackoverflow.com/q/5608702
possible better answer: http://stackoverflow.com/a/50617726
has comment: http://stackoverflow.com/comment/88245436
answer count: 3
has title: How to automatically retain the type of number when converting from string
accepted answer: http://stackoverflow.com/a/50618632
has body: Is there an easy and obvious way to convert a string to a number of whatever type it looks like as a string, in other words I'd like to retain its type, whether it looks like int, float or complex and convert from string to number. This would be handy for example when reading data from text file. Usually conversion is made from string to a certain type of number for example a=int('2.2'). The downside of this is that 2.2 is not int and it will be cut to 2. Is there an easy and obvious way to let the code decide which type of number it is and convert to that type? A similar question How do I parse a string to float or int in Python is a basic question of how to convert to int or float. My question went further and asked the code to decide which type of number it is. A similar question How can I convert a string to either int or float with priority of int is a little hard to understand what the questions is, and the accepted answer does not cover my case.

http://stackoverflow.com/a/50669602
has comment: http://stackoverflow.com/comment/88349422
has comment: http://stackoverflow.com/comment/88349473
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50669523
has comment: http://stackoverflow.com/comment/88349282
answers question: http://stackoverflow.com/q/50669523
type: Answer
has comment: http://stackoverflow.com/comment/88349252
has body: Standard quoting rules for csv says that " are quoted by doubling, so in your line starting with 3, the four """" are interpreted as two quoted ". You don't show the end of the line, but perhaps the initial " on each line shouldn't be there? See quotechar, quoting, and doublequote in the docs: http://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.read_csv.html for more info.
has comment: http://stackoverflow.com/comment/88349444

http://stackoverflow.com/a/50621063
type: Answer
has comment: http://stackoverflow.com/comment/88327900
score: 4
upvote count: 4
has body: You can do this in Perl and it will run in a matter of seconds for 100 million lines. use strict; use warnings; use feature 'say'; # read command line arguments my ( $first_length, $second_length, $lines, $first_word, $second_word ) = @ARGV; $first_word //= 'TRY'; $second_word //= 'OFTEN'; # define your alphabet of random characters my @alphabet = ( 'a' .. 'z', q{ } ); my $max_rand = scalar @alphabet; foreach my $i ( 1 .. $lines ) { say join( q{ }, ( join q{}, map { $alphabet[ int rand $max_rand ] } 1 .. $first_length ), $first_word, ( join q{}, map { $alphabet[ int rand $max_rand ] } 1 .. $second_length ), $second_word, ); } This program takes three or five arguments: $ perl foo.pl 3 4 100000000 TRY OFTEN On my machine it took about three seconds to generate the full 100M lines. The output looks like this: wab TRY mcqb OFTEN tdb TRY tobw OFTEN rlf TRY lg v OFTEN ofn TRY oxdf OFTEN o j TRY vcfp OFTEN ffv TRY doud OFTEN lvl TRY ckci OFTEN xqh TRY wnaa OFTEN fhj TRY pmp OFTEN oxe TRY swyi OFTEN
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50613848
has comment: http://stackoverflow.com/comment/88312615
answers question: http://stackoverflow.com/q/50613848

http://stackoverflow.com/comment/88337965
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50663898
type: Comment
has text: @Gurman I need to find the ip inside a large text, your example doesnt work

http://stackoverflow.com/comment/88115888
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50551020
score: 0
has text: still need help guys so please help with this question. thank you

http://stackoverflow.com/comment/88347136
comment on: http://stackoverflow.com/a/50667904
type: AnswerComment
score: 0
type: Comment
has text: Also, go inside the folder where you've kept chromedriver and do `chmod +x chromedriver.exe`

http://stackoverflow.com/a/50545502
score: 1
accepted answer of: http://stackoverflow.com/q/50544754
has body: I finally found a solution. All I had to do was add this: STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), 'DjangoProjects\Sample\website\static' ) In the settings and also moved: {% load staticfiles %} To the very top of the HTML document, instead of under. I put it under at first because it wasn't giving a red line which to me seems like there isn't an error.
upvote count: 1
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50544754
downvote count: 0

http://stackoverflow.com/comment/88358710
has text: @coldspeed thanks a lot! That helps. Let me see how I can modify it further. Thanks again.
comment on: http://stackoverflow.com/q/50674350
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/50711613
score: 0
has body: As @nuric mentioned the problem is with input image dimension. If you input image has a height of 48, width of 48 and input channel is 3 which results in (3,48,48), then your input to the model be (batch size, 3, 48, 48). here batch size is nothing but number of training images in a single batch given to model for training Pseudo code training_list = [] for i in range(0, batch_size): image = read_image(training_set[i]) training_list.append(image) training_set = numpy.array(training_list) so now the dimension of training set are (batch size, 3, 48, 48)
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50686404
answers question: http://stackoverflow.com/q/50686404

http://stackoverflow.com/comment/98438101
score: 0
type: Comment
has text: Thanks, that's nice, but the format of text isn't the same in documents(
comment on: http://stackoverflow.com/a/50601592
type: AnswerComment

http://stackoverflow.com/comment/88393787
comment on: http://stackoverflow.com/a/50691768
type: Comment
has text: It probably has something to do with conflicting paths from anaconda/python2/python3. You should probably use virtual environments or use pyenv from here: https://github.com/pyenv/pyenv
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88332988
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50659747
type: QuestionComment
has text: Thanks for all the help. I called the functions and not it saying NameError: name 'age' is not defined. I tried editing the code but that isnt working either. And i guess stackoverflow is telling me that the question i posted wasn't liked or received well by the community and i could be blocked entirely. It's my first day on this site.

http://stackoverflow.com/q/50672356
linked to: http://stackoverflow.com/q/29828825
tagged with: matplotlib
has title: matplotlib: customised x-axis ticks for cdf of datetime values
accepted answer: http://stackoverflow.com/a/50680477
tagged with: cdf
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0
has body: I have a cdf of datetime list. After running the following code, where objDate is a list of datetime values (format: %Y-%m-%d), I get the cdf with ticks on x axis showing every second year in the range of values. How can I get customized labels for ticks along x-axis by specifying: 1. the range (min year and max year) 2. interval (lets say 6 months apart, so that tick labels are like 01/17, 07/17, 01/18, 07/18, ... ) import matplotlib.pyplot as plt import pandas as pd ser = pd.Series(objDate) ser.hist(cumulative=True, density=1, bins=500, histtype='step') plt.show()
has answer: http://stackoverflow.com/a/50680477
tagged with: python
downvote count: 0
score: 1
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88369795

http://stackoverflow.com/q/50654530
score: 1
type: Question
has body: I'm developing a custom network module for Ansible 2.5.2 for MikroTik RouterOS. I want to change the remote username under the hood, e.g. if in my inventory I have ansible_user: ansible, I would like to change it to ansible_user: ansible+cet. I have seen modules that do this in action plugins, like here: CFSworks/ansible-routeros. However, it seems that in Ansible 2.5 with network_cli connection type this is no longer the case. When I add the following sample action plugin to plugins/action directory nothing happens – I don't see routeros action plugin is called in debug console: class ActionModule(_ActionModule): def run(self, tmp=None, task_vars=None): display.debug('routeros action plugin is called') result = super(ActionModule, self).run(task_vars=task_vars) return result This is my playbook: - hosts: routeros gather_facts: no connection: network_cli tasks: - ... And this is my inventory: routeros: hosts: example: ansible_host: 192.168.88.1 ansible_user: ansible # ansible_user: ansible+cet &lt;-- i want to add '+cet' on the fly ansible_ssh_pass: ansible ansible_network_os: routeros What is the proper way to replace the connection user in Ansible 2.5 with network_cli connection type?
downvote count: 0
has title: Change remote user in custom module
has comment: http://stackoverflow.com/comment/88320393
tagged with: ansible
has comment: http://stackoverflow.com/comment/88320369
tagged with: ansible-inventory
favorite count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/88320284
type: UnansweredQuestion
upvote count: 1
tagged with: python

http://stackoverflow.com/a/50551893
score: 0
answers question: http://stackoverflow.com/q/50551399
type: AcceptedAnswer
has body: def Sign_Up(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): cd = form.cleaned_data name = cd['name'] email = cd['email'] password = cd['password'] user = form.save() user.refresh_from_db() user.save() user = authenticate(username=email, password=password) return HttpResponseRedirect('/') else: form = SignUpForm() return render(request,'signup.html', {'form':form}) def Sign_In(request): if request.method =='POST' : form = SignInForm(request) if form.is_valid(): F = form.cleaned_data Eemail = F['email'] Epassword = F['password'] user=authenticate(username=F,password=Epassword) if user is not None: return HttpResponseRedirect("/") else: form=SignInForm() message='login failed' retuen render(request,'login.html',{'form':form,'message':message}) look at upside code
type: Answer
accepted answer of: http://stackoverflow.com/q/50551399
has comment: http://stackoverflow.com/comment/88154113
has comment: http://stackoverflow.com/comment/88143911

http://stackoverflow.com/q/50589912
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50594949
type: Question
has title: python 3.X windows multiprocessing
has body: I have read many topics about differences between window and linux multiprocessing, but still I cannot find the answer. I have script like: def create_file(): #here user define output file name def READ_MANY_LOG(): #here user define path to log files and we read all these logs to one list() def select_unic_value(READ_MANY_LOG): #here specified unic value selected def SEARCH_ENGINE(search_criteria, READ_MANY_LOG): #here perform search from all logs with search_criteria and stored to multiprocess dict (return_dict) def sort_all_logs_per_unic_value(create_file, select_unic_value): mpc = 0 mpa = [] for n in select_unic_value: search_criteria = criteria(n) mps = Process(target=SEARCH_ENGINE, args=(search_criteria, READ_MANY_LOG)) mpa.append(mps) mpc = mpc + 1 if mpc&gt;=multiprocess.cpu_count(): for p in mpa: p.start() for p in mpa: p.join() For t_g in return_dict.values(): for t_x in t_g: print(t_x,file=out, flush=True, end='') print('PRINT done') mpc = 0 mpa = [] return_dict = multiprocess.Manager().dict() create_file() READ_MANY_LOG() select_unic_value(READ_MANY_LOG) if __name__ == "__main__": MULT.freeze_support() SORT_BY_MAC_DIR(output_name) It works perfect on linux, because multiprocess inherit values from create_file() , READ_MANY_LOG(), select_unic_value(READ_MANY_LOG) and start multiprocess only for SEARCH_ENGINE. But on windows because of spawn it starts the whole script in different process. Is there any way for windows to start multiprocess only for specific part : SEARCH_ENGINE ? thanks a lot in advance.
score: 0
answer count: 1

http://stackoverflow.com/q/50556062
tagged with: discord.py
has answer: http://stackoverflow.com/a/50556219
accepted answer: http://stackoverflow.com/a/50556219
score: 0
has comment: http://stackoverflow.com/comment/88123132
answer count: 1
has comment: http://stackoverflow.com/comment/88128972
has title: Discord.py music bot, using a text file to save volume integer but I get ValueError: invalid literal for int() with base 10: ''
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88123185
has body: I've been trying to make a Discord.py bot. While modifying some of the base code for the music portion to store the volume in a text file(so it's consistent everytime it plays a new song) and I ran into some problems. ValueError: invalid literal for int() with base 10: '' Here's my code for the relevant portion: @commands.command(pass_context=True, no_pm=True) async def volume(self, ctx, value: int): """Sets the volume of the currently playing song.""" state = self.get_voice_state(ctx.message.server) with open(r'E:\PythonProjects\WeebBot\textfiles\volumefile.txt', 'r+') as volumefile: open(r'E:\PythonProjects\WeebBot\textfiles\volumefile.txt', 'w') volumefile.write(str(value)) if state.is_playing(): read_data = volumefile.read() player = state.player player.volume = int(read_data.rstrip('\n')) / 100 await self.bot.say('Set the volume to {:.0%}'.format(player.volume)) volumefile.close() I've tried using floats (player.volume uses 0.1 to 2.0 as values for volume from 1% to 200%) and I think I also delete any \n chars that might show up at the end of the file. I'm only reading ints all bunched up so I don't believe I need to do anything else?
type: Question

http://stackoverflow.com/comment/88309493
type: QuestionComment
comment on: http://stackoverflow.com/q/50648367
has text: Well, sorry to RTFM, but: [docs for moveToThread](https://doc.qt.io/qt-5/qobject.html#moveToThread).
score: 1
type: Comment

http://stackoverflow.com/q/50641824
has title: Adding further properties to a function: timing and iteration improvement
tagged with: mathematical-optimization
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 1
type: Question
tagged with: numpy
upvote count: 1
has body: I have a function written in python which does two procedures: Preprocessing: read in data from an array and compute some values that I will later need to prevent repeated computation Iterate and compute a 'summary' of the data at every stage and use this to solve an optimisation problem. The code is as follows: import numpy as np def iterative_hessian(data, targets, sketch_method, sketch_size, num_iters): ''' Original problem is min 0.5*||Ax-b||_2^2 iterative_hessian asks us to minimise 0.5*||S_Ax||_2^2 - &lt;A^Tb, x&gt; for a summary of the data S_A ''' A = data y = targets n,d = A.shape x0 = np.zeros(shape=(d,)) m = int(sketch_size) # sketching dimension ATy = A.T@y covariance_mat = A.T.dot(A) for n_iter in range(int(num_iters)): S_A = m**(-0.5)*np.random.normal(size=(m, n)) B = S_A.T.dot(S_A) z = ATy - covariance_mat@x0 + np.dot(S_A.T, np.dot(S_A,x0)) # x_new = np.linalg.solve(B,z) x0 = x_new return np.ravel(x0) In practise I do not use the S_A = m**(-0.5)*np.random.normal(size=(m, n)) line but use a different random transform which is faster to apply but in principle it is sufficient for the question. This code works well for what I need but I was wondering if there is a reasonable way to do the following: Instead of repeating the line S_A = m**(-0.5)*np.random.normal(size=(m, n)) for every iteration, is there a way to specify the number of independent random copies (num_iters - which can be thought of as between 10 and 30) of S_A that are needed prior to the iteration and scan through the input only once to generate all such copies? I think this would store the S_A variables in some kind of multi-dimensional array but I'm not sure how best to do this, or whether it is even practical. I have tried a basic example doing this in parallel but it is slower than repeatedly passing through the matrix. Suppose that I want to endow this function with more properties, for instance I want to return the average time taken on line x_new = np.linalg.solve(B,z). Doing this i…
tagged with: iteration
favorite count: 0
tagged with: python
tagged with: large-data

http://stackoverflow.com/q/50665548
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 0
tagged with: django-forms
type: Question
has title: How to optimise Django FormView for database performance
tagged with: django-models
has answer: http://stackoverflow.com/a/50670425
has comment: http://stackoverflow.com/comment/88341206
answer count: 1
has body: I have never optimised my Django code and I'm not sure I fully understand Django optimisation docs so can you tell me if this FormView class can be somehow optimised (I'm guessing yes ...)? The part of code which I'm worried about is the Patient lookup: Patient.objects.get(patientId=self.kwargs['patientId']) - it's happening 3 times ... Does it mean Django will hit the database 3 times or only once? Can/should this be optimised, and if yes - how? class PatientNotes(SingleObjectMixin, FormView): slug_url_kwarg = 'patientId' slug_field = 'patientId' pk_url_kwarg = 'patientId' template_name = "patient/patient_detail.html" form_class = AddNewNoteForm def get_queryset(self): queryset = super(PatientNotes, self).get_queryset() self.current_patient = Patient.objects.get(patientId=self.kwargs['patientId']) my_result = queryset.filter(patient=self.current_patient) return my_result def post(self, request, *args, **kwargs): self.object = Patient.objects.get(patientId=self.kwargs['patientId']) return super().post(request, *args, **kwargs) def form_valid(self, form): self.object = form.save(commit=False) self.object.patient = Patient.objects.get(patientId=self.kwargs['patientId']) self.object.note_created_by_date = datetime.date.today() self.object.save() return super().form_valid(form) def get_success_url(self): return reverse('PatientDetailView', kwargs={'patientId': self.object.patient.patientId})

http://stackoverflow.com/a/50592142
has body: Yes, they are via function auto-specialization. In Julia, functions will auto-specialize on the concrete types when JIT compiling. This is true for all numbers, and in fact even things like Float64 are just types defined in Julia itself and use these same mechanisms. This blog post describes this pattern in more detail
accepted answer of: http://stackoverflow.com/q/50587864
type: AcceptedAnswer
downvote count: 0
score: 4
type: Answer
answers question: http://stackoverflow.com/q/50587864
has comment: http://stackoverflow.com/comment/88228256
has comment: http://stackoverflow.com/comment/88228986
upvote count: 4

http://stackoverflow.com/comment/88205904
comment on: http://stackoverflow.com/a/50597920
score: 0
type: Comment
has text: Thank you for your help! =)
type: AnswerComment

http://stackoverflow.com/a/50687280
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50686065
answers question: http://stackoverflow.com/q/50686065
has comment: http://stackoverflow.com/comment/88404132
type: AcceptedAnswer
downvote count: 0
has body: I'm not very familiar with Python but according to the MySQL documentation here: Result sets produced by the stored procedure are automatically fetched and stored as MySQLCursorBuffered instances. For more information about using these result sets, see stored_results(). "see stored_results()" leads to code examples featuring iteration over cursor.stored_results().
type: Answer

http://stackoverflow.com/q/50549910
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88110981
has comment: http://stackoverflow.com/comment/88110727
accepted answer: http://stackoverflow.com/a/50549966
has comment: http://stackoverflow.com/comment/88110751
has title: Numpy array multiple condition boolean
type: Question
tagged with: numpy
tagged with: boolean
answer count: 2
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/88110718
has comment: http://stackoverflow.com/comment/88110771
possible better answer: http://stackoverflow.com/a/50549956
has answer: http://stackoverflow.com/a/50549956
has comment: http://stackoverflow.com/comment/88110959
has comment: http://stackoverflow.com/comment/88110888
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50549966
upvote count: 2
has comment: http://stackoverflow.com/comment/88111046
has comment: http://stackoverflow.com/comment/88110787
has comment: http://stackoverflow.com/comment/88110810
tagged with: python
has comment: http://stackoverflow.com/comment/88110874
has comment: http://stackoverflow.com/comment/88110670
has comment: http://stackoverflow.com/comment/88110667
has body: I want my array to pass two conditions. If I try to do this with just one I don't have any problems but if I'll give code two conditions python crashes. Here is my code: import numpy as np from collections import deque queue = deque([], maxlen=10) queue.appendleft(31) queue.appendleft(32) queue.appendleft(33) cond1 = 35 cond2 = 30 A_1 = np.array(queue) print(cond2 &gt; A_1 &lt; cond1) # print(A_1 &gt; 30) # works # array([ True, True, True], dtype=bool) print(((cond2 &gt; A_1 &lt; cond1).sum() == A_1.size).astype(np.int)) # print(((A_1 &gt; 30).sum() == A_1.size).astype(np.int)) # works # 1

django-allauth
tags question: http://stackoverflow.com/q/50652915
tags question: http://stackoverflow.com/q/50548685
type: Tag
tag name: django-allauth
tags question: http://stackoverflow.com/q/50696207
tags question: http://stackoverflow.com/q/50666402

http://stackoverflow.com/comment/88319122
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50648521
has text: Can you show how `IsActiveUser` is defined?

http://stackoverflow.com/q/50567546
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/88145155
type: UnansweredQuestion
has title: How to display a picture instead of the console window on raspberry pi
type: Question
tagged with: python
has body: I am building a DLP 3D printer based on a raspberry pi. The mechanical part is working fine so far. Now I am looking for a way to send static .png images to my DLP Beamer via HDMI using Python. Which would be the best solution for this problem? Currently my Raspberry Pi is booting to console and I am connecting via SSH. As a Python and Raspberry Pi beginner it is a bit difficult for me to choose the right approach which suits to my requirements. Using Google I found: framebuffer imageviewer //seems to need root Dispmanx pygame Is there any easier solution maybe with a small example? I would be very grateful for your help!
has answer: http://stackoverflow.com/a/50567712
score: 0
answer count: 1

http://stackoverflow.com/q/50626137
score: 0
has comment: http://stackoverflow.com/comment/88262422
favorite count: 0
tagged with: parsing
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: http://stackoverflow.com/tag/xls
tagged with: django
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/88262577
has title: Django cannot read Arabic from uploaded .xls file
type: Question
has body: When uploading a .xls file containing Arabic to my Django website, I get the following error when running code: UnicodeDecodeError 'charmap' codec can't decode byte 0x81 in position 655224: character maps to Here is my python / django code (it is original without any decoding as I tried many variants they all failed): #certain_file is the uploaded file certain_file = TextIOWrapper(request.FILES['certain_file'].file, encoding=request.encoding) with certain_file as f: soup = BeautifulSoup(f, "html.parser") #rest of code My goal is to parse uploaded file. Many thanks for the help in advance!

http://stackoverflow.com/comment/88595027
comment on: http://stackoverflow.com/a/50694476
type: AnswerComment
has text: I follow the curve fitting part much better now. However, how do you determine the initial equation of the parabola to be `parabola( x, .45, 2.33 )`? In my case, I have two lists and I want to determine the initial equation of the parabola.
score: 0
type: Comment

http://stackoverflow.com/comment/88343162
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50664779
has text: @Rlourenco, I've updated the answer. The main point is python would decode file by itself if you pass proper encoding name in function `open`.
score: 0

http://stackoverflow.com/comment/88350526
has text: I am asking to try `./Logs` not `./Logs/` Get rid of ending slash. lets see
type: Comment
comment on: http://stackoverflow.com/q/50670208
type: QuestionComment
score: 0

http://stackoverflow.com/a/50681613
accepted answer of: http://stackoverflow.com/q/50681408
upvote count: 4
has comment: http://stackoverflow.com/comment/88373182
type: AcceptedAnswer
downvote count: 0
has body: You say "I expect the fifth decimal value to round up". OK, but in what circumstances? Given that your example inputs only have 6 significant digits, and a Python float (64-bit) supports about 15 digits, you can safely add a tiny amount to get the behavior you want: (df2 + 1e-12).round(5) It gives: 0 0 0.70313 1 0.83122 This assumes the largest value in df2 is under 1000 or so, and the smallest value is less than about 1e-6 assuming 6 sigfigs. The addition of a small amount makes sure any trailing "5"s are rounded up, so long as your inputs are within some known range where the small addition won't make the results incorrect.
type: Answer
has comment: http://stackoverflow.com/comment/88376981
has comment: http://stackoverflow.com/comment/88372933
score: 4
answers question: http://stackoverflow.com/q/50681408

http://stackoverflow.com/comment/88437870
score: 0
type: AnswerComment
has text: since i don' t know the character of your dataset(columns and classes) and the way you are parsing them from the file, the only thing can't guide me is to know the shape of np.array(batch_x).shape and np.array(batch_y).shape
type: Comment
comment on: http://stackoverflow.com/a/50711097

http://stackoverflow.com/comment/88223747
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50554549
has text: Thanks for the answer, however i tried both but still get the error below: WARNING:root:Got recoverable error from GET https://jira-server.com/rest/api/2/serverInfo, will retry [1/3] in 9.50354793356s. Err: 401 Unauthorized, i think this has something to do with the jira itself cause i could not get status_code 401 after this warnning.

http://stackoverflow.com/comment/137088526
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50654276
has text: If json cannot load it, pandas cannot do it either. The file must be in the right json format, which it is not. Can anyone with an error when loading the file with json drop a remark here that they could load the file with pandas instead? I do not see why this should work then, see the remark below the question. I could not load my json file with pandas either, therefore I doubt that this answer answers the question about the JSONDecodeError.

http://stackoverflow.com/comment/88152449
has text: I've downvoted because this isn't a minimum, complete, verifiable example. It would not be possible to reproduce your bug with the code you provide.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50563488
score: 1

http://stackoverflow.com/q/50560453
has comment: http://stackoverflow.com/comment/88133702
has comment: http://stackoverflow.com/comment/88168667
score: 0
tagged with: python-3.x
has title: Error during Installing nltk 2.0.4 on python 3.6
answer count: 0
type: UnansweredQuestion
tagged with: python
type: Question
tagged with: nltk
has body: I am new to python and trying to install NLTK 2.0.4 but following exception is thrown: Command "python setup.py egg_info" failed with error code 1 in C:\Users\AHMADR~1\AppData\Local\Temp\pip-install-j3n9bb9v\nltk\ Any suggestion to get rid of this error or any other way to install this version on python 3.6. My OS is Windows and I am using this command to install pip install -Iv nltk==2.0.4 Thanks in advance

http://stackoverflow.com/a/50616046
accepted answer of: http://stackoverflow.com/q/50615463
has comment: http://stackoverflow.com/comment/88242001
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50615463
type: Answer
score: 2
has body: Type Error: can't multiply sequence by non-int of type 'float' means exactly what it says. You cannot multiply a non-number(non-int) data type with a numbered data type. For example, you cannot multiply strings with a number. The above code you have submitted actually works. But, since you are getting this error, I assume the above code is just a proxy for your actual code. So, I'll tell how I solved the same error that I had gotten when I was doing something similar. Let's say there is a csv file that contains the subject marks for a class like the table below | | Maths | English | | Adam | 98 | 78 | | John | 34 | 89 | As you can see, there is a row index as well as a column index. If you run marks = pd.read_csv("marks.csv") marks will have 3 columns with the firs column containing the names of the students. Pandas read assumed the first column was part of the data. Now, if you multiply this with a Numpy array, you will get an error. Since, numbers can't be multiplied with strings. To solve this, we need to explicitly tell pandas that the first column in the file is the row index. marks = pd.read_csv("marks.csv", index_col=0) The parameter, index_col tells which column in the file to take as the row index. You can read about this in detail in their documentation, here.
upvote count: 2

http://stackoverflow.com/q/50687366
tagged with: qthread
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has body: I want to know how to kill a QThread. I have to make a game and the 'enemy' moves until it's dead. What I am doing at the moment is to just override the run method with a loop that ends when it dies but with what I have until the moment I can't tell or try if it will work and I would like to know if it works before moving on to the GUI. So what I have until the moment is the following: from PyQt5.QtCore import QThread class Enemy(QThread): def __init__(self): super().__init__() self.alive = True def run(self): while self.alive: # here I code the moving . . . Outside this, I code if the enemy gets killed I change the attribute alive of the enemy to False. So, my question is: do I have to add something after the while breaks (which it will if the enemy dies)? Or do I have to add something like self.terminate()? Thank you
tagged with: pyqt5
type: Question
has comment: http://stackoverflow.com/comment/88384485
has comment: http://stackoverflow.com/comment/88384593
linked to: http://stackoverflow.com/q/323972
score: 0
has title: How to kill a QThread
tagged with: python

http://stackoverflow.com/q/50643953
has comment: http://stackoverflow.com/comment/88298259
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50655934
accepted answer: http://stackoverflow.com/a/50655934
has title: Dictionary Structure (dict -> dict) with a list in it comparison
possible better answer: http://stackoverflow.com/a/50644591
has answer: http://stackoverflow.com/a/50644591
type: Question
score: 1
has comment: http://stackoverflow.com/comment/88298240
upvote count: 2
tagged with: python-2.7
answer count: 2
has comment: http://stackoverflow.com/comment/88298787
downvote count: 1
favorite count: 0
has body: Have this dict -> dict -> list structure Want to compare 2 structures of this kind. one = {"1iG5NDGVre": {"118": ["test1", "test2", "test3", "tcp", "22", "Red", "0.0.0.0/0"]}} two = {"1iG5NDGVre": {"118": ["test1", "test2", "test3", "tcp", "22", "Red", "Blue", "0.0.0.0/0"]}} This code works well: def compare(one,two): for mainkey in one: for subkey in one[mainkey]: return set(one[mainkey][subkey]) ^ set(two[mainkey][subkey]) However when dict -> dict have more or less keys it should be returned by a function that key was added or removed along with all list values. Also if list was modified, it should be returned by the program that the list was modified. Anybody can help on this? It is pretty much used to compare two JSONs, I want to see when keys were removed, added or its values modified. Update 1: I am still learning Python For this structure: one = {"1iG5NDGVre": {"118": ["test1", "test2", "test3", "tcp", "22", "Red", "0.0.0.0/0"]}} two = {"1iG5NDGVre": {"118": ["test1", "test2", "test3", "tcp", "22", "Red", "Blue", "0.0.0.0/0"]},"119": ["test10","test11"]} It does not work. It should print as output: 118 was modified. New values Blue. 119 was added with values test10 test11 and for these scenarios: 1. one = {"1iG5NDGVre": {"118": ["test1", "test2", "test3", "tcp", "22", "Red", "0.0.0.0/0"]}} two = {"1iG5NDGVre": } Should print as output: 118 was removed with values test1 test2 test3 tcp 22 Red 0.0.0.0/0 2. one = {"1iG5NDGVre": {"118": ["test1", "test2", "test3", "tcp", "22", "Red", "0.0.0.0/0"]}} two = {"1iG5NDGVre": {"118": ["test100", "test200", "test3", "tcp", "22", "Red", "Blue", "0.0.0.0/0"]},"119": ["test10","test11"]} Should print as output: 118 was modifed. New values test100 test200 I want to cover all possible cases. I do this as I said for JSON comparison.

http://stackoverflow.com/q/50638159
duplicate of: http://stackoverflow.com/q/14156473
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/2400504
score: 1
linked to: http://stackoverflow.com/q/2400504
has answer: http://stackoverflow.com/a/50638245
has title: replace list of strings using dictionary
has comment: http://stackoverflow.com/comment/88286445
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88286408
has comment: http://stackoverflow.com/comment/88286313
has body: I have python code my_list = ['hsdpa_-_rl_fail', 'avg_reported_cqi.', 'fach-c_load_ratio', 'canc_isho_cpich/ecno_nrt_m1010c209'] my_dict = {'-' : 'dash' , '.':'dot' , '/':'slash'} I want search and replace in my_list as per mapping given in my_dict that is my_dict key shall be replaced by respective value in all element of my_list. How this can be done in pythonic way?
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/76611865
type: Answer
has body: Please find below Code with open('data.txt', 'r') as file: text = file.read() text = text.replace('\n', '').replace(' ', '') bracket_start = text.index('[') bracket_end = text.rindex(']') content = text[bracket_start+1:bracket_end] elements = content.split(',') elements = [elem.strip() for elem in elements] result = ' '.join(elements) print(result)
answers question: http://stackoverflow.com/q/50661970
score: 0

http://stackoverflow.com/q/50637420
favorite count: 0
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/57603785
score: 1
upvote count: 1
has title: updating and merging a column in pandas dataframe
type: Question
has answer: http://stackoverflow.com/a/50637466
accepted answer: http://stackoverflow.com/a/50637466
tagged with: dataframe
has body: I have a column 'A' in two dataframes, say df1 and df2. df1: | ID | A | | |------|---|--| | ID1 | 5 | | | ID2 | 6 | | | ID3 | 7 | | | ID4 | 8 | | df2: | ID | A | | |------|---|--| | ID1 | 5 | | | ID2 | 1 | | | ID3 | 8 | | | ID5 | 7 | | | ID6 | 8 | | | ID7 | 9 | | Required updated df1: | ID | A | | |------|---|--| | ID1 | 5 | | | ID2 | 1 | | | ID3 | 8 | | | ID4 | 8 | | | ID5 | 7 | | | ID6 | 8 | | | ID7 | 9 | | I want to update the column 'A' in df1 with values from df2 if the ID is in df2, else I want to keep the same value in df1. Moreover, if there are new IDs in df2, I want to add the new values in df1. I have seen the documentation of pd.DataFrame.update it does update the values from the df2 to df1 but it does not adds the new values to df1. Any help will be appreciated. Thanks in advance.
has answer: http://stackoverflow.com/a/57603785
answer count: 2
tagged with: pandas
downvote count: 0
tagged with: algorithmic-trading

http://stackoverflow.com/comment/88120960
comment on: http://stackoverflow.com/a/50554449
has text: So I installed anaconda, did conda install tensorflow, it said it downloaded but when i go onto my python project it says no module named tensorflow
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50547610
downvote count: 0
has title: Historical price per minute between two timestamps for a cryptocurrency
has answer: http://stackoverflow.com/a/50547893
accepted answer: http://stackoverflow.com/a/50547893
has comment: http://stackoverflow.com/comment/88106037
has comment: http://stackoverflow.com/comment/88106306
has comment: http://stackoverflow.com/comment/88106320
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88106176
has comment: http://stackoverflow.com/comment/88105950
score: 1
type: Question
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/88106252
answer count: 1
has comment: http://stackoverflow.com/comment/88106046
favorite count: 0
has body: I am successfully using the following code to output the price per minute for historical price data ranging back a couple of hours: import requests import datetime import pandas as pd import matplotlib.pyplot as plt def minute_price_historical(symbol, comparison_symbol, limit, aggregate, exchange=''): url = 'https://min-api.cryptocompare.com/data/histominute?fsym={}&amp;tsym={}&amp;limit={}&amp;aggregate={}'\ .format(symbol.upper(), comparison_symbol.upper(), limit, aggregate) if exchange: url += '&amp;e={}'.format(exchange) page = requests.get(url) data = page.json()['Data'] df = pd.DataFrame(data) df['timestamp'] = [datetime.datetime.fromtimestamp(d) for d in df.time] return df time_delta = 1 # Bar width in minutes df = minute_price_historical('BTC', 'USD', 9999, time_delta) print('Max length = %s' % len(df)) print('Max time = %s' % (df.timestamp.max() - df.timestamp.min())) plt.plot(df.timestamp, df.close) plt.xticks(rotation=45) plt.show() Thumbs up to the Cryptocompare API guys. Ultimately, I would like to achieve the following: 1) Output the price per minute between two timestamps, e.g. 3/12/18 3.00pm (15.00) and 3/12/18 3.30pm (15.30) 2) I would like to save this data into 3 columns "Token"(in the case above BTC), "Timestamp", "Price" as a csv or json ideally Anyone with an idea or two on how to do that with the given code or an alternative approach?
has comment: http://stackoverflow.com/comment/88106384
tagged with: python-3.x
tagged with: python
tagged with: cryptocurrency
has comment: http://stackoverflow.com/comment/88106007

http://stackoverflow.com/q/50577489
tagged with: tweepy
tagged with: excel
type: Question
has answer: http://stackoverflow.com/a/50578877
tagged with: twitter
tagged with: python-2.7
score: 0
has body: Think I'm overlooking the answer so need a fresh pair of eyes. My script should search and get tweets, then write the tweet date, username, and tweet text on one row, separated by columns. Then write the next matching tweet to a new row and so on. Printing the returned twitter object values confirms all ok. Can print and separate the data for each tweet. However, when writing to Excel, my loop code just writes the first tweet n times, without the remaining tweets. Code: print ('TEST PRINT...') for tweet in tweepy.Cursor(api.search, search).items(numberOfTweets): print(tweet.created_at) print(tweet.user.screen_name) print(tweet.text) print '\n' for tweet in tweepy.Cursor(api.search, search).items(numberOfTweets): for rowNum in range(3, sheet.max_row): sheet.cell(row=rowNum, column=1).value = tweet.created_at sheet.cell(row=rowNum, column=2).value = tweet.user.screen_name sheet.cell(row=rowNum, column=3).value = tweet.text break The second code block is the issue. How can I write the three above tweet values for each tweet on separate rows? Thanks in advance...
answer count: 1
has title: Python Openpyxl: Writing to sheet rows with multiple values from object
type: UnansweredQuestion
tagged with: python

gmail
type: Tag
tags question: http://stackoverflow.com/q/50608129
tags question: http://stackoverflow.com/q/50594442
tag name: gmail
tags question: http://stackoverflow.com/q/50695188
tags question: http://stackoverflow.com/q/50651811

http://stackoverflow.com/comment/88219959
has text: I'm always using the keras framework and not plain tensorflow, so I'm not 100% sure how to do that. I suggest to first understand what exactly you want to do and then look up some resources (like how to have multiple outputs, or how to create a softmax output). Also, your hidden_2 layer takes hidden_1 and not hidden_1_drop as an input. Was my suggestion of starting the network with an single layer and building it up when sure that works helped you in solving your problem?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50603453

http://stackoverflow.com/a/62364856
has body: A bit late but maybe someone else may find it helpful. You can parse the output of HDFStore.info(). Objects in table format have the type appendable: &gt;&gt;&gt; print(h5_table.info()) &lt;class 'pandas.io.pytables.HDFStore'&gt; File path: /tmp/df_table.h5 /df frame_table (typ-&gt;appendable,nrows-&gt;2,ncols-&gt;2,indexers-&gt;[index],dc-&gt;[]) &gt;&gt;&gt; print(h5_fixed.info()) &lt;class 'pandas.io.pytables.HDFStore'&gt; File path: /tmp/df_fixed.h5 /df frame (shape-&gt;[2,2]) This is a minimal (i.e. without error handling for missing file or key) example: def get_hd5_format(path, key): with pd.HDFStore(path) as store: info = store.info() return 'table' if 'typ-&gt;appendable' in next(k for k in info.splitlines()[2:] if k.startswith('/'+key)).split()[2] else 'fixed' Example usage: &gt;&gt;&gt; get_hd5_format('/tmp/df_table.h5', 'df') 'table' &gt;&gt;&gt; get_hd5_format('/tmp/df_fixed.h5', 'df') 'fixed'
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50569465
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50569465
downvote count: 0

http://stackoverflow.com/q/50571317
favorite count: 0
possible better answer: http://stackoverflow.com/a/67199394
tagged with: python
has body: I'm using Pytrends to extract Google trends data, like: from pytrends.request import TrendReq pytrend = TrendReq() pytrend.build_payload(kw_list=['bitcoin'], cat=0, timeframe=from_date+' '+today_date) And it returns an error: ResponseError: The request failed: Google returned a response with code 429. I made it yesterday and for some reason it doesn't work now! The source code from github failed too: pytrends = TrendReq(hl='en-US', tz=360, proxies = {'https': 'https://34.203.233.13:80'}) How can I fix this? Thanks a lot!
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88158101
has comment: http://stackoverflow.com/comment/88158447
has comment: http://stackoverflow.com/comment/88153021
upvote count: 10
has comment: http://stackoverflow.com/comment/122248770
has comment: http://stackoverflow.com/comment/88158612
type: Question
has answer: http://stackoverflow.com/a/50616233
has answer: http://stackoverflow.com/a/50729238
accepted answer: http://stackoverflow.com/a/50616233
has comment: http://stackoverflow.com/comment/106667866
score: 10
has answer: http://stackoverflow.com/a/67199394
answer count: 6
has answer: http://stackoverflow.com/a/62323830
has comment: http://stackoverflow.com/comment/88153102
has comment: http://stackoverflow.com/comment/88175812
has answer: http://stackoverflow.com/a/75805852
downvote count: 0
tagged with: google-trends
has answer: http://stackoverflow.com/a/77485741
has title: Pytrends: The request failed: Google returned a response with code 429

pyqt5
tags question: http://stackoverflow.com/q/50575900
tags question: http://stackoverflow.com/q/50548820
tags question: http://stackoverflow.com/q/50545917
tags question: http://stackoverflow.com/q/50591822
type: Tag
tags question: http://stackoverflow.com/q/50671868
tags question: http://stackoverflow.com/q/50575492
tags question: http://stackoverflow.com/q/50593591
tags question: http://stackoverflow.com/q/50681354
tags question: http://stackoverflow.com/q/50657352
tags question: http://stackoverflow.com/q/50651712
tags question: http://stackoverflow.com/q/50548328
tags question: http://stackoverflow.com/q/50564390
tags question: http://stackoverflow.com/q/50549439
tags question: http://stackoverflow.com/q/50687366
tags question: http://stackoverflow.com/q/50578978
tags question: http://stackoverflow.com/q/50596027
tags question: http://stackoverflow.com/q/50637053
tags question: http://stackoverflow.com/q/50661112
tags question: http://stackoverflow.com/q/50648367
tags question: http://stackoverflow.com/q/50610214
tags question: http://stackoverflow.com/q/50664527
tags question: http://stackoverflow.com/q/50600811
tags question: http://stackoverflow.com/q/50655135
tags question: http://stackoverflow.com/q/50640196
tags question: http://stackoverflow.com/q/50596590
tags question: http://stackoverflow.com/q/50554791
tags question: http://stackoverflow.com/q/50620954
tags question: http://stackoverflow.com/q/50590087
tags question: http://stackoverflow.com/q/50562433
tags question: http://stackoverflow.com/q/50560412
tags question: http://stackoverflow.com/q/50566738
tags question: http://stackoverflow.com/q/50553886
tags question: http://stackoverflow.com/q/50556216
tags question: http://stackoverflow.com/q/50566848
tags question: http://stackoverflow.com/q/50601611
tags question: http://stackoverflow.com/q/50688163
tags question: http://stackoverflow.com/q/50547593
tags question: http://stackoverflow.com/q/50572925
tag name: pyqt5
tags question: http://stackoverflow.com/q/50602489
tags question: http://stackoverflow.com/q/50611181
tags question: http://stackoverflow.com/q/50593841
tags question: http://stackoverflow.com/q/50557450
tags question: http://stackoverflow.com/q/50606443
tags question: http://stackoverflow.com/q/50659758
tags question: http://stackoverflow.com/q/50563382
tags question: http://stackoverflow.com/q/50625583
tags question: http://stackoverflow.com/q/50631443
tags question: http://stackoverflow.com/q/50556719
tags question: http://stackoverflow.com/q/50608275

http://stackoverflow.com/a/50622270
answers question: http://stackoverflow.com/q/50621680
upvote count: 2
has body: As to why it happens, let's wait for someone more expert, not sure there really is a reason. NumPy keeps dimensions when slicing and drops them when indexing. It's actually a Python thing, the same happens with lists. You can drop single-dimensional axes with np.squeeze a = np.ones((2500, 500)) a[0].shape (500,) a[0:1].shape (1, 500) a[0:1].squeeze().shape (500,)
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/a/50644311
upvote count: 2
has comment: http://stackoverflow.com/comment/88299376
has comment: http://stackoverflow.com/comment/88299482
has body: from collections import Counter dict(Counter(your_dict).most_common(5)) OUTPUT: {'10': 7, '3': 5, '4': 8, '5': 8, '7': 3}
type: Answer
downvote count: 1
has comment: http://stackoverflow.com/comment/88300139
has comment: http://stackoverflow.com/comment/88299222
score: 1
answers question: http://stackoverflow.com/q/50644186
has comment: http://stackoverflow.com/comment/88299606

http://stackoverflow.com/q/50659268
favorite count: 0
linked to: http://stackoverflow.com/q/1732348
tagged with: python
tagged with: regex
possible better answer: http://stackoverflow.com/a/50659625
downvote count: 0
linked to: http://stackoverflow.com/q/753052
has answer: http://stackoverflow.com/a/50659625
score: 1
has comment: http://stackoverflow.com/comment/88328641
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88328584
type: Question
answer count: 2
has title: Parse text using regex to extract valid passage
upvote count: 1
has comment: http://stackoverflow.com/comment/88329614
has answer: http://stackoverflow.com/a/50659354
accepted answer: http://stackoverflow.com/a/50659354
has body: How can I parse text on python using regex to extract a valid passage from stuff like near accomodation\n\nNear accomodation is one case of accomodation. By changing the shape of the lens, accomodation adjusts the refractory power to the distance of an object under observation. The issue is I want to extract Near accomodation is one case of accomodation. By changing the shape of the lens, accomodation adjusts the refractory power to the distance of an object under observation. That means the valid text should end on a period and get rid of stuff like "The issue is" which is an unfinished sentence as well as anything that comes before characters like \n. Another example would be The level of dopamine available in nerve terminals is controlled by the enzyme monoamineoxidase, which inactivates the neurotransmitter in the presynapse. \n\n Which should extract The level of dopamine available in nerve terminals is controlled by the enzyme monoamineoxidase, which inactivates the neurotransmitter in the presynapse. So get also rid of any html tags So I need clean passages that end up in a period. Without any newline characters or html tags that could come after or before the relevant passage. All passages are more or less like the examples I provided.

http://stackoverflow.com/q/50560882
tagged with: python
has comment: http://stackoverflow.com/comment/88136421
answer count: 1
downvote count: 1
tagged with: computer-science
accepted answer: http://stackoverflow.com/a/50562500
tagged with: algorithm
upvote count: 4
has body: Consider the following problem (and solution): Given n non-negative integers representing the height of bars of width one of a histogram, find the maximum area rectangle of histogram i.e. the maximum area rectangle contained in the histogram. The key idea is to calculate: R[i] = Area of the largest rectangle with the bar at i is as the smallest bar in the rectangle (i.e. width = H[i]) left[i] = the left most boundary of R[i], which is the leftmost bar greater than H[i]. right[i] = the right most boundary of R[i], which is the rightmost bar greater than H[i]. I've understood that a stack is needed to calculate right and left but I think I was able to supply a similar solution without using a stack: def max_area_rect(lst): n = len(lst) right = [-1] * n left = [-1] * n right[n - 1] = n for i in range(n - 2, -1, -1): right[i] = i + 1 if lst[i] &gt; lst[i + 1] else right[i + 1] left[0] = -1 for i in range(1, n): left[i] = i - 1 if lst[i - 1] &lt; lst[i] else left[i - 1] max_res = -1 for i in range(n): right_len = right[i] - i -1 left_len = i - left[i] + 1 h = min(lst[right_len - 1], lst[left_len + 1]) res = (right_len + left_len) * h if res &gt; max_res: max_res = res return max_res # test print(max_area_rect([4, 2, 1, 8, 6, 8, 5, 2])) # expected result: 20 So my question is: Why do we need a stack? Is my way valid?
linked to: http://stackoverflow.com/q/4311694
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/50562500
has title: Maximum area of a rectangle in an histogram - Why do we need stack?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88134036

http://stackoverflow.com/comment/88155539
has text: shell output: >>> Techpost.published.filter(publish__year=2018) <QuerySet [<Techpost: test>]> but month and day giving empty queryset
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50572611

http://stackoverflow.com/q/50669917
favorite count: 0
has title: python 3: error when dump/load sympy lambdify-epression
tagged with: python
tagged with: python-3.x
upvote count: 2
tagged with: pickle
has answer: http://stackoverflow.com/a/50670095
type: AnsweredQuestion
has body: I want to save/serialize a Sympy-Lambdify func into a file and use/load it by another python-program later. Case 1: it works well import dill import sympy as sp from sympy.utilities.lambdify import lambdify dill.settings['recurse'] = True a,b = sp.symbols('a, b') expr = a**2 + 2*a + 1 + b func = lambdify((a,b), expr) myfunc = dill.loads(dill.dumps(func)) print(myfunc) print(type(myfunc)) print(myfunc(2,3)) output: &lt;function &lt;lambda&gt; at 0x00000210AA0D6598&gt; &lt;class 'function'&gt; 12 Case 2： return errors import dill import sympy as sp from sympy.utilities.lambdify import lambdify dill.settings['recurse'] = True a,b = sp.symbols('a, b') expr = a**2 + 2*a + 1 + b func = lambdify((a,b), expr) with open('expr', 'wb') as outf: dill.dump(expr, outf) with open('expr','rb') as inf: myfunc= dill.load(inf) print(myfunc) print(type(myfunc)) print(myfunc(2,3)) Output: a**2 + 2*a + b + 1 &lt;class 'sympy.core.add.Add'&gt; Traceback (most recent call last): File "test.py", line 25, in &lt;module&gt; print(myfunc(2,3)) TypeError: 'Add' object is not callable Could someone help me to fix it? Thank you all in advance!
tagged with: dill
type: Question
tagged with: sympy
score: 2
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50670095

http://stackoverflow.com/comment/88286069
score: 0
comment on: http://stackoverflow.com/q/50638043
type: Comment
type: QuestionComment
has text: where the text file is written? can you access that method?

http://stackoverflow.com/comment/88161545
comment on: http://stackoverflow.com/q/50576086
score: 0
type: QuestionComment
has text: @PeterLucas, i'm not sure if a `count` / `size` on the `state` column gives you what you want, but its in my answer. I think what you need is a count of different states per sales person, which requires a group by on sales person & state. please clarify, and I can update the answer
type: Comment

http://stackoverflow.com/q/50588666
has title: How to compare charcter to new line in python
score: 2
type: AnsweredQuestion
has body: How can I compare a char to '\n' in python? Here is what I'm trying to do: def grabInstructionsExecuted (str, beg): index = beg while str[index] != '\n' index += 1; return str[beg:index-1] However, I get this error: File "grabMIPS.py", line 7 while str[index] != '\n' ^ SyntaxError: invalid syntax I'm new to python, this seems pretty basic but I can't get it to work. Thank you.
has answer: http://stackoverflow.com/a/50588712
upvote count: 3
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/50588712
answer count: 2
has answer: http://stackoverflow.com/a/50589111
favorite count: 0
accepted answer: http://stackoverflow.com/a/50589111
has comment: http://stackoverflow.com/comment/88186743
tagged with: python

http://stackoverflow.com/q/50566993
type: UnansweredQuestion
has title: How can I start a bash script 20 seconds after startup?
tagged with: python
has body: I got a bash script that stops a program, mounts the pi and starts the program again. I would like to start it on startup, but after the program itself started. So my idea was to simply wait some time (20 or 30 seconds) and start the script then (task.sh). Any idea how I can do that? Or any other idea how to solve this? (let the script wait for the program to start won't work i guess, cause then the script would restart after the program is restarted, right?) Thanks and Greetings, Elias
has answer: http://stackoverflow.com/a/50569124
downvote count: 0
has comment: http://stackoverflow.com/comment/88144273
type: Question
has comment: http://stackoverflow.com/comment/88143988
tagged with: raspberry-pi
score: 5
tagged with: raspberry-pi3
has comment: http://stackoverflow.com/comment/88144068
answer count: 2
tagged with: bash
has comment: http://stackoverflow.com/comment/88144138
has comment: http://stackoverflow.com/comment/88149974
has comment: http://stackoverflow.com/comment/88149169
favorite count: 0
tagged with: autostart
has comment: http://stackoverflow.com/comment/88144448
upvote count: 5
has answer: http://stackoverflow.com/a/50570440

http://stackoverflow.com/a/50690315
has body: Programs can't run when the computer is powered off. However, you can run a computer headlessly (without mouse, keyboard, and monitor) to save resources. Just ensure your program runs over the command line interface.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50690141

http://stackoverflow.com/comment/88200248
has text: yes, those answers are related to the `Entry` widget and you're using a `Text` widget. The point is to understand how events are processed, and that's the same for all widgets.
comment on: http://stackoverflow.com/q/50594802
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50668795
has title: Why does this python CGI script gives a white page?
answer count: 1
has body: I don't understand why this code gives me a white page in my browser. This is my script: # H8_webserver_cgi_run_v2.py # Before the server is running: # http://localhost:8080/H8_cgi/test-1.py from http.server import HTTPServer, CGIHTTPRequestHandler ## cgi_directories ## This defaults to ['/cgi-bin', '/htbin'] CGIHTTPRequestHandler.cgi_directories=['/H8_cgi'] port = 8080 httpd = HTTPServer(('127.0.0.1', port), CGIHTTPRequestHandler) print("Starting simple_httpd on port: " + str(httpd.server_port)) print("cgi-dirs: ",CGIHTTPRequestHandler.cgi_directories) print('try: http://localhost:8080/H8_cgi/test1.html') import webbrowser webbrowser.open_new_tab('http://localhost:8080/H8_cgi/test1.html') # First the browser, later the server. How can this possibly work? print('First the browser, later the server. How can this possibly work?') httpd.serve_forever() The HTML page to which it refers is: H8: Simpele CGI-demo Een formulier verwerken met CGI. Vul het formulier in. Uw geslacht Man Vrouw I love Python Ik kan Python dromen Ik ben een Pythonista Uw naam Uw auto(s) ----- Geen ---- Volvo Saab Opel Audi VW Anders All I got is a white browser page. And this is the feedback of the server: "C:\Users\Dell E6430\AppData\Local\Programs\Python\Python35\python.exe" "E:/Anton/Python scripts/H8_webserver_cgi_run_v2.py" Starting simple_httpd on port: 8080 cgi-dirs: ['/H8_cgi'] try: http://localhost:8080/H8_cgi/test1.html First the browser, later the server. How can this possibly work? 127.0.0.1 - - [03/Jun/2018 18:20:18] "GET /H8_cgi/test1.html HTTP/1.1" 200 - 127.0.0.1 - - [03/Jun/2018 18:20:18] command: E:\Anton\H8_cgi\test1.html "" ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 52021) Traceback (most recent call last): ---------------------------------------- File "C:\Users\Dell E6430\AppData\Local\Programs\Python\Python35\lib\socketserver.py", line 313, in _handle_request_noblock self.process_request(request, client_address…
has answer: http://stackoverflow.com/a/50833724
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: UnansweredQuestion
tagged with: cgi
type: Question
score: 0

http://stackoverflow.com/comment/130695685
type: AnswerComment
has text: Why do you need to use sudo?
type: Comment
comment on: http://stackoverflow.com/a/57325375
score: 0

http://stackoverflow.com/comment/88260152
has text: Thanks for replies.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50625027

http://stackoverflow.com/q/50550467
answer count: 2
has answer: http://stackoverflow.com/a/50550515
tagged with: python
has title: How can i see the content of a xml file in python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50550572
has body: I'm struggling to find a way of seeing the content of a xml file. I have done a lot of searching and the only progress I am making is to keep running my code without any results
type: Question
score: 0
has comment: http://stackoverflow.com/comment/88111851

http://stackoverflow.com/q/50662610
tagged with: pydub
has body: So I have written a very simple Python 3 program to take all of the .wav audio files in the working directory and convert them to .flac. Don't worry about any assumptions it makes (like the .wav files being valid, output filenames already existing, etc.). See below: import os from multiprocessing import Pool from pydub import AudioSegment def worker(filename): song = AudioSegment.from_wav(filename) song.export(filename.replace(".wav",".flac"), format = "flac") if __name__ == '__main__': converted_count = 0 convertlist = [] for filename in os.listdir(os.getcwd()): if filename.endswith(".wav"): convertlist.append(filename) converted_count += 1 p = Pool(processes=min(converted_count, os.cpu_count())) p.map(worker, convertlist) I've timed this and, on my system, have noticed a significant speedup as compared to using no multiprocessing at all. However, this almost seems too simple; I'm not very experienced with multiprocessing (nor multithreading), so I'm honestly not sure if there's a faster, more efficient way to do this. If you were tasked with writing this simple converter in Python, how would you do it? What would you do to make it more efficient than this?
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: audio
has title: Using Multiprocessing to Batch Convert .wav to .flac (Python, Pydub)
tagged with: multiprocessing
type: Question
upvote count: 4
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50663143
score: 4
has answer: http://stackoverflow.com/a/51846530

http://stackoverflow.com/q/50608309
downvote count: 0
linked to: http://stackoverflow.com/q/24656131
favorite count: 0
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/88226385
has title: Regex for matching adjacent words where order doesn't matter
has answer: http://stackoverflow.com/a/50610067
upvote count: 1
has body: I'm using regex with python and trying to figure out the best way to match a pattern where the order of two words I'm searching for doesn't matter, but they must be adjacent. So for example, I'm searching for either the phrase "fat cat lasagna co" or "cat fat lasagna co", and I have to imagine there's a better way than just r"\b(fat cat|cat fat) lasagna co\b" I read this question which addressed a similar problem but the words didn't have to be adjacent and couldn't figure out how to apply it to my problem.
type: AnsweredQuestion
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/50610067
answer count: 1

http://stackoverflow.com/q/50603658
score: 0
has comment: http://stackoverflow.com/comment/88221237
answer count: 1
has comment: http://stackoverflow.com/comment/88220776
has comment: http://stackoverflow.com/comment/88220895
has comment: http://stackoverflow.com/comment/88222617
has comment: http://stackoverflow.com/comment/88220825
tagged with: python
has comment: http://stackoverflow.com/comment/88220978
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50606425
tagged with: tk-toolkit
has comment: http://stackoverflow.com/comment/88220798
has comment: http://stackoverflow.com/comment/88221025
has title: i need assistants, a button should work 4 two possibilities from a combo box with specific lines but only really works for option 1
type: Question
has comment: http://stackoverflow.com/comment/88221853
has comment: http://stackoverflow.com/comment/88222410
has answer: http://stackoverflow.com/a/50606425
has comment: http://stackoverflow.com/comment/88220941
has comment: http://stackoverflow.com/comment/88220613
has body: I setup a button to work with two possibilities from a combo box so that if Event 1 is chosen it will save to lines 1 to 4 which works fine and saves with no problems but when Event 2 is chosen it should save 5 to 8 but it doesn't work correctly the 5 will place its self in corrected line but 6 will fly of like 10 lines down, i spent yesterday adding and removing code but no gold.any ideas? def saveteam(): with open("data/tournamentdatae1.txt",'r') as f: get_all=f.readlines() event = combo_event.get() if event == 'Event 1': with open("data/tournamentdatae1.txt",'r+') as f: for i,line in enumerate(get_all,1): if i == 1: input1 = team_1.get() f.writelines(input1) f.writelines("\n") for i,line in enumerate(get_all,1): if i == 2: input2 = team_2.get() f.writelines(input2) f.writelines("\n") for i,line in enumerate(get_all,1): if i == 3: input3 = team_3.get() f.writelines(input3) f.writelines("\n") for i,line in enumerate(get_all,1): if i == 4: input4 = team_4.get() f.writelines(input4) f.writelines("\n") if event == 'Event 2': with open("data/tournamentdatae1.txt",'r+') as f: for i,line in enumerate(get_all,1): if i == 5: input1 = team_1.get() f.writelines(input1) f.writelines("\n") else: f.writelines(line) for i,line in enumerate(get_all,1): if i == 6: input2 = team_2.get() f.writelines(input2) f.writelines("\n") else: f.writelines(line) this is what i do but not sure how to make show work with this if event == 'Event 1': if indivcombo == 'Individual 1': get_all[20] = individual.get() + "\n" if indivcombo == 'Individual 2': get_all[21] = individual.get() + "\n" if indivcombo == 'Individual 3': get_all[22] = individual.get() + "\n" if indivcombo == 'Individual 4': get_all[23] = individual.get() + "\n" if indivcombo == 'Individual 5': get_all[24] = individual.get() + "\n" if indivcombo == 'Individual 6': get_all[25] = individual.get() + "\n" if indivcombo == 'Individual 7': get_all[26] = individual.get() + "\n" if indivcombo == 'Individual 8': get_all[27] = individual.ge…
has comment: http://stackoverflow.com/comment/88220138
tagged with: python-3.4

http://stackoverflow.com/a/70109368
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50659044
upvote count: 2
has body: I do : "Run > Configuration per file > Execute in an external system terminal", then when you run your .py containing the app.run, it will be launched in an external console. If you close the console the server will be closed too.
downvote count: 0

http://stackoverflow.com/comment/88240434
has text: `from datetime import timezone` is valid in python3 but not python2. I'm not sure what the replacement is.
type: Comment
comment on: http://stackoverflow.com/q/50615133
type: QuestionComment
score: 1

http://stackoverflow.com/a/50642067
accepted answer of: http://stackoverflow.com/q/50639576
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50639576
has comment: http://stackoverflow.com/comment/88374391
type: Answer
downvote count: 0
score: 1
has body: ASG = asObj.describe_auto_scaling_groups(AutoScalingGroupNames=[event['targetASG']]) I think targetASG is not part of the SNS event.. SNS Events look like this: { "Records": [ { "EventVersion": "1.0", "EventSubscriptionArn": "arn:aws:sns:EXAMPLE", "EventSource": "aws:sns", "Sns": { "SignatureVersion": "1", "Timestamp": "1970-01-01T00:00:00.000Z", "Signature": "EXAMPLE", "SigningCertUrl": "EXAMPLE", "MessageId": "95df01b4-ee98-5cb9-9903-4c221d41eb5e", "Message": "Hello from SNS!", "MessageAttributes": { "Test": { "Type": "String", "Value": "TestString" }, "TestBinary": { "Type": "Binary", "Value": "TestBinary" } }, "Type": "Notification", "UnsubscribeUrl": "EXAMPLE", "TopicArn": "arn:aws:sns:EXAMPLE", "Subject": "TestInvoke" } } ] } You should grab the message and parse the targetASG value from there like e.g. import json [...] targetASG = event[‘Records’][0][‘Sns’][‘Message’] myMessage = json.loads(targetASG) name = myMessage['targetASG'] ASG = asObj.describe_auto_scaling_groups(AutoScalingGroupNames=[name]) [...]

http://stackoverflow.com/q/50553268
downvote count: 3
has comment: http://stackoverflow.com/comment/88117289
type: Question
upvote count: 0
has title: invalid syntax in the secondary line in the semicolon : E4_Email
has body: when i'm ruining programs compiler :told me invalid syntax in the secondary line in the semicolon : E4_Email save (): lgin_pass_email_contactnumber_save={} lgin_pass_email_contactnumber_save[ E1_full_name: E2_password: E3_re-password : E4_Email :E5_contact_number .get()]=E1_full_name, E2_password,E4_Email,E5_contact_number.get f=open("E1","wb") pickle.dump(gin_pass_email_contactnumber_save,f) f.close login()
answer count: 1
has answer: http://stackoverflow.com/a/50555288
favorite count: 0
type: UnansweredQuestion
score: -3
tagged with: python

http://stackoverflow.com/comment/88145697
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50567528
type: Comment
has text: Replacing methods (or adding new ones) on a per-instance basis is indeed rarer but it's sometimes the best solution and definitly not "very bad practice". OTHO, there's a strong naming convention about ALL_UPPER names denoting (pseudo) constants so rebinding `self.BAR` _is_ bad practice. Oh and yes: you're aware that methods are not the only descriptors ? Would you write `type(self).x.__get__(self, type(self))` to access a property ? I've been reading Python code for 19+ years now and I've only seen `type(self).attrname` used instead of `self.attrname` for a couple corner cases.

http://stackoverflow.com/q/50679638
has comment: http://stackoverflow.com/comment/88368812
answer count: 1
favorite count: 0
tagged with: aggregate
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88368865
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88371262
score: 1
has answer: http://stackoverflow.com/a/50679723
accepted answer: http://stackoverflow.com/a/50679723
type: Question
downvote count: 0
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88369024
has body: From a csv file having the following format: Date,Data 01-01-01,111 02-02-02,222 03-03-03,333 I am calculating the monthly average of the values using the following code: data = pd.read_csv("input.csv") data['Month'] = pd.DatetimeIndex(data.reset_index()['Date']).month mean_data = data.groupby('Month').mean() Then I output a csv file using the following command: mean_data.to_csv("test.csv") It works fine and give me the following output: Month,Data 01,01 02,02 03,03 04,04 ... But now I would like to know how many data have been included inside the monthly average calculation. For that I changed: mean_data = data.groupby('Month').mean() by: mean_data = data.groupby(['Month']).agg(['mean', 'count']) But the problem comes now. When I want to output the csv , I now have a weird format as follow: Data,Data, mean,count, Month, 01, 01,8, 02, 02,9, 03, 03,7, 04, 04,5, Which is not really convenient. Instead I would like to have the following output: Month,Mean,Count 01,01,8 02,02,9 03,03,7 04,04,5 Does anyone know how to achieve that?
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has title: Python - data.to_csv output format

http://stackoverflow.com/comment/102076506
score: 0
type: Comment
type: QuestionComment
has text: I've ported the above code to Python 3 and I've run it using 32-bits Python 3.6.5 without errors.
comment on: http://stackoverflow.com/q/50629277

http://stackoverflow.com/comment/88547625
comment on: http://stackoverflow.com/a/50684963
score: 0
type: AnswerComment
type: Comment
has text: @Ajax1234 Yes it is. That is actually my second issue (converting the string to float). When I did convert it I am getting 'TypeError: 'float' object is not iterable' when using: for value in BWLinkNames[key]: If I can somehow convert it to float then writing float to excel would eliminate my first problem. But it isnt allowing me. Does python allow me to iterate float value from dictionary?

http://stackoverflow.com/a/50610634
answers question: http://stackoverflow.com/q/50610593
has body: You need to use the pip command in a terminal or cmd instead of the Python prompt. Open a terminal or command prompt and just type pip3 install numpy
type: Answer
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50610593

http://stackoverflow.com/a/50637466
has comment: http://stackoverflow.com/comment/88285786
accepted answer of: http://stackoverflow.com/q/50637420
type: Answer
has comment: http://stackoverflow.com/comment/88285724
has body: I believe need: df = pd.concat([df1, df2]).drop_duplicates(subset=['ID'], keep='last').sort_values('ID') print (df) ID A 0 ID1 5 1 ID2 1 2 ID3 8 3 ID4 8 3 ID5 7 4 ID6 8 5 ID7 9 Explanation: First concat both DataFrame together: print (pd.concat([df1, df2])) ID A 0 ID1 5 1 ID2 6 2 ID3 7 3 ID4 8 0 ID1 5 1 ID2 1 2 ID3 8 3 ID5 7 4 ID6 8 5 ID7 9 Because same ID are created, remove duplicates by drop_duplicates with keep only last value: print (pd.concat([df1, df2]).drop_duplicates(subset=['ID'], keep='last')) ID A 3 ID4 8 0 ID1 5 1 ID2 1 2 ID3 8 3 ID5 7 4 ID6 8 5 ID7 9 And last sort by ID by sort_values.
has comment: http://stackoverflow.com/comment/88285201
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50637420

http://stackoverflow.com/q/50627930
has title: compile python executable to work outside of main python directory
type: Question
tagged with: visual-c++
score: 0
answer count: 1
tagged with: packaging
type: UnansweredQuestion
tagged with: windows
tagged with: python
has body: I am working on packaging and distributing some python applications in Windows by wrapping together a python runtime, the python packages for the applications, and some executables to run the python applications. The approach is just to modify the source for python.exe to launch the applications but accept command line arguments for things like data file names. Below is an example C++ source for one of the executables: // source for my_python_application1 #include "stdafx.h" #include "Windows.h" #include "Python.h" wchar_t SWITCH[] = L"-m"; wchar_t APP[] = L"my_python_application1.main"; int wmain(int argc, wchar_t **argv) { int newargc; newargc = argc + 2; // can use this to modify the PythonPath for specific distributions // _putenv("PYTHONPATH=\"\""); wchar_t **newargv = new wchar_t*[newargc]; newargv[0] = argv[0]; newargv[1] = SWITCH; newargv[2] = APP; for (int i = 1; i &lt; argc; i++) { newargv[i + 2] = argv[i]; } return Py_Main(newargc, newargv); // return Py_Main(argc, argv); } Functionally this achieves everything I need it to achieve, but I suffer from a certain OCD nature which leads me to want things organized in a certain way. I'd like to have a structure like the following /application_suite /python_runtime python.exe python36.dll (and everything else in a python dir) /python_applications my_python_application1.exe my_python_application2.exe However, since mypythonapplication1/2.exe are basically modified python.exe files, in order for them to work properly (load the python dll, import modules, access all of the landmarking features necessary for modules to be interconnected) they need to be located in the /python_runtime directory. I'm wondering is there a way to compile these executables so that they can be arranged in the directory structure that I presented, but know that they python_runtime directory and all of its structure are located in a relative path of './python_runtime' or whatever so that this all behaves well no matter where the distributi…
has answer: http://stackoverflow.com/a/50632115

http://stackoverflow.com/q/50559539
has comment: http://stackoverflow.com/comment/88129652
has title: import a file from another location - python
has comment: http://stackoverflow.com/comment/88129669
type: Question
tagged with: python-2.7
score: 0
tagged with: python-import
has answer: http://stackoverflow.com/a/50559583
answer count: 3
has comment: http://stackoverflow.com/comment/88129802
has answer: http://stackoverflow.com/a/50559799
possible better answer: http://stackoverflow.com/a/50560426
has comment: http://stackoverflow.com/comment/88129698
has answer: http://stackoverflow.com/a/50560426
tagged with: python
tagged with: module
has comment: http://stackoverflow.com/comment/88129889
has body: There are two folders , each contain a python file . For example: first_folder contains a.py &amp; second_folder contains b.py I tried importing b.py in a.py But i got not Import error. ImportError: No module named b Pls help me to solve this. I also tried creating a blank init.py in both folders, but it did not worked. Folder structure: /home/user/scripts/ | |--------python_scripts | | | | | |------- a.py | |--------lib | |-------b.py
accepted answer: http://stackoverflow.com/a/50559799
has comment: http://stackoverflow.com/comment/88129708
type: AnsweredQuestion

http://stackoverflow.com/comment/88389283
has text: @root The question only hints at numeric data being compared though, but I get your point. If OP wants to cover every single case they should probably import assert_series_equal from pandas.testing and reset the index.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50689768

http://stackoverflow.com/comment/88336231
has text: This approach only works for the 'End station', and 'Duration' is missing. The expected output is, 'Start station' and 'End station' into one column 'station', and keep 'Duration' accordingly.
type: Comment
comment on: http://stackoverflow.com/a/50662912
type: AnswerComment
score: 0

http://stackoverflow.com/q/50582966
tagged with: excel
has answer: http://stackoverflow.com/a/50583085
type: AnsweredQuestion
has body: I have a table that needs to be split into multiple files grouped by values in column 1 - serial. +--------+--------+-------+ | serial | name | price | +--------+--------+-------+ | 100-a | rdl | 123 | | 100-b | gm1 | -120 | | 100-b | gm1 | 123 | | 180r | xxom | 12 | | 182d | data11 | 11.50 | +--------+--------+-------+ the output would be like this: 100-a.xls 100-b.xls 180r.xls etc.etc. and opening 100-b.xls cotains this: +--------+------+-------+ | serial | name | price | +--------+------+-------+ | 100-b | gm1 | -120 | | 100-b | gm1 | 123 | +--------+------+-------+ I tried using Pandas to define the dataframe by using this code: import pandas as pd #from itertools import groupby df = pd.read_excel('myExcelFile.xlsx') I was successful in getting the data frame, but i have no idea what to do next. I tried following this similar question on Stackoverflow, but the scenario is a bit different. What is the next approach to this?
accepted answer: http://stackoverflow.com/a/50583085
type: Question
score: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/35997013
answer count: 1
has title: python: how to split excel files grouped by first column
tagged with: python

http://stackoverflow.com/comment/88336641
type: Comment
type: AnswerComment
has text: Lot of functions introduced that I wasn't aware of like window.mode(). Thank you so much @cdlane
comment on: http://stackoverflow.com/a/50663269
score: 0

http://stackoverflow.com/comment/93670794
type: Comment
comment on: http://stackoverflow.com/a/53397484
type: AnswerComment
score: 0
has text: Could you elaborate on your answer? It's not clear what you mean simply from this

http://stackoverflow.com/comment/88100192
comment on: http://stackoverflow.com/q/50543696
score: 0
has text: In the code, as it is, all of these are undefined variables: `time`, `nameofhost`, `hostsname`, `message`, `clients_input`, `IP`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50631622
has body: I would like to display a map of US DMAs (geographical area similar to county/state, based on advertising considerations) with some data binding for the color (which I managed to do) AND labels for the DMA number (each DMA has a 3 digit code associated with it). My Code is as follows so far import pandas as pd import matplotlib.pyplot as plt import vincent as vi vi.core.initialize_notebook() df = pd.read_csv('data.csv', sep=',') geo_data = [{'name': 'dma', 'url': r'https://raw.githubusercontent.com/simzou/nielsen-dma/master/nielsentopo.json', 'feature': "nielsen_dma"} ] vis = vi.Map(data = df, geo_data=geo_data, projection='albersUsa', data_bind='numberDMA', data_key='dma', map_key={'dma': 'properties.dma'}) vis.to_json('vega.json', html_out=True, html_path=map.html')
score: 0
tagged with: visualization
tagged with: vincent
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88273253
answer count: 0
has comment: http://stackoverflow.com/comment/88311419
type: Question
has title: Vincent Python Map with Text Labels

http://stackoverflow.com/comment/88367691
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50678927
has text: @AzatIbrakov what mistake in this makes awful??

http://stackoverflow.com/comment/88229086
type: Comment
has text: That is not an answer, it should be a comment that indicates that you have tested the code in PySide and you have not had any problem. Why is not it an answer ?, because it does not help to solve the problem, just check that the code that shows the asker is correct so probably the error is in another part of the asker code that has not yet shown.
comment on: http://stackoverflow.com/a/50609248
type: AnswerComment
score: 0

http://stackoverflow.com/a/50605256
upvote count: 1
has body: You need to open your terminal and type pip and press the TAB key. The pip versions available on your sandbox shall be listed. Use pip3 to install the packages you require. The way to do so remains the same pip3 install "packageName". This would make the package available with the Python3 installation you wish to use in Zeppelin.
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88220298
type: Answer
answers question: http://stackoverflow.com/q/50603891
accepted answer of: http://stackoverflow.com/q/50603891

http://stackoverflow.com/q/50675459
has body: #!/usr/bin/python3 import cv2 cam=cv2.VideoCapture(0) checking if camera is working!! cam.isOpened(): print("Working") while(cam.isOpened()): status,frame=cam.read() cv2.imshow('camera1',frame) if cv2.waitKey(1) &amp; 0xFF==ord('q') : break Removing windows by calling below function If i dont write this function then also it will run properly!! cv2.destroyAllWindows() cam.release()
has comment: http://stackoverflow.com/comment/88360752
score: 5
has title: What is the use of function destroyAllWindows() if the window automatically gets destroyed using waitKey() function?
answer count: 1
favorite count: 0
tagged with: python
tagged with: computer-vision
upvote count: 6
has comment: http://stackoverflow.com/comment/88421953
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88360716
downvote count: 1
has answer: http://stackoverflow.com/a/72885032
type: Question
tagged with: opencv

http://stackoverflow.com/a/50613463
has comment: http://stackoverflow.com/comment/88268666
score: 0
has comment: http://stackoverflow.com/comment/88277279
answers question: http://stackoverflow.com/q/50611955
type: Answer
has comment: http://stackoverflow.com/comment/88242529
has body: I have tried your code and it works fine so you may want to check if you are rendering the right HTML files maybe, i've changed your code to make sure it's working and it is my_dict1={'temp_k' :json_object['wind']['speed']} sorry but I cant write a comment yet!
has comment: http://stackoverflow.com/comment/88253468

http://stackoverflow.com/a/50587752
has comment: http://stackoverflow.com/comment/88185319
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50587249
accepted answer of: http://stackoverflow.com/q/50587249
has body: Your user_directory_path function doesn't return anything (or, more exactly, it's dioesn't explicitely return anything so it implicitely returns None). It has to return the full file path (relative to your settings.MEDIA_ROOT) including the filename: upload_to may also be a callable, such as a function. This will be called to obtain the upload path, including the filename. This callable must accept two arguments and return a Unix-style path (with forward slashes) to be passed along to the storage system https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.FileField.upload_to
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50682487
upvote count: 1
tagged with: tensorflow
type: Question
score: 1
has body: I'm trying to build a recurrent neural network, the inputs are from mnist database, so they are 28x28 pixels images. Here is my network model: def _pre_activation(self, input_values, layer): return tf.add(tf.matmul(input_values, layer['weights']), layer['biases']) def network_model(self, x): layer = {'weights':tf.Variable(tf.random_normal([self.rnn_size, self.nb_of_outputs])), 'biases': tf.Variable(tf.random_normal([self.nb_of_outputs]))} x = tf.transpose(x, [1,0,2]) x = tf.reshape(x, [-1, self.chunk_size]) x = tf.split(x, self.nb_of_chunks, 0) lstm_cell = rnn.BasicLSTMCell(self.rnn_size) lstm_outputs, states = rnn.static_rnn(lstm_cell, x_splitted, dtype=tf.float32) output = self._pre_activation(lstm_outputs, layer) return output I get the following error: Shape must be rank 2 but is rank 3 for 'MatMul' (op: 'MatMul') with input shapes: [28,1,128], [128,10]. My problem is, from a tensor of shape (28, 28), tf.split outputs a list of 28 arrays of shape (1,28), but I want 28 arrays of shape (28, ). I tried to iterate it to a new list and reshaping each array one by one, but the problem is no session is running at this moment, and no value exist in those tensors. I didn't found any useful help on the internet, probably because that I don't know how to formulate my problem.
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: tf.split outputs tensors with a useless dimension
answer count: 0

http://stackoverflow.com/comment/88213292
comment on: http://stackoverflow.com/q/50598070
score: 0
has text: The spaCy installation definitely looks successful and it sounds like you did everything correctly here. Could you post the actual code you're running as part of your API, e.g. what's done in `proc.py`? That's likely where the problem is.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88335792
type: QuestionComment
has text: @wwii, I have checked, there always will be a NaN for either. 'Start station' or 'End station' . But not both.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50662613

http://stackoverflow.com/a/50560025
score: 0
has body: Error occur because you had define room_path variable in method and access and used room_path variable outside the method. def room(): room_path=["1","2"] user_choice = "" print ("If you decide to ditch Todd and go to the campfire alone, enter 1") print ("If you decide to drag Todd with you to the campfire, enter 2") user_choice = input("your option number") if user_choice == room_path [1]: print ("yes") elif user_choice == room_path [2]: print ("no")
type: Answer
answers question: http://stackoverflow.com/q/50557518

http://stackoverflow.com/comment/88316208
type: QuestionComment
score: 1
has text: `self` is passed implicitly when you call an instance method on an instance.
comment on: http://stackoverflow.com/q/50652766
type: Comment

http://stackoverflow.com/q/50664485
tagged with: python
has title: Train CNN model with multiple folders and sub-folders
has answer: http://stackoverflow.com/a/65791594
tagged with: tensorflow
has body: I am developing a convolution neural network (CNN) model to predict whether a patient in category 1,2,3 or 4. I use Keras on top of TensorFlow. I have 64 breast cancer patient data, classified into four category (1=no disease, 2= …., 3=….., 4=progressive disease). In each patient's data, I have 3 set of MRI scan images taken at different dates and inside each MRI folder, I have 7 to 8 sub folders containing MRI images in different plane (such as coronal plane/sagittal plane etc). I learned how to deal with basic “Cat-Dog-CNN-Classifier”, it was easy as I put all the cat &amp; dog images into a single folder to train the network. But how do I tackle the problem in my breast cancer patient data? It has multiple folders and sub-solders. Please suggest.
type: Question
has answer: http://stackoverflow.com/a/50665238
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/55304529
tagged with: keras
type: UnansweredQuestion

http://stackoverflow.com/comment/88185268
has text: I think the issue was the usage of Convolution2D instead of Conv2D, when i changed it worked properly. Convolution2D does not do what i want even if you have filter_size =(2, 2).
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50587110

http://stackoverflow.com/a/50690230
answers question: http://stackoverflow.com/q/50673439
upvote count: 1
type: Answer
has body: Problem The Kivy App is not switching screen because there are two instances of ScreenSwitcher. One instance was instantiated in the kv file by ScreenSwitcher:. The second instance was instantiated in the Python script by manager = ScreenSwitcher(). The button's on_press event was referencing the second instance of ScreenSwitcher. Solution store.py Add from kivy.properties import ObjectProperty. Replace manager = ScreenSwitcher() with manager = ObjectProperty(None) class MainScreen(GridLayout): manager = ObjectProperty(None) store.kv Add manager: manager after &lt;MainScreen&gt;:. This is to hook-up ObjectProperty to ScreenSwitcher's id. Add id: manager after ScreenSwitcher: &lt;MainScreen&gt;: manager: manager rows: 2 size_hint: 1, 1 ... ScreenSwitcher: id: manager Please refer to the example and output for details. Example store.py from kivy.app import App from kivy.uix.screenmanager import Screen from kivy.uix.gridlayout import GridLayout from kivy.properties import ObjectProperty class ScreenOne(Screen): pass class ScreenTwo(Screen): pass class MainScreen(GridLayout): manager = ObjectProperty(None) class StoreApp(App): def build(self): return MainScreen() if __name__ == "__main__": StoreApp().run() store.kv #:kivy 1.10.1 &lt;ToolBar@BoxLayout&gt;: size_hint_y: None height: 35 pos_hint: {'top': 1, 'y': 0} padding: 5,2,5,2 spacing: 5 canvas: Color: rgba: .7, 1, .7, 1 Rectangle: pos: self.pos size: self.size &lt;ToolButton@Button&gt;: color: 0,0,0,1 align: 'center' &lt;ScreenOne&gt;: Label: text: 'SCREEN ONE' font_size:50 &lt;ScreenTwo&gt;: Label: text: 'SCREEN TWO' font_size:50 &lt;MainScreen&gt;: manager: manager rows: 2 size_hint: 1, 1 ToolBar: ToolButton: text: 'Screen one' on_press: root.manager.current = 'sone' ToolButton: text: 'Screen two' on_press: root.manager.current = 'stwo' ScreenSwitcher: id: manager Output
downvote count: 0
score: 1

http://stackoverflow.com/comment/88243973
comment on: http://stackoverflow.com/a/50605609
type: AnswerComment
has text: thank you! I finally discovered this: wmic os get 'OperatingSystemSKU /value', it gives me a number instead of text, which solved my problem
score: 0
type: Comment

http://stackoverflow.com/q/50691616
has title: How do I use GeneratorExit?
tagged with: python
has comment: http://stackoverflow.com/comment/88393959
tagged with: generator
score: 2
type: AnsweredQuestion
upvote count: 3
downvote count: 1
has comment: http://stackoverflow.com/comment/88393096
type: Question
has answer: http://stackoverflow.com/a/50692325
tagged with: iterator
has comment: http://stackoverflow.com/comment/88393043
has comment: http://stackoverflow.com/comment/88393136
has comment: http://stackoverflow.com/comment/88393069
answer count: 3
has body: I have the following mcve: import logging class MyGenIt(object): def __init__(self, name, content): self.name = name self.content = content def __iter__(self): with self: for o in self.content: yield o def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): if exc_type: logging.error("Aborted %s", self, exc_info=(exc_type, exc_value, traceback)) And here is sample use: for x in MyGenIt("foo",range(10)): if x == 5: raise ValueError("got 5") I would like logging.error to report the ValueError, but instead it reports GeneratorExit: ERROR:root:Aborted &lt;__main__.MyGenIt object at 0x10ca8e350&gt; Traceback (most recent call last): File "&lt;stdin&gt;", line 8, in __iter__ GeneratorExit When I catch GeneratorExit in __iter__: def __iter__(self): with self: try: for o in self.content: yield o except GeneratorExit: return nothing is logged (of course) because __exit__ is called with exc_type=None. Why do I see GeneratorExit instead of ValueError in __exit__? What do I do to get the desired behavior, i.e., ValueError in __exit__?
linked to: http://stackoverflow.com/q/44598548
accepted answer: http://stackoverflow.com/a/50692325
possible better answer: http://stackoverflow.com/a/50692136
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50692136
has answer: http://stackoverflow.com/a/50692103

http://stackoverflow.com/q/50632046
downvote count: 0
tagged with: boto3
score: 4
has body: I have this script: #!/usr/bin/env python3 import boto3 import argparse import time ec2 = boto3.resource('ec2') dstamp = time.strftime("_%m-%d-%Y-0") parser = argparse.ArgumentParser(description='Create Image(AMI) from Instance tag:Name Value') parser.add_argument('names', nargs='+', type=str.upper, help='instance name or list of names to create images from') args = parser.parse_args() # List Source Instances for Image/Tag Creation for instance in ec2.instances.all(): # Pull Name tags from source instances for name in instance.tags: if name["Key"] == 'Name': instancename = name["Value"] # Check for Name Tag Match with args for iname in args.names: if iname == instancename: # Create an image if we have a match image = instance.create_image( Description=f"Created from Source: {instance.id} Name: {instancename}", Name=instancename + dstamp, NoReboot=True) print('New: {} from instance.id: {} {}'.format(image.id, instance.id, instancename)) # ---------------------------------------------- # Can't copy tags from src instance - cause of auto-generated by Cloudformation Tags # error I got: "Tag keys starting with 'aws:' are reserved for internal use" # So we skip any tag [Key] named 'aws:' # ---------------------------------------------- for tag in instance.tags: dst_tags = [] if tag['Key'].startswith('aws:'): print("Skip tag that starts with 'aws:' " + tag['Key']) else: dst_tags.append(tag) print(' Tags:', dst_tags) image.create_tags(Tags=dst_tags) This is working perfectly, but the final function I am missing is to apply the tags to the underlying volume snapshots within the newly created image. Do I have to totally switch to client = boto3.client('ec2') in order to tag my volume snapshots? To put it another way - how are people who are using images for backup tagging their volume snapshots? I have been working with boto3 and python 3 for all of 3 weeks along with my regular duties, any help would be appreciated.
favorite count: 0
tagged with: python-3.x
has title: Using Boto3 (resource method) to create image - can't add tags to snapshots?
answer count: 0
type: UnansweredQuestion
tagged with: python
type: Question
upvote count: 4
tagged with: amazon-ec2

http://stackoverflow.com/comment/88345980
comment on: http://stackoverflow.com/q/50667057
type: QuestionComment
has text: for i in nums: here "i" does not contain the index value, "i" contains list items value. "in" operator iterates over items, not indices. let input is [1,1,2,1,1,1,1,2,3]. In the first iteration, i=1,i+1=2,i+2=3 so, nums[1]=1 nums[2]=2 nums[3]=1 . . . . . In the last iteration, again,i=1,i+1=2,i+2=3 and again you're accessing nums[1],nums[2] and nums[3]! But you expected to check nums[6],nums[7],nums[8]. Every time when i=1 you are accessing the indices 1,2 and 3.That's why you're getting this error. In the second function you're accessing the index values,so it's working.
score: 0
type: Comment

http://stackoverflow.com/q/50669231
tagged with: sqlalchemy
has title: SQLAlchemy sessions keep dropping after a few minutes
upvote count: 1
tagged with: flask
favorite count: 0
tagged with: postgresql
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88354956
linked to: http://stackoverflow.com/q/14343740
has comment: http://stackoverflow.com/comment/88352805
tagged with: python
has body: I am writing a Flask API that needs to communicate with many datastores, Postgres on AWS RDS being one of them. I want to avoid Flask-SQLAlchemy (trying to reduce package dependence), and given that my use case is pretty simple, I think the standard SQLAlchemy library should suffice. This is my models.py file: class DriverPostgres: def __init__(self): self.connector = PostgresCredentials() self.connection_str = 'postgresql+psycopg2://{}:{}@{}/{}'.format(...) self.engine = create_engine(self.connection_str) self.Session = scoped_session( sessionmaker(autocommit=False, autoflush=True, bind=self.engine)) Base.metadata.create_all(bind=self.engine) def get_user_by_email(self, email): session = self.Session() result = session.query(User).filter_by(email=email).first() self.Session.remove() return result def register_user(self, ...): user = User(...) session = self.Session() session.add(user) try: session.commit() except IntegrityError: return False finally: self.Session.remove() return True In my Flask app server.py file, I import DriverPostgres at the top of the app and instantiate driver_postgres = DriverPostgres(), and when handling requests I make calls like driver_postgres.get_user_by_email(). This logic works perfectly when the app is first loaded. I can send as many requests through as I want with no issues. However, if I wait for a few minutes and hit the app again, I get the following error: Traceback (most recent call last): File "/Users/user/.virtualenvs/demo/lib/python3.6/site-packages/flask/app.py", line 2309, in __call__ return self.wsgi_app(environ, start_response) File "/Users/user/.virtualenvs/demo/lib/python3.6/site-packages/flask/app.py", line 2295, in wsgi_app response = self.handle_exception(e) File "/Users/user/.virtualenvs/demo/lib/python3.6/site-packages/flask_cors/extension.py", line 161, in wrapped_function return cors_after_request(app.make_response(f(*args, **kwargs))) File "/Users/user/.virtualenvs/demo/lib/python3.6/site-packages/flask/app.py…
downvote count: 0
answer count: 0
score: 1
type: Question

http://stackoverflow.com/comment/88205174
type: AnswerComment
type: Comment
has text: @kodeturtle looks like you missed `enctype="multipart/form-data"` check updates.
comment on: http://stackoverflow.com/a/50597940
score: 0

pykafka
tag name: pykafka
tags question: http://stackoverflow.com/q/50573918
type: Tag

http://stackoverflow.com/comment/88323933
comment on: http://stackoverflow.com/a/50656587
type: Comment
has text: @adampicker As stated in my answer, the field is not properly defined. Check my edit above.
score: 0
type: AnswerComment

http://stackoverflow.com/q/50638837
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88289226
has title: Django database authentication plugin error
tagged with: mysql
type: Question
has comment: http://stackoverflow.com/comment/88287771
score: 0
has comment: http://stackoverflow.com/comment/88287970
answer count: 1
has answer: http://stackoverflow.com/a/68387820
has body: I had a Django project that I had worked on in the past for quite a while. Recently, I tried to reopen it and add some minor changes. What happened is that recently I also reinstalled MySQL(8.0) and of course, recreated my old database. But now when I tried to run the server or any other operation, I get the following error: 2059, "Authentication plugin 'caching_sha2_password' cannot be loaded: The specified module could not be found. I tried the solution from other post, but it did not work for me. Here is also a full traceback of the error: https://pastebin.com/JqexqTtC
linked to: http://stackoverflow.com/q/50169576
has comment: http://stackoverflow.com/comment/88288001
type: UnansweredQuestion

http://stackoverflow.com/q/50598752
has comment: http://stackoverflow.com/comment/88206805
has body: I have been having issues with running my code as a problem occurs in this section of code within my program. Every time I attempt to 'keep' or 'change' the case, the program simply outputs a blank line. I prefer to only provide this section of my program, as I feel this is the root of the issue. if (len(remainderCases) == finalRoundRemainder): print("Only 2 cases left - the case you chose at the beginning of the game, Case #" + str(user) + ",") print("and Case #" + str(remainderCases[0]) + ". The result will be your winnings.") keepOrChange = input("Would you like to 'keep' or 'change' your case: ") while (keepOrChange != "keep") and (keepOrChange != "change"): keepOrChange = input("The value '" + str(keepOrChange) + "' is invalid. Would you like to keep or change your case (enter 'keep' or 'change'): ") if (keepOrChange == "keep"): print(userValue) else: print(remainder) else: print("") print("Next case!")
upvote count: 0
answer count: 1
has title: Incorrect output with 'while' and variables, in Python game
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 2
type: Question
score: -2
has comment: http://stackoverflow.com/comment/88208319
has answer: http://stackoverflow.com/a/50599343
accepted answer: http://stackoverflow.com/a/50599343

http://stackoverflow.com/a/50655848
upvote count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88327692
answers question: http://stackoverflow.com/q/50653035
has comment: http://stackoverflow.com/comment/88333652
has body: Use advanced indexing together with np.ix_: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; &gt;&gt;&gt; X = np.array( ([[0. , 2.8, 3.5, 0. , 2.5, 1. , 0.8], ... [0. , 0. , 0. , 0. , 0. , 0. , 0. ], ... [3.5, 2.5, 0. , 0. , 2.8, 1.3, 1.1], ... [3.6, 3.8, 3.3, 0. , 2.5, 0.6, 0.4], ... [2.5, 1.5, 2.8, 0. , 0. , 3.1, 1.9], ... [1. , 0.8, 1.3, 0. , 3.1, 0. , 2.8], ... [0.8, 1.6, 1.1, 0. , 1.9, 2.8, 0. ]])) &gt;&gt;&gt; &gt;&gt;&gt; row = 1; col = 3 &gt;&gt;&gt; h, w = X.shape &gt;&gt;&gt; i = np.r_[row, :row, row+1:h] &gt;&gt;&gt; j = np.r_[:col, col+1:w] &gt;&gt;&gt; X[np.ix_(i, j)] array([[0. , 0. , 0. , 0. , 0. , 0. ], [0. , 2.8, 3.5, 2.5, 1. , 0.8], [3.5, 2.5, 0. , 2.8, 1.3, 1.1], [3.6, 3.8, 3.3, 2.5, 0.6, 0.4], [2.5, 1.5, 2.8, 0. , 3.1, 1.9], [1. , 0.8, 1.3, 3.1, 0. , 2.8], [0.8, 1.6, 1.1, 1.9, 2.8, 0. ]])
type: Answer

sensors
type: Tag
tag name: sensors
tags question: http://stackoverflow.com/q/50602212
tags question: http://stackoverflow.com/q/50694190

http://stackoverflow.com/a/50648124
downvote count: 0
answers question: http://stackoverflow.com/q/50645204
has comment: http://stackoverflow.com/comment/88309715
type: Answer
has body: How about sorting the output using a natural sort: import re _nsre = re.compile(r'(\d+)') def natural_sort_key(s): return [int(text) if text.isdigit() else text.lower() for text in re.split(_nsre, s)] s = "1 10 2 100 101 102 103 104 105 106 107 108 109 11 110 111 112 113 114 115 116 117 118 119 12 120 121 122 123 124 125 126 127 128 129 13 130 131 132 133 134 135 136 137 138 139 14 140 141 142 143 144 145 146 147 148 149 15 150 151 152 153 154 155 156 157 158 159 16 17 18 19 20 200c 21 22 23 24 25 26 260 261 262 263 264 265fs 266fs 267c 268c 269c 27 273c 274c 275c 276c 28 29 2c 30 302 31 32c 33c 34 35c 36 37 38 3c 4 5 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 524 6 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 7 701 702 703 704 705 706 707 708 709 710 8 801 802 803 804 805 806 807 808 809 810 9 901 902 S1 S10 S11 S12 S13 S14 S15 S16 S17 S18 S19 S2 S20 S3 S4 S5 S6 S7 S8 S9" list1 = s.split(' ') list1.sort(key=natural_sort_key) Output list1: ['1', '2', '2c', '3c', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32c', '33c', '34', '35c', '36', '37', '38', '100', '101', '102', '103', '104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129', '130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '140', '141', '142', '143', '144', '145', '146', '147', '148', '149', '150', '151', '152', '153', '154', '155', '156', '157', '158', '159', '200c', '260', '261', '262', '263', '264', '265fs', '266fs', '267c', '268c', '269c', '273c', '274c', '275c', '276c', '302', '501', '502', '503', '504', '505', '506', '507', '508', '509', '510', '511', '512', '513', '514', '515', '516', '517', '518', '519', '520', '521', '522', '524', '601', '602', '603'…
score: 1
upvote count: 1

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/50674086
tags question: http://stackoverflow.com/q/50621605
tags question: http://stackoverflow.com/q/50560862
tags question: http://stackoverflow.com/q/50675058
tags question: http://stackoverflow.com/q/50563994
tags question: http://stackoverflow.com/q/50692842
tags question: http://stackoverflow.com/q/50569345
tags question: http://stackoverflow.com/q/50617233
tags question: http://stackoverflow.com/q/50637603
type: Tag

http://stackoverflow.com/q/50608207
answer count: 1
score: -7
favorite count: 0
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/312443
has body: l = [1,2,3,4,5,6,7,8,9,10] I have a list and I need to print 5 elements per line to get: 1 2 3 4 5 6 7 8 9 10 I tried everything but I'm stuck, help!
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88226144
has comment: http://stackoverflow.com/comment/88226827
downvote count: 7
type: Question
has answer: http://stackoverflow.com/a/50608354
has title: Print 5 elements of a list per line
linked to: http://stackoverflow.com/q/312443
upvote count: 0

http://stackoverflow.com/comment/88383278
comment on: http://stackoverflow.com/q/50686608
score: 0
type: Comment
type: QuestionComment
has text: @martineau When I posted my comment there isn't any space. https://stackoverflow.com/posts/50686608/revisions

http://stackoverflow.com/q/50555102
possible better answer: http://stackoverflow.com/a/50555602
answer count: 2
has answer: http://stackoverflow.com/a/50555602
linked to: http://stackoverflow.com/q/47789
has title: Merge loop and print statement in Python
downvote count: 0
favorite count: 0
tagged with: python
score: 1
tagged with: python-3.x
has body: items = [ "Abby","Brenda","Cindy","Diddy" ] for item in items: print(item) I use to write this statement for output items. Is there a way to merge both print and loops. Something like: print(item for item in items) Correct me if I am wrong!
has answer: http://stackoverflow.com/a/50555154
upvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50555154
type: Question

http://stackoverflow.com/comment/88194890
comment on: http://stackoverflow.com/q/50592706
has text: You must have used merge instead of concat.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88201560
type: QuestionComment
has text: `CreateAPIView` return object's details by default. What is your current response? Can you show full serializer's code and `getOrder` code also?
score: 0
comment on: http://stackoverflow.com/q/50595929
type: Comment

http://stackoverflow.com/comment/88481173
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50567100
has text: @joeb, I have attached the output in the question itself.Thanks
score: 0

http://stackoverflow.com/a/50634640
type: Answer
score: 2
downvote count: 0
has body: Your current approach is not very efficient, as you will iterate over txt, multiple times, 2 (in and find()) for each operator. You could use index() instead of find() and just ignore the ValueError exception , e.g.: def findNextOpr(txt): for o in '+-*/': try: return txt.index(o) except ValueError: pass return -1 You can do this in a single (perhaps more readable) pass by enumerate()ing the txt and return if you find the character, e.g.: def findNextOpr(txt): for i, c in enumerate(txt): if c in '+-*/': return i return -1 Note: if you wanted all of the operators you could change the return to yield, and then just iterate over the generator, e.g.: def findNextOpr(txt): for i, c in enumerate(txt): if c in '+-*/': yield i In []: for op in findNextOpr('1+2-3+4'): print(op) Out[]: 1 3 5
has comment: http://stackoverflow.com/comment/88279968
answers question: http://stackoverflow.com/q/50634600
has comment: http://stackoverflow.com/comment/88279730
upvote count: 2

http://stackoverflow.com/q/50681362
has title: Float formatting and output to ascii file using Pandas
tagged with: formatting
type: Question
tagged with: format
has comment: http://stackoverflow.com/comment/88372592
tagged with: dataframe
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/88372399
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50681628
tagged with: python
has body: I have a pandas DataFrame that looks like this:: &gt;&gt;&gt; df In [6]: df Out[6]: 0 1 2 3 0 0.445598 0.173835 0.343415 0.682252 1 0.881592 0.696942 0.702232 0.696724 2 0.662527 0.955193 0.131016 0.609548 and I'd simply like an ascii output such as: 0 1 2 3 0 0.446 0.174 0.343 0.682 1 0.882 0.697 0.702 0.697 2 0.663 0.955 0.131 0.610 I can use df = df.round(3) but then data.to_ascii screws up the formatting.

http://stackoverflow.com/comment/88298429
type: Comment
has text: That would be nice. As mentioned I tried several approaches but without success to do this what you're saying. It does not matter where I have these calculated data. Important is to have them explicitly in order to do other calculations outside from my initial function
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50643746

http://stackoverflow.com/a/50683084
score: 24
upvote count: 24
has comment: http://stackoverflow.com/comment/88396314
has comment: http://stackoverflow.com/comment/88396557
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88406267
answers question: http://stackoverflow.com/q/50678184
type: Answer
has comment: http://stackoverflow.com/comment/88396377
has body: You can use a temporary function or a lambda: async def main(): session = aiohttp.ClientSession() await asyncio.start_server(lambda r, w: handle_client(r, w, session), '', 55555) This works because even though the lambda is not technically a coroutine, it behaves just like one - when invoked it returns a coroutine object. For larger programs you might prefer a class-based approach where a class encapsulates the state shared by multiple clients without having to pass it explicitly. For example: class ClientContext: def __init__(self): self.session = aiohttp.ClientSession() # ... add anything else you will need "globally" async def handle_client(self, reader, writer): # ... here you get reader and writer, but also have # session etc as self.session ... async def main(): ctx = ClientContext() await asyncio.start_server(ctx.handle_client), '', 55555)
has comment: http://stackoverflow.com/comment/88394833
accepted answer of: http://stackoverflow.com/q/50678184
has comment: http://stackoverflow.com/comment/88396454

http://stackoverflow.com/q/50574342
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88158115
tagged with: python
tagged with: dictionary
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88158253
downvote count: 0
has answer: http://stackoverflow.com/a/50574402
accepted answer: http://stackoverflow.com/a/50574402
type: Question
has title: How to keep a copy of a dictionary with swapped items?
has body: The function swap_elements must swap elements in a dict and keep snapshots of the resulting dict before swapping back the elements to keep the original intact. By example: swap_elements({0: [1, 2], 1: [3, 4]}, [(0, 1), (1, 0)], (0, 0)) Should return {'entry 0': {0 :[2, 1], 1: [3, 4]}, 'entry 1': {0: [3, 2], 1: [1, 4]} Here is the code. def swap_elements(grid, new_positions, current_x_y): modified_grids_1 = {} i = 0 # original = grid for pos in new_positions: # print(pos[0], pos[1], current_x_y[0], current_x_y[1]) # print(grid[pos[0]][pos[1]], grid[current_x_y[0]][current_x_y[1]]) grid[pos[0]][pos[1]], grid[current_x_y[0]][current_x_y[1]] = grid[current_x_y[0]][current_x_y[1]], grid[pos[0]][pos[1]] # print_grid(grid) modified_grids_1.update({"entry "+str(i): grid}) # print_grid(modified_grids[i]) i += 1 grid[current_x_y[0]][current_x_y[1]], grid[pos[0]][pos[1]] = grid[pos[0]][pos[1]], grid[current_x_y[0]][current_x_y[1]] # print_grid(grid) print(modified_grids_1) # for k in modified_grids.keys(): # print_grid(modified_grids.get(k)) return modified_grids_1 I get the changed grid value inserted rightly into modified_grids_1 dictionary in for loop. But outside the for loop all the item values inserted in for loop gets back to the original value.
upvote count: 2

http://stackoverflow.com/comment/88199916
type: QuestionComment
has text: Thanks Bryan. That all makes sense, but when I try value = event.widget.get() it says I'm missing a positional argument 'index 1'
comment on: http://stackoverflow.com/q/50594802
score: 0
type: Comment

http://stackoverflow.com/comment/88423071
has text: No worries! Glad I could help!
type: AnswerComment
comment on: http://stackoverflow.com/a/50687453
score: 0
type: Comment

http://stackoverflow.com/comment/88232539
has text: Thanks for letting me about `tolist()` it fixed the entire issue :)
type: Comment
comment on: http://stackoverflow.com/a/50611194
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88241182
type: QuestionComment
type: Comment
has text: Stack Overflow is not a code writing service. Please show your code. Since Stack Overflow hides the Close reason from you: *Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/).*
comment on: http://stackoverflow.com/q/50597714
score: 0

http://stackoverflow.com/comment/88331304
type: Comment
comment on: http://stackoverflow.com/a/50660627
score: 0
type: AnswerComment
has text: Thanks for the help, man, but getting the result `Requirement already satisfied: selenium in c:\users\usuário\appdata\local\programs\python\python36-32\lib\site-packages (3.12.0)`

http://stackoverflow.com/a/50618087
type: AcceptedAnswer
downvote count: 0
has body: Use DataFrame.iloc with DataFrame.idxmax: df['Res'] = df.iloc[:, 1:].idxmax(axis=1) #if first column is index #df['Res'] = df.idxmax(axis=1) print (df) No Candidate_A Candidate_B Candidate_C Res 0 1 8 9 12 Candidate_C 1 2 18 9 12 Candidate_A 2 3 9 9 7 Candidate_A
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/50618066
upvote count: 1
answers question: http://stackoverflow.com/q/50618066

http://stackoverflow.com/comment/88397790
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50694219
score: 2
has text: can you please show the `for` loop where the `i` and `t` come from?

http://stackoverflow.com/a/50640942
type: Answer
answers question: http://stackoverflow.com/q/50640623
score: 2
downvote count: 0
upvote count: 2
has body: crop them with a small padding to prevent border effects and merge them back. you can see how this is done over here, line 552. https://github.com/lopuhin/kaggle-dstl/blob/master/train.py

http://stackoverflow.com/a/50582200
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88180469
has body: Based on the error, the content variable you are passing is not in the expected format. Use print(type(content)) and print(content) to understand what information are you passing and if it is the expected type. The library you are using is not a Google official library. Find an official example here. Is true that you cannot translate a whole website and an equivalent solution is not implemented. You need to read the page and adequate it; or pre-process content using dragnet, in your case. Find below a Python Client Library for Translation API example: # Imports the Google Cloud client library from google.cloud import translate # Instantiates a client translate_client = translate.Client() # The text to translate text = u'Hello, world!' # The target language target = 'ru' # Translates some text into Russian translation = translate_client.translate( text, target_language=target) print(u'Text: {}'.format(text)) print(u'Translation: {}'.format(translation['translatedText']))
upvote count: 1
has comment: http://stackoverflow.com/comment/88179497
answers question: http://stackoverflow.com/q/50572358
type: Answer
has comment: http://stackoverflow.com/comment/88182719

http://stackoverflow.com/comment/88201470
comment on: http://stackoverflow.com/q/50595740
has text: Why IE,it is too slow
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50582556
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50586256
has comment: http://stackoverflow.com/comment/88180793
tagged with: docker
answer count: 2
tagged with: angular
downvote count: 0
has body: I have two containers Auth and Frontend. I have managed to get both the containers working independently, I need to establish the link between the two to send and receive HTTP requests. Generally, the connections are made in angular like http://localhost:3000/auth/. Note: Both are in different deployments and services. Should I be using Ingress or Nginx?
favorite count: 0
accepted answer: http://stackoverflow.com/a/50586256
has title: Kubernetes - Configuring Angular to Work with a Backend API
possible better answer: http://stackoverflow.com/a/50584666
has answer: http://stackoverflow.com/a/50584666
tagged with: kubernetes
tagged with: python
type: AnsweredQuestion
score: 1

arrays
tags question: http://stackoverflow.com/q/50668495
tags question: http://stackoverflow.com/q/50580196
tags question: http://stackoverflow.com/q/50629625
type: Tag
tags question: http://stackoverflow.com/q/50646102
tags question: http://stackoverflow.com/q/50568508
tags question: http://stackoverflow.com/q/50671899
tags question: http://stackoverflow.com/q/50604250
tags question: http://stackoverflow.com/q/50610993
tags question: http://stackoverflow.com/q/50591126
tags question: http://stackoverflow.com/q/50587297
tags question: http://stackoverflow.com/q/50573104
tags question: http://stackoverflow.com/q/50549910
tags question: http://stackoverflow.com/q/50545870
tags question: http://stackoverflow.com/q/50630280
tags question: http://stackoverflow.com/q/50608021
tags question: http://stackoverflow.com/q/50646292
tags question: http://stackoverflow.com/q/50615734
tags question: http://stackoverflow.com/q/50554019
tags question: http://stackoverflow.com/q/50594318
tags question: http://stackoverflow.com/q/50542586
tags question: http://stackoverflow.com/q/50562946
tags question: http://stackoverflow.com/q/50634310
tags question: http://stackoverflow.com/q/50625567
tags question: http://stackoverflow.com/q/50662438
tags question: http://stackoverflow.com/q/50604328
tags question: http://stackoverflow.com/q/50547504
tags question: http://stackoverflow.com/q/50685409
tags question: http://stackoverflow.com/q/50683207
tags question: http://stackoverflow.com/q/50579691
tags question: http://stackoverflow.com/q/50645325
tags question: http://stackoverflow.com/q/50569070
tags question: http://stackoverflow.com/q/50627737
tags question: http://stackoverflow.com/q/50599655
tags question: http://stackoverflow.com/q/50662164
tags question: http://stackoverflow.com/q/50641042
tags question: http://stackoverflow.com/q/50658020
tags question: http://stackoverflow.com/q/50567706
tags question: http://stackoverflow.com/q/50602441
tags question: http://stackoverflow.com/q/50647167
tags question: http://stackoverflow.com/q/50554272
tags question: http://stackoverflow.com/q/50616439
tags question: http://stackoverflow.com/q/50573677
tag name: arrays
tags question: http://stackoverflow.com/q/50679664
tags question: http://stackoverflow.com/q/50628500
tags question: http://stackoverflow.com/q/50571299
tags question: http://stackoverflow.com/q/50580391
tags question: http://stackoverflow.com/q/50630101
tags question: http://stackoverflow.com/q/50543265
tags question: http://stackoverflow.com/q/50586926
tags question: http://stackoverflow.com/q/50648443
tags question: http://stackoverflow.com/q/50556214
tags question: http://stackoverflow.com/q/50553645
tags question: http://stackoverflow.com/q/50604402
tags question: http://stackoverflow.com/q/50687450
tags question: http://stackoverflow.com/q/50615262
tags question: http://stackoverflow.com/q/50570067
tags question: http://stackoverflow.com/q/50668290
tags question: http://stackoverflow.com/q/50690751
tags question: http://stackoverflow.com/q/50659491
tags question: http://stackoverflow.com/q/50595150
tags question: http://stackoverflow.com/q/50636323
tags question: http://stackoverflow.com/q/50571381
tags question: http://stackoverflow.com/q/50644639
tags question: http://stackoverflow.com/q/50544788
tags question: http://stackoverflow.com/q/50628138
tags question: http://stackoverflow.com/q/50671172
tags question: http://stackoverflow.com/q/50664416
tags question: http://stackoverflow.com/q/50651443
tags question: http://stackoverflow.com/q/50691577
tags question: http://stackoverflow.com/q/50650491
tags question: http://stackoverflow.com/q/50580518
tags question: http://stackoverflow.com/q/50642883
tags question: http://stackoverflow.com/q/50672033
tags question: http://stackoverflow.com/q/50585695

http://stackoverflow.com/comment/88288954
type: QuestionComment
comment on: http://stackoverflow.com/q/50630668
has text: @DanielRoseman Please see my edit with my new code - I can init but can't update between the handlers.
score: 0
type: Comment

http://stackoverflow.com/comment/88103189
score: 0
has text: @MiniMiloe If a random subset of colors is fine with you, do something like `less_colors = {k: v for k, v in list(colors.cnames.items())[::5]}` this would keep a fifth of the colors and discard the others. Don't forget to replace `colors.cnames` with `less_colors` in the rest of the script.
type: AnswerComment
comment on: http://stackoverflow.com/a/50545735
type: Comment

http://stackoverflow.com/comment/88149587
type: Comment
type: QuestionComment
has text: Maybe you actually try using the [ban](http://discordpy.readthedocs.io/en/latest/api.html#discord.Client.ban) command in some way in your code?
comment on: http://stackoverflow.com/q/50569780
score: 0

http://stackoverflow.com/comment/88170277
score: 2
type: Comment
has text: Downvoters, it isn't _that_ bad a question. The problem statement is clear and the question is answerable.
type: QuestionComment
comment on: http://stackoverflow.com/q/50580481

http://stackoverflow.com/comment/88305173
type: Comment
has text: what other possible case?
comment on: http://stackoverflow.com/a/50636084
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88179562
has text: Thanks, this works. So it seems the `Base.value.getter/setter` decorators are meant to somehow use properties from another class while redefining part of it, not to indicate inheritance. So in my example the setter definition will overwrite the `value` property with the `Base` getter and the new setter. Weird...
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50584858
score: 0

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/50582432
tags question: http://stackoverflow.com/q/50618404
tags question: http://stackoverflow.com/q/50552404
tags question: http://stackoverflow.com/q/50565663
type: Tag
tags question: http://stackoverflow.com/q/50669877
tags question: http://stackoverflow.com/q/50681949
tags question: http://stackoverflow.com/q/50672428
tags question: http://stackoverflow.com/q/50649754
tags question: http://stackoverflow.com/q/50654624
tags question: http://stackoverflow.com/q/50598524
tags question: http://stackoverflow.com/q/50649985
tags question: http://stackoverflow.com/q/50574034
tags question: http://stackoverflow.com/q/50592875
tags question: http://stackoverflow.com/q/50651406
tags question: http://stackoverflow.com/q/50553025
tag name: csv
tags question: http://stackoverflow.com/q/50692295
tags question: http://stackoverflow.com/q/50629892
tags question: http://stackoverflow.com/q/50685769
tags question: http://stackoverflow.com/q/50618536
tags question: http://stackoverflow.com/q/50558077
tags question: http://stackoverflow.com/q/50598674
tags question: http://stackoverflow.com/q/50599312
tags question: http://stackoverflow.com/q/50588823
tags question: http://stackoverflow.com/q/50692572
tags question: http://stackoverflow.com/q/50696486
tags question: http://stackoverflow.com/q/50642204
tags question: http://stackoverflow.com/q/50595288
tags question: http://stackoverflow.com/q/50622697
tags question: http://stackoverflow.com/q/50546401
tags question: http://stackoverflow.com/q/50543279
tags question: http://stackoverflow.com/q/50593590
tags question: http://stackoverflow.com/q/50577413
tags question: http://stackoverflow.com/q/50593781
tags question: http://stackoverflow.com/q/50687118
tags question: http://stackoverflow.com/q/50659821
tags question: http://stackoverflow.com/q/50629261
tags question: http://stackoverflow.com/q/50604133
tags question: http://stackoverflow.com/q/50564837
tags question: http://stackoverflow.com/q/50588691
tags question: http://stackoverflow.com/q/50692749
tags question: http://stackoverflow.com/q/50679638
tags question: http://stackoverflow.com/q/50551034
tags question: http://stackoverflow.com/q/50667127
tags question: http://stackoverflow.com/q/50544235
tags question: http://stackoverflow.com/q/50543666
tags question: http://stackoverflow.com/q/50572153
tags question: http://stackoverflow.com/q/50626573
tags question: http://stackoverflow.com/q/50546775
tags question: http://stackoverflow.com/q/50574244
tags question: http://stackoverflow.com/q/50688353
tags question: http://stackoverflow.com/q/50628767
tags question: http://stackoverflow.com/q/50647561
tags question: http://stackoverflow.com/q/50666714
tags question: http://stackoverflow.com/q/50610967
tags question: http://stackoverflow.com/q/50623009
tags question: http://stackoverflow.com/q/50556805
tags question: http://stackoverflow.com/q/50550639
tags question: http://stackoverflow.com/q/50619573
tags question: http://stackoverflow.com/q/50573209
tags question: http://stackoverflow.com/q/50555000
tags question: http://stackoverflow.com/q/50666410
tags question: http://stackoverflow.com/q/50648481
tags question: http://stackoverflow.com/q/50684104
tags question: http://stackoverflow.com/q/50683765
tags question: http://stackoverflow.com/q/50616513
tags question: http://stackoverflow.com/q/50614545
tags question: http://stackoverflow.com/q/50572587
tags question: http://stackoverflow.com/q/50646878
tags question: http://stackoverflow.com/q/50629427
tags question: http://stackoverflow.com/q/50638076
tags question: http://stackoverflow.com/q/50625680
tags question: http://stackoverflow.com/q/50618621
tags question: http://stackoverflow.com/q/50691307
tags question: http://stackoverflow.com/q/50549715
tags question: http://stackoverflow.com/q/50664839
tags question: http://stackoverflow.com/q/50568826
tags question: http://stackoverflow.com/q/50647213
tags question: http://stackoverflow.com/q/50665855

http://stackoverflow.com/q/50647031
has answer: http://stackoverflow.com/a/54949808
answer count: 1
has body: I have a python script where I am building a string one line at a time. I add the '\r\n' at the end of each line of a string with exception of the last line. This string gets written into a tag in Ignition SCADA. When I examine the contents of the tag, where the '\r\n' should have created the carriage return/new line all I have is a space (' '). Any idea why this is behaving this way and what I can do to get the string to format correctly? Thanks! Edit: Here's the code: myStr = '' for i in range(1, 10): myStr += 'This is line ' + str(i) + '.\r\n' resp = system.tag.write('myStrTag', myStr) print myStr
tagged with: python
has title: Strings in Python with \r\n not rendering carriage return line feed in SCADA tags
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88304616
has comment: http://stackoverflow.com/comment/88304688
has comment: http://stackoverflow.com/comment/88304593
type: Question
tagged with: scada-ignition
has comment: http://stackoverflow.com/comment/88305037
score: 0

http://stackoverflow.com/q/50551728
accepted answer: http://stackoverflow.com/a/50552265
score: 4
upvote count: 4
answer count: 2
tagged with: pandas
has title: Pandas - Create a table with a "dummy variable"
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50552265
tagged with: python
tagged with: stata
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50552036
has body: Let's say I have this dataframe id | car | sex | income ------------------------------- 1 | European | Male | 45000 2 | Japanese | Female | 48000 3 | American | Male | 53000 Is there an easy way to create this one (using pandas) ? | id | car | choice | sex | income 1.| 1 | European | 1 | Male | 45000 2.| 1 | American | 0 | Male | 45000 3.| 1 | Japanese | 0 | Male | 45000 | ---------------------------------------- 4.| 2 | European | 0 | Female | 48000 5.| 2 | American | 0 | Female | 48000 6.| 2 | Japanese | 1 | Female | 48000 | ---------------------------------------- 7.| 3 | European | 0 | Male | 53000 8.| 3 | American | 1 | Male | 53000 9.| 3 | Japanese | 0 | Male | 53000 The idea is to get every modality of the "car" variable in the base, and to indicate which one every person has chosen through the "choice" variable. For example, in the first table, the person with the id 1 has chosen an European car, so choice equals 1 in the line where car is European, and zero in the line where car equals American or Japanese. I already coded something which manually does it (using a dictionary) but I wanted to know if a cleaner solution exists. (This has for aim to format the data in order to use an asclogit/nlogit under Stata)
type: Question
possible better answer: http://stackoverflow.com/a/50552036

http://stackoverflow.com/comment/88247600
type: Comment
comment on: http://stackoverflow.com/q/50617691
score: 0
has text: Might be hard for some names like D'J M O'Brien, Doris Di-O Y.
type: QuestionComment

http://stackoverflow.com/q/50577697
accepted answer: http://stackoverflow.com/a/50581487
has title: django model object and queryset save to other table
has comment: http://stackoverflow.com/comment/88169456
tagged with: django
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88169011
tagged with: django-models
has comment: http://stackoverflow.com/comment/88170321
type: Question
has comment: http://stackoverflow.com/comment/88168599
has body: using django 2.0.2 python3.4 skip details models.py class Post(models.Model): postuid = models.BigAutoField( db_column='postUID', primary_key=True) useruid = models.Foreignkey .... skip content = models.Text .... registerdate = models.Date .... class KeepPost(models.Model): keeppostuid = models.BigAutoField( db_column='KeepPostUID', primary_key=True) useruid = models.ForeignKey( 'Userinfo', db_column='UserUID', on_delete=models.CASCADE) postuid = models.ForeignKey( 'Post', db_column='PostUID', on_delete=models.DO_NOTHING) content = models.TextField(db_column='Content') registerdate = models.DateTimeField( db_column='RegisterDate') keepdate = models.DateTimeField( db_column='KeepDate') class ReportPost(models.Model): reportuid=models.BigAutoField( db_column='ReportUID', primary_key=True) postuid=models.ForeignKey( 'Post', db_column='PostUID', on_delete=models.DO_NOTHING) #useruid is reporter useruid=models.ForeignKey( 'Userinfo', db_column='UserUID', on_delete=models.CASCADE) registerdate = models.DateTimeField( db_column='RegisterDate' Post to KeepPost Post.objects.get(postuid=1) or Post.objects.filter(useruid=1) KeepPost.objects.create(modelobjects or queryset) get() is return model object , filter() is return queryset if i want delete after reported why use on_delete DO_NOTHING -> I want to keep a record even if ReportedPost is deleted just one post deleted ex) postmodel = Post.objects.get(postuid=request.get("postuid")) want that models move to KeepPost and delete postmodel.delete() if user want delete account usermodel = User.objects.get(useruid=useruid) Postquery = usermodel.post_set.all() reportPost = ReportPost.objects.filter(Q(postuid__in=Postquery)) i think move to KeepPost after intersect Postquery and reportPost usermodel.delete()
answer count: 1
tagged with: django-rest-framework
score: 0
has comment: http://stackoverflow.com/comment/88169418
has answer: http://stackoverflow.com/a/50581487

http://stackoverflow.com/q/50559152
score: 1
has comment: http://stackoverflow.com/comment/88134567
has comment: http://stackoverflow.com/comment/88134389
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88134291
tagged with: machine-learning
upvote count: 1
tagged with: python
tagged with: computer-vision
answer count: 1
has comment: http://stackoverflow.com/comment/88134695
has title: Custom Layer in Keras for idct
has answer: http://stackoverflow.com/a/50562195
downvote count: 0
type: UnansweredQuestion
tagged with: keras
has comment: http://stackoverflow.com/comment/88134448
has body: I am trying to write a custom layer in Keras for IDCT (Inverse Discrete Cosine Transform) as there is no built-in function in Keras for IDCT as compared to DCT. So when I write my layer as: model = Sequential() model.add(Conv2D(512,1,activation='relu', input_shape= (8,8,64) )) model.add(Lambda( lambda x: get_2d_idct_tensor(x) ) ) where my function is defined as : def get_2d_idct_tensor(coefficients): return fftpack.idct(K.transpose(fftpack.idct(K.transpose(coefficients), norm='ortho')), norm='ortho') I get the following error: ----&gt; 9 model.add(Lambda( lambda x: get_2d_idct_tensor(x) ) ) 10 11 #model.add(Lambda(lambda x: K.tf.spectral.dct(K.transpose(K.tf.spectral.dct(K.transpose(x), type=2, norm='ortho')), norm='ortho'),input_shape=(8, 8, 512),output_shape=(8, 8, 1) )) /usr/local/lib/python3.6/dist-packages/keras/models.py in add(self, layer) 520 output_shapes=[self.outputs[0]._keras_shape]) 521 else: --&gt; 522 output_tensor = layer(self.outputs[0]) 523 if isinstance(output_tensor, list): 524 raise TypeError('All layers in a Sequential model ' /usr/local/lib/python3.6/dist-packages/keras/engine/topology.py in __call__(self, inputs, **kwargs) 617 618 # Actually call the layer, collecting output(s), mask(s), and shape(s). --&gt; 619 output = self.call(inputs, **kwargs) 620 output_mask = self.compute_mask(inputs, previous_mask) 621 /usr/local/lib/python3.6/dist-packages/keras/layers/core.py in call(self, inputs, mask) 683 if has_arg(self.function, 'mask'): 684 arguments['mask'] = mask --&gt; 685 return self.function(inputs, **arguments) 686 687 def compute_mask(self, inputs, mask=None): &lt;ipython-input-14-dae1f7021aae&gt; in &lt;lambda&gt;(x) 7 model.add(Conv2D(512,1,activation='relu', input_shape= (8,8,64) )) 8 ----&gt; 9 model.add(Lambda( lambda x: get_2d_idct_tensor(x) ) ) 10 11 #model.add(Lambda(lambda x: K.tf.spectral.dct(K.transpose(K.tf.spectral.dct(K.transpose(x), type=2, norm='ortho')), norm='ortho'),input_shape=(8, 8, 512),output_shape=(8, 8, 1) )) &lt…

http://stackoverflow.com/q/50546695
tagged with: python
has body: I am learning Python. Here is what I am trying to do and in the order I'm trying to do it: Open up an excel file Find all of the worksheets Take all of the rows on each work sheet and save as a csv If there are 3 worksheets on 1 excel file, there should be 3 csv files. Problem: I can't seem to be able to write the number of rows onto the worksheet. My code: import os, csv, re, openpyxl file_storage = [] excel_storage = [] excel_columns = ['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'] rowData = [] os.chdir('C:\\Users\\testing\\Desktop\\python\\chapter_14\\practice_project_files') print(str(os.getcwd())) for filenames in os.listdir(): file_storage.append(filenames) for x in range(len(file_storage)): file_type = re.compile('.*\.xlsx') files_found = file_type.search(file_storage[x]) if files_found: excel_storage.append(file_storage[x]) for y in range(len(excel_storage)): wb = openpyxl.load_workbook(excel_storage[y]) #print(wb.sheetnames) #print(str(len(wb.sheetnames))) for z in range(len(wb.sheetnames)): wb.active = z sheet = wb.active with open('test.csv', 'wb') as f: csvWriter = csv.writer(f) for r in range(1,sheet.max_row + 1): for colNum in range(0, sheet.max_column ): stuff = sheet[excel_columns[colNum] + str(r)].value rowData.append(stuff) csvWriter.writerow(r) wb.close() The part of my code that is giving me problems in particular: rowData.append(stuff) csvWriter.writerow(r) The error message I am getting: iterable expected, not int What am I doing wrong?
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/50546747
answer count: 1
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50546747
has title: Python Opening in Excel writing to CSV

http://stackoverflow.com/q/50568513
answer count: 4
score: 2
has comment: http://stackoverflow.com/comment/88148722
type: AnsweredQuestion
favorite count: 0
has title: Pandas series vectorized text processing
type: Question
tagged with: pandas
has comment: http://stackoverflow.com/comment/88147107
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/50621062
upvote count: 3
has comment: http://stackoverflow.com/comment/88148646
has comment: http://stackoverflow.com/comment/88146957
possible better answer: http://stackoverflow.com/a/50569559
downvote count: 1
has answer: http://stackoverflow.com/a/50569559
has body: I would like to improve my Pandas code using vectorized operations. So let's say I have a simple DataFrame with one text column which may contain urls. Column1 0 hello http://www.google.com 1 bye www.mail.com www.docs.google.com/index ... At this moment I am iterating the rows and applying the following substitution: s = re.sub('https*://[\w\.]+\.com[\w=*/\-]+|https*://[\w\.]+\.com|[\w\.]+\.com/[\w/\-]+',lambda x: re.findall('(?&lt;=\://)[\w\.]+\.com|[\w\.]+\.com', x.group())[0], s) The expected output should be: Column1 0 hello google.com 1 bye mail.com docs.google.com ... Is it possible to do this the whole series at a time?
has answer: http://stackoverflow.com/a/50606682
accepted answer: http://stackoverflow.com/a/50621062
has answer: http://stackoverflow.com/a/50569585

http://stackoverflow.com/a/50564263
score: 1
has body: x = eval("['good', 'bad', 'something', 'another']") The eval command does just that, but please avoid using it if you are not sure of what you are doing. If, for example, you try to put runnable code inside that string, the eval command will run it, potentially disrupting your system or opening it to external attacks. I assumed that you were working on a toy script that doesn't involve networking or access from external sources
has comment: http://stackoverflow.com/comment/88138710
answers question: http://stackoverflow.com/q/50564209
has comment: http://stackoverflow.com/comment/88140502
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/88140314
downvote count: 1

http://stackoverflow.com/q/50651872
has comment: http://stackoverflow.com/comment/105563606
has answer: http://stackoverflow.com/a/50654336
downvote count: 0
score: 7
favorite count: 0
has title: Can't execute msg (and other) Windows commands via subprocess
tagged with: python-3.x
type: Question
tagged with: windows
tagged with: python
has body: I have been having some problems with subprocess.call(), subprocess.run(), subprocess.Popen(), os.system(), (and other functions to run command prompt commands) as I can't seem to get the msg command to work. import subprocess subprocess.call("msg * Hey",shell=True) In theory, this should send "Hey" to every computer on the network unfortunately, this isn't running at all and I'm not quite sure why. I can run it on cmd successfully, but can't get it to work from Python. I'd love to hear why this doesn't work and hopeful a way to fix my code or an alternate solution. Edit: Solved, thanks for everyone's help. Upgrading to 64-bit Python did the trick.
tagged with: subprocess
answer count: 3
upvote count: 7
has answer: http://stackoverflow.com/a/50651923
has answer: http://stackoverflow.com/a/59747964
has comment: http://stackoverflow.com/comment/88315001
type: UnansweredQuestion

http://stackoverflow.com/comment/88351067
has text: Yes. The polygon you are using must be passed as a contour
comment on: http://stackoverflow.com/a/50670359
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50560826
type: Answer
answers question: http://stackoverflow.com/q/50560525
upvote count: 12
accepted answer of: http://stackoverflow.com/q/50560525
has body: The error tells you that plt.bar returns a single object, which cannot be unpacked. So you need to remove the comma (,). Instead call the returned bar container something like bars = plt.bar(xpos,revenue). You also cannot blindly copy some other solution for scatters or plots for bars. Instead you need to adapt it to the bars. So you need to go through the bars and check which of them, if any, is hovered. See a complete solution here: import numpy as np import matplotlib.pyplot as plt company=['google','amazon','msft','fb'] revenue=[80,68,54,27] fig=plt.figure() ax=plt.subplot() xpos=np.arange(len(company)) bars = plt.bar(xpos,revenue) annot = ax.annotate("", xy=(0,0), xytext=(-20,20),textcoords="offset points", bbox=dict(boxstyle="round", fc="black", ec="b", lw=2), arrowprops=dict(arrowstyle="-&gt;")) annot.set_visible(False) def update_annot(bar): x = bar.get_x()+bar.get_width()/2. y = bar.get_y()+bar.get_height() annot.xy = (x,y) text = "({:.2g},{:.2g})".format( x,y ) annot.set_text(text) annot.get_bbox_patch().set_alpha(0.4) def hover(event): vis = annot.get_visible() if event.inaxes == ax: for bar in bars: cont, ind = bar.contains(event) if cont: update_annot(bar) annot.set_visible(True) fig.canvas.draw_idle() return if vis: annot.set_visible(False) fig.canvas.draw_idle() fig.canvas.mpl_connect("motion_notify_event", hover) plt.show()
score: 12
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/94557261
downvote count: 0
has comment: http://stackoverflow.com/comment/117248685
has comment: http://stackoverflow.com/comment/94557514

http://stackoverflow.com/comment/88229131
score: 0
type: Comment
has text: If you just clear the session at Auth0, your application still "knows" who the user is and so it might skip requesting a new token when you ask for it. But that's a little out of the realm of the identity provider (Auth0) and more related to the overall architecture of your application.
comment on: http://stackoverflow.com/a/50609438
type: AnswerComment

http://stackoverflow.com/a/50677445
has body: So, you are providing a file-like object for the class to write data. You could use a child class that behaves the way you want OR let it write to a file and then process it OR use a virtual file Related: How to do virtual file processing?
answers question: http://stackoverflow.com/q/50664450
type: Answer
score: 0

http://stackoverflow.com/comment/88381923
comment on: http://stackoverflow.com/q/50685576
type: Comment
type: QuestionComment
score: 0
has text: Or you could create a custom RNNCell based on LSTMCell where you select a slice of the total input.

http://stackoverflow.com/q/50638502
has comment: http://stackoverflow.com/comment/88287293
tagged with: algorithm
possible better answer: http://stackoverflow.com/a/58410129
has comment: http://stackoverflow.com/comment/88287193
answer count: 2
has comment: http://stackoverflow.com/comment/88287140
has body: I am writing a function to find all the hills and valleys in a given list. For instance, [1,0,0,0,1] returns 3 and [0,1,0,1,0] returns 5. [0,2,2,1,1,0,0] returns 3. If a number (or consecutive numbers with same values) are bigger or smaller than both of its neighbors, it is considered as a hill or a valley. Below is my code: def hill_and_vally(s): if not s or len(s) &lt; 2: return 0 i = 0 count = 0 pre = None while i &lt; len(s): if i == 0: while s[i] == s[i+1]: # loop until value is different i += 1 i += 1 if i &lt; len(s): # check if it reaches the end count += 1 pre = s[i-1] # track the previous value elif i == len(s) - 1: while s[i] == s[i-1]: i -= 1 i -= 1 if i &gt;= 0: count += 1 break else: while s[i] == s[i+1]: i += 1 i += 1 if s[i] &gt; s[i-1] and pre &gt; s[i-1]: # it is a valley count += 1 elif s[i] &lt; s[i-1] and pre &lt; s[i-1]: # it is a hill count += 1 pre = s[i-1] return count Can someone help me to improve the complexity to O(N). Or show me another way to do it with better complexity? Please show me some examples. Thanks in advance.
downvote count: 0
has title: find all the hills and valley in a list
favorite count: 0
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88287692
has answer: http://stackoverflow.com/a/50638625
has answer: http://stackoverflow.com/a/58410129
type: Question
accepted answer: http://stackoverflow.com/a/50638625

http://stackoverflow.com/comment/88239872
has text: To new users joining the SO community, welcome! After you accumulate answer(s) to your question, you can choose one answer that solves your problem the best. For that answer, you may click the check mark ✅ under the votes to mark your question as solved, this will indicate to others that your question had been solved. Note that accepting is completely your choice.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50596763

http://stackoverflow.com/comment/88204944
has text: I just got error message that no module named 'pymysql'. and my python version is 3.6.5 and pip version is 10.0.1.
score: 0
comment on: http://stackoverflow.com/q/50597746
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50566754
type: Question
score: 0
has comment: http://stackoverflow.com/comment/88143595
has comment: http://stackoverflow.com/comment/88143754
has comment: http://stackoverflow.com/comment/88143938
answer count: 5
has answer: http://stackoverflow.com/a/50566933
tagged with: parsing
has title: Parse txt to blocks
has answer: http://stackoverflow.com/a/50566935
has answer: http://stackoverflow.com/a/50568447
has answer: http://stackoverflow.com/a/50567559
accepted answer: http://stackoverflow.com/a/50567559
has answer: http://stackoverflow.com/a/50567055
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has body: i have a txt file, which has the following structure start id=1 date=21.05.2018 summ=500 end start id=7 date=23.05.2018 summ=500 owner=guest end and i need to parse it in a list of dictionaries (str : str (even it is int type or date: convert it to string)). i.e. split it on block with start end, and after that split it on = symbol. The amount of lines between start end can be different. D But a can't realize it. I tried something like this: d ={} arr = [] ind = 0 for line in plines: ind = ind + 1 if 'startpayment' in line: print('ind = ' + str(ind)) for i in range(ind, len(plines)): print(i) key, value = plines[i].strip().split('=') if type(value) == 'str': d[key] = str(value) elif type(value) == 'int': d[key] = int(value) arr.append(d) if 'endpayment' in line: break Could someone help me? Thanks
possible better answer: http://stackoverflow.com/a/50566933

http://stackoverflow.com/q/50636902
upvote count: 1
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50637638
answer count: 2
has comment: http://stackoverflow.com/comment/88283934
has title: regular expression not matching white space
has body: I am at a loss on why this isn't matching all the occurances. I even put it in a RE tool online and it should match. I am running on Linux with 3.6. It only matches the search when it is followed by the '_SINK' but not when followed by '\s'. Here is a snippet of my search text and RE: import re lines = ['R_d_10763 VDDI_1007 Group_BGA_BGA_VDD_INT_AD26 3.711438e+000', 'R_d_10771 VDDI_1007 VDDI_1012 1.337785e+001', 'R_d_8607 Group_BGA_BGA_VSS_AH6 Group_BGA_BGA_VSS_AJ43 3.777161e+000', 'R_d_6585 Group_BGA_BGA_AVDD085_MIPI_DPHY_Y36 Group_BGA_BGA_AVDD085_MIPI_DPHY_W35_SINK_ 3.860682e-003', 'R_d_69804 Xm4s4s2_M_DPDATA0_580 Group_BGA_BGA_XMIPI_DSI_D0_P_V38_SINK_ 2.668494e-001', 'R_d_69668 XCP_ANT_SW1_383 Group_BGA_BGA_XCP_ANT_SW1_N5_SINK_ 5.037550e-001', 'R_d_13 AVDD085_MIPI_DPHY_540 Group_BGA_BGA_AVDD085_MIPI_DPHY_Y36 2.854267e-002',] for line in lines: conn1, conn2, res = line.split()[1:] match1 = re.search(r'(A?[A-Z][0-9]{1,2})(?:_SINK|\s)', conn1) match2 = re.search(r'(A?[A-Z][0-9]{1,2})(?:_SINK|\s)', conn2) try: conn1 = match1.group(1) except AttributeError: pass try: conn2 = match2.group(1) except AttributeError: pass print(f'Connection 1: {conn1} Connection 2: {conn2} Resistance: {res}') The output I get is: Connection 1: VDDI_1007 Connection 2: Group_BGA_BGA_VDD_INT_AD26 Resistance: 3.711438 Connection 1: VDDI_1007 Connection 2: VDDI_1012 Resistance: 13.37785 Connection 1: Group_BGA_BGA_VSS_AH6 Connection 2: Group_BGA_BGA_VSS_AJ43 Resistance: 3.777161 Connection 1: Group_BGA_BGA_AVDD085_MIPI_DPHY_Y36 Connection 2: W35 Resistance: 0.003860682 Connection 1: Xm4s4s2_M_DPDATA0_580 Connection 2: V38 Resistance: 0.2668494 Connection 1: XCP_ANT_SW1_383 Connection 2: N5 Resistance: 0.5037550 Connection 1: AVDD085_MIPI_DPHY_540 Connection 2: Group_BGA_BGA_AVDD085_MIPI_DPHY_Y36 Resistance: 0.02854267 But it should be Connection 1: VDDI_1007 Connection 2: AD26 Resistance: 3.711438 Connection 1: VDDI_1007 Connection 2: VDDI_1012 Resistance: 13.37785 Connection 1: AH6 Connection…
possible better answer: http://stackoverflow.com/a/50637374
has comment: http://stackoverflow.com/comment/88284100
has answer: http://stackoverflow.com/a/50637374
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50637638
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/88284986
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/50676046
has answer: http://stackoverflow.com/a/50702166
tagged with: pip
upvote count: 1
type: Question
tagged with: pandas
downvote count: 0
answer count: 1
score: 1
tagged with: pypy
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I am getting troubles to install pandas on pypy3. When I use pip to install it: pypy3 -m pip install pandas The output starts with the following: Installing collected packages: pandas Running setup.py install for pandas ... - Subprocess output does not appear to be encoded as cp1252 Subprocess output does not appear to be encoded as cp1252 After a short pause, I get a long text of warnings: .... pandas/_libs/src/parser/tokenizer.c(1412): warning C4996: 'strncpy': This function or variable may be unsafe. Consider using strncpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. C:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\ucrt\string.h(344): note: Siehe Deklaration von "strncpy" C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -Ipandas/_libs/src/klib -Ipandas/_libs/src -IC:\Users\scandas\opt\site-packages\numpy\core\include -IC:\Users\scandas\opt\include /Tcpandas/_libs/src/parser/io.c /Fobuild\temp.win32-3.5\Release\pandas/_libs/src/parser/io.obj io.c pandas/_libs/src/klib\khash.h(574): warning C4090: "Funktion": Unterschiedliche "const"-Qualifizierer pandas/_libs/src/parser/io.c(30): warning C4996: 'open': The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name: _open. See online help for details. C:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\ucrt\corecrt_io.h(516): note: Siehe Deklaration von "open" pandas/_libs/src/parser/io.c(40): warning C4996: 'close': The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name: _close. See online help for details. C:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\ucrt\corecrt_io.h(459): note: Siehe Deklaration von "close" pandas/_libs/src/parser/io.c(74): warning C4996: 'close': The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name: _close. See online help for details. C:\Program Files (x86)\W…
has title: Error with installing pandas on pypy3: ...Microsoft Visual Studio 14.0\\VC\\BIN\\cl.exe' failed with exit status 2

http://stackoverflow.com/q/50592183
has answer: http://stackoverflow.com/a/50592323
tagged with: tkinter
type: Question
has title: Add background Image on widget Text using PIL
tagged with: python-imaging-library
has body: I would like to know if there is a command that will put the image in the foreground, set it to transparent and block it, that is, the picture will look like a background for a text editor
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/88196580
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50593632
score: 3
has text: Converting to tuple would be the standard approach

http://stackoverflow.com/q/50573260
type: UnansweredQuestion
tagged with: input
tagged with: python
has body: I would like to know if it is possible to obtain a simpledialog.SimpleDialog in python with 2 inputs. The documentation is not clear on this and I could not find any information on this online. The end result I would like to get is something on the lines of this: An input box with 2 lines one for each variable |---------------------| |Input 1 | ' text abc'| |---------------------| |Input 2 | ' Text fgh'| |---------------------| Kind regards and thanks in advance
upvote count: 0
tagged with: tkinter
type: Question
has title: simpledialog.SimpleDialog in python with 2 inputsH
score: -1
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50574998
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/88325050
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50657501
has text: The only thing I worry about with this solution (and probably affects mine too) is floating point rounding, e.g. if `6.0` is stored as `6.00001` will this be correct? Maybe we have to convert to `int` first, with `np.isclose` to guarantee we get the right one.

http://stackoverflow.com/q/50685323
type: Question
tagged with: flask
tagged with: ajax
has body: Today I was solving how to use recaptcha from flask-WTF 0.14.2 in form which is POST on server via ajax. I wasn't able to find solution how to implement recaptcha with ajax and successfully validate it on server and then send answer back to client. Recaptcha validation was complaining with this error despite I was sending required "response parameter" from client to server: 'recaptcha': ['The response parameter is missing.'] I was not able to find answer anywhere on Stackoverflow so I post here my own working code.
score: 0
answer count: 1
tagged with: recaptcha
tagged with: flask-wtforms
has answer: http://stackoverflow.com/a/50685324
type: UnansweredQuestion
tagged with: python
has title: flask-wtf recaptcha validation through ajax

http://stackoverflow.com/a/50596241
has body: If you are looking to filter out just that character: negation of str.contains Escape the open paren. Some characters can be interpreted as special regex characters. You can escape them with a backslash. df[~df.my_column.str.contains('\(')] some_col my_column 0 1 some 1 2 word str.match all non-open-paren By the way, this is a bad idea! Checking the whole string that it isn't a character with regex is gross. df[df.my_column.str.match('^[^\(]*$')] some_col my_column 0 1 some 1 2 word Comprehension using in df'(' not in x for x in df.my_column some_col my_column 0 1 some 1 2 word
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88201639
has comment: http://stackoverflow.com/comment/88201622
has comment: http://stackoverflow.com/comment/88201606
answers question: http://stackoverflow.com/q/50595548
upvote count: 2
type: Answer

http://stackoverflow.com/a/50560060
answers question: http://stackoverflow.com/q/50559986
has body: Here's a function that does the trick. In [13]: def get_every_3rd_instance(mylist, item): ...: count = 0 ...: idx_list = [] ...: for idx, i in enumerate(mylist): ...: if i == item: ...: count += 1 ...: if count == 3: ...: idx_list.append(idx) ...: count = 0 ...: ...: return idx_list In [14]: get_every_3rd_instance(l, 6) Out[14]: [26, 33]
type: Answer
score: -1
downvote count: 1
upvote count: 0

http://stackoverflow.com/comment/88270778
type: AnswerComment
has text: Thanks @jmcnamara, your answer helped me to understand that I can't merge Excel table's cells and use 'autofilter':True, but I decided don't use .add_table, because I must to follow a determined format. But, thanks again, because XlsxWriter is the best.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50628640

pygame
tags question: http://stackoverflow.com/q/50667769
tags question: http://stackoverflow.com/q/50557939
tags question: http://stackoverflow.com/q/50629942
tags question: http://stackoverflow.com/q/50671502
tags question: http://stackoverflow.com/q/50614592
tags question: http://stackoverflow.com/q/50630244
tags question: http://stackoverflow.com/q/50547988
tags question: http://stackoverflow.com/q/50650456
tags question: http://stackoverflow.com/q/50616126
tags question: http://stackoverflow.com/q/50558360
tags question: http://stackoverflow.com/q/50584057
tags question: http://stackoverflow.com/q/50572229
tags question: http://stackoverflow.com/q/50584736
tags question: http://stackoverflow.com/q/50644295
tags question: http://stackoverflow.com/q/50550397
tags question: http://stackoverflow.com/q/50589701
tags question: http://stackoverflow.com/q/50542831
tags question: http://stackoverflow.com/q/50610188
tags question: http://stackoverflow.com/q/50567595
tags question: http://stackoverflow.com/q/50566851
tags question: http://stackoverflow.com/q/50586672
tags question: http://stackoverflow.com/q/50689598
tag name: pygame
tags question: http://stackoverflow.com/q/50545990
tags question: http://stackoverflow.com/q/50686169
tags question: http://stackoverflow.com/q/50630647
tags question: http://stackoverflow.com/q/50677749
tags question: http://stackoverflow.com/q/50633643
tags question: http://stackoverflow.com/q/50571812
tags question: http://stackoverflow.com/q/50653574
tags question: http://stackoverflow.com/q/50554102
tags question: http://stackoverflow.com/q/50656365
tags question: http://stackoverflow.com/q/50682144
tags question: http://stackoverflow.com/q/50547353
tags question: http://stackoverflow.com/q/50690427
tags question: http://stackoverflow.com/q/50569453
tags question: http://stackoverflow.com/q/50690369
tags question: http://stackoverflow.com/q/50690386
type: Tag

http://stackoverflow.com/q/50673064
tagged with: traceback
type: Question
answer count: 2
tagged with: for-loop
upvote count: 1
possible better answer: http://stackoverflow.com/a/50673263
has answer: http://stackoverflow.com/a/50673959
accepted answer: http://stackoverflow.com/a/50673959
favorite count: 0
tagged with: python
tagged with: python-pdfkit
downvote count: 0
has body: I'm using a for loop to go down a list and create variables for the pdfkit module and it works just fine for the first two items on the list then has an error on the Third. This is my code: import pdfkit import time link1 = "https://www." link2 = ".com" pdf = ".pdf" for line in open('links.txt'): print(line.strip("\n\r")) newlink = link1 + line.strip("\n\r") + link2 print(newlink) newpdf = line.strip("\n\r") + pdf print(newpdf) pdfkit.from_url(newlink, newpdf) print('Finished') And its pulling from This list: bing yahoo google It Successfully completes the first 2 items and prints a pdf on them then I get an error that says, Traceback (most recent call last): File new.py, line 14 in module pdfkit.from_url(newlink, newpdf) File "/usr/local/lib/python2.7/dist-packages/pdfkit/api.py", line 26 in from_return r.to_pdf(output_path) File "/usr/local/lib/python2.7/dist-packages/pdfkit/pdfkit.py," line 156, in traise IOError('wkhtmltopdf reported an error:\n' + stderr) IOError:wkhtmltopdf reported an error: Does anybody know why I'm getting this error and how to fix it?
score: 1
has answer: http://stackoverflow.com/a/50673263
tagged with: error-handling
type: AnsweredQuestion
has title: For loop goes through the first 2 items on the list then has a Tracback error on the Third

http://stackoverflow.com/comment/88366486
type: QuestionComment
score: 0
has text: Yes, it just needs to be a unique sequence
comment on: http://stackoverflow.com/q/50678421
type: Comment

http://stackoverflow.com/comment/88277784
type: QuestionComment
has text: I met the same problem.
comment on: http://stackoverflow.com/q/50553054
score: 0
type: Comment

http://stackoverflow.com/q/50575021
has body: I am having troubles figuring out how to plug in values from a dataframe into a list. The dataframe looks like this date A B C D 2018-05-25 188.58 35.56 1.66 21.91 When I do this: new = stats['A'] print(new) I get this: 18 188.58 Name: A, dtype: float64 I am looking for a list like this, but how to get the values in there: mylist = [188.58, 35.56, 1.66, 21.91]
score: 1
upvote count: 1
type: Question
downvote count: 0
tagged with: dataframe
has answer: http://stackoverflow.com/a/50575159
has title: How to get current values from dataframe to build a list?
answer count: 3
tagged with: pandas
favorite count: 0
has answer: http://stackoverflow.com/a/50575207
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50575033
tagged with: python

http://stackoverflow.com/a/50550507
type: Answer
has comment: http://stackoverflow.com/comment/88112052
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88112000
has comment: http://stackoverflow.com/comment/88112098
upvote count: 2
type: AcceptedAnswer
has body: Just use a simple helper function def contains(emails, email): for contained_email in emails: if email["email"] == contained_email["email"]: return True return False emails_new = [email for email in emails_all if not contains(emails_exist, email)]
accepted answer of: http://stackoverflow.com/q/50550433
answers question: http://stackoverflow.com/q/50550433

http://stackoverflow.com/q/50625680
has answer: http://stackoverflow.com/a/50625943
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/50625933
upvote count: 2
type: Question
type: AnsweredQuestion
has title: Skip a number of lines when reached to a number in file
possible better answer: http://stackoverflow.com/a/50625892
has body: I have a file as follows: Col1 Col2 A 1 A 1 A 1 A 2 A 1 A 1 A 3 A 1 A 1 A 1 I want to read the file line by line in Python. When I reach a line with Col2 > 1, I want to skip the number of lines equal to Col2. Here, when reached to A 2, I want to skip the next 2 lines and when I reach to Col2 equal to 3, I want to skip the next 3 lines and so on. If I read the whole file in a list, I can do the following: k = [1, 1, 1, 2, 1, 1, 3, 1, 1, 1] i = [] for element in k: if element &gt; 1: h = k.index(element) i.append(h) for j in range(1,element+1): i.append(h+j) new_list = [] for d in range(1, len(k)+1): if not d in i: new_list.append(k[d-1]) But my actual file is 7.2 GB so I thought to be more memory efficient, to read it line by line. How could I then implement this in Python?
answer count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/50625943
linked to: http://stackoverflow.com/q/394809
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/50625892

http://stackoverflow.com/a/50603030
downvote count: 0
has body: Try this, df.loc[df['col2'] ==1,'col6']=df['col3']*df['col5'] df.loc[df['col2'] ==2,'col6']=df['col4']*df['col5'] df['col6']=df['col6'].fillna(0)
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/50602820
score: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50602820

http://stackoverflow.com/a/50594483
answers question: http://stackoverflow.com/q/50594324
type: Answer
score: 1
has body: What you've done is not at all the same thing as execfile. So, it shouldn't be that surprising that it doesn't have the same effect as execfile. exec (and execfile) executes some code directly in the current scope. import checks whether the module has already been loaded, executing its code in a brand new scope if not, and then gives you a variable holding that module object in the current scope. For example, let's say we had a file named mod.py that looks like this: x = 1 print(x) Now, let's import it: &gt;&gt;&gt; import mod 1 &gt;&gt;&gt; mod.x 1 &gt;&gt;&gt; x NameError: name 'x' is not defined &gt;&gt;&gt; import mod # nothing will get printed the second and later times Compare what happens when you execfile it: &gt;&gt;&gt; execfile('mod.py') 1 &gt;&gt;&gt; mod.x NameError: name 'mod' is not defined &gt;&gt;&gt; x 1 &gt;&gt;&gt; execfile('mod.py') 1 On top of that, your execf doesn't even work, for multiple reasons: a.replace(".py", "") doesn't mutate a, it just returns a new string that you ignore. Your fibonacci.py module doesn't have a function named main. You can't "proceed to rest of code after a sys.exit", because sys.exit exits the program. You can handle this with except SystemExit:, but you shouldn't. At any rate, you definitely can't handle it with except AttributeError:; that will only fire because of, e.g., the fact that the module exists but doesn't have a .main attribute. At any rate, as What's New in Python 3.0 explains, the right way to do execfile in Python 3 is to open the file, read its contents, and exec them. In other words: with open(a) as f: exec(f.read()) If you want to wrap this in a function, notice that it will execute the code inside that function's local environment. If you want to execute it in globals no matter what, or in the environment of its caller, or anything else, you need to specify that. See the exec docs for details, but for a simple example: def execf(a): with open(a) as f: exec(f.read(), globals()) As a side note, in …
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/88352801
type: Comment
type: QuestionComment
has text: Please see http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question
comment on: http://stackoverflow.com/q/50671382
score: 0

http://stackoverflow.com/q/50675058
tagged with: python-3.x
upvote count: 0
downvote count: 5
tagged with: pivot-table
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/88359881
score: -5
has answer: http://stackoverflow.com/a/50675127
linked to: http://stackoverflow.com/q/50674086
has comment: http://stackoverflow.com/comment/88360420
has title: how to synchronize data frames in python?
answer count: 1
favorite count: 0
tagged with: pandas-groupby
has comment: http://stackoverflow.com/comment/88359979
tagged with: python
has body: I have two data frames 0 Product Range(Days) Sold 1 A 1-3 5 2 4-7 23 3 8-15 2 4 B 4-7 4 5 8-15 1 6 C 1-3 5 7 D 1-3 2 8 E 1-3 9 and 0 Product Repair_Calls 1 A 2 2 C 45 3 D 32 4 E 1 Can it be merged into one with repair calls being placed equally with respect to the product and not by 0-4 0 Product Range(Days) Sold Repair_Calls 1 A 1-3 5 2 2 4-7 23 3 8-15 2 4 B 4-7 4 0 5 8-15 1 6 C 1-3 5 45 7 D 1-3 2 32 8 E 1-3 9 1

http://stackoverflow.com/q/50686078
has comment: http://stackoverflow.com/comment/88382328
has comment: http://stackoverflow.com/comment/88382962
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/4806911
score: 1
has title: How to compare Twitter Ids in python
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88382062
answer count: 2
duplicate of: http://stackoverflow.com/q/39981237
has answer: http://stackoverflow.com/a/50686135
downvote count: 0
linked to: http://stackoverflow.com/q/4806911
linked to: http://stackoverflow.com/q/6062973
has comment: http://stackoverflow.com/comment/88382150
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/50686135
has body: I'm working with twitter ids which are strings because they are so huge. Twitter's api has a "Since_id" and I want to search tweets since the earliest tweet in a list. For example: tweet_ids = [u'1003659997241401843', u'1003659997241401234234', u'100365999724140136236'] # etc since_id = min(tweet_ids) So far min(tweet_ids) works but I want to understand why it works because I want to know if it is just by chance that it worked on the few samples I gave it, or if it is guaranteed to always work. Edit: To clarify I need to get the lowest tweet id. How do I get the lowest tweet id if they are strings that are > 2^32-1 and therefore can't be represented as integers in python 2.7 on a 32 bit machine. I am using python 2.7 if that matters
has comment: http://stackoverflow.com/comment/88382467
has answer: http://stackoverflow.com/a/50686101
linked to: http://stackoverflow.com/q/7604966
has comment: http://stackoverflow.com/comment/88382343
tagged with: string
duplicate of: http://stackoverflow.com/q/2622994
has comment: http://stackoverflow.com/comment/88381970
favorite count: 0
duplicate of: http://stackoverflow.com/q/35489619
possible better answer: http://stackoverflow.com/a/50686101
has comment: http://stackoverflow.com/comment/88382661
has comment: http://stackoverflow.com/comment/88382054
has comment: http://stackoverflow.com/comment/88382361
tagged with: python

http://stackoverflow.com/q/50637081
tagged with: twitter-bootstrap
has comment: http://stackoverflow.com/comment/88287941
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: Right now I'm stuck between two things: Either I have a login form that works but isn't exactly what you call visually appealing and one that looks flawless but doesn't do anything. (I know quite the situation) As shown the one up top is clearly quite the looker (sarcasm*), but I want the hideous one at the bottom to work. For the for up top, I just used {{ form }} tag and have at one point my code looked like this: {% csrf_token %} {{ form.username.label_tag }} {{ form.username }} {{ form.password.label_tag }} {{ form.password }} But again this doesn't give me the look I want. As of right now, to get the non-functional (but pretty) form look at the bottom I'm using the code for the bootstrap template signin (signin.css included in my base template). This is what my form.html looks like right now: {% extends 'accounts/base.html' %} {% block main_content %} {% csrf_token %} {{ form}} Please Sign In {% endblock %} I have seen another StackOverflow post such as this one and tried installing django-widget-tweaks but since I'm using cloud9-ide it didn't work So please if there's a way where I could either somehow implement the form tags in my Html or successfully download django-tweaks, please let me know and I would greatly appreciate it. Thanks in advance.
has comment: http://stackoverflow.com/comment/88285183
linked to: http://stackoverflow.com/q/38496439
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88289475
has title: Is there a way to link input fields from HTML to the ACTUAL form fields used in DJANGO
has answer: http://stackoverflow.com/a/50638918
has answer: http://stackoverflow.com/a/50637888
score: 0
has comment: http://stackoverflow.com/comment/88289506
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/comment/88103947
comment on: http://stackoverflow.com/q/50545022
score: 1
type: Comment
type: QuestionComment
has text: Your code works and shows the gif for me. Is it possible for you to post the rest of your code?

http://stackoverflow.com/comment/88117328
score: 0
has text: @AGNGazer, no, I could load the huge data into `A` chunk by chunk,
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50552896

http://stackoverflow.com/comment/88246771
comment on: http://stackoverflow.com/q/50618422
score: 0
type: Comment
type: QuestionComment
has text: Tuples are immutable. Here `FullFilesList` is a tuple.So when you try to assign a value at `index` it will rise `TypeError`. If you really want to do that convert `FullFilesList` to a list first, then mutate it and convert back to tuple again.

http://stackoverflow.com/q/50630910
has answer: http://stackoverflow.com/a/50631121
upvote count: 3
type: Question
score: 3
has answer: http://stackoverflow.com/a/50630994
tagged with: dataframe
tagged with: sorting
has title: Sort dataframe columns by month and year
answer count: 2
tagged with: pandas
downvote count: 0
has body: I am looking at monthly data, in a data frame. The column headers are all string, converted from datetime. This is my final output thus far: Feb 18 Jan 18 Mar 18 Flavor Vanilla 16.0 10.0 0.0 Chocolate 20.0 20.0 16.0 Seems that the columns are sorted alphabetically. Is there a way I can sort these columns of type string by month AND year? Does it involve using prefixes?
favorite count: 0
accepted answer: http://stackoverflow.com/a/50630994
tagged with: python
possible better answer: http://stackoverflow.com/a/50631121
type: AnsweredQuestion

http://stackoverflow.com/comment/88353329
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50671524
has text: I can use polygon, but I dont need to close polygon

http://stackoverflow.com/a/50578649
has comment: http://stackoverflow.com/comment/88167186
has comment: http://stackoverflow.com/comment/88166610
has comment: http://stackoverflow.com/comment/88167638
has comment: http://stackoverflow.com/comment/88167339
has comment: http://stackoverflow.com/comment/88167015
has comment: http://stackoverflow.com/comment/88167765
has comment: http://stackoverflow.com/comment/88167384
type: AcceptedAnswer
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/88166634
has body: Let's use a little math to make things easier. Filter out the columns you want. I use DataFrame.filter to do this Get a mask of cells > 0 Multiply each row of this mask with a range (you want 1-6) using DataFrame.mul Replace 0s in the result with x using DataFrame.replace Aggregate the rows to form a single string, using DataFrame.agg (data.filter(like='c_flow') .gt(0) .mul(range(1, 7)) .replace(0, 'x') .astype(str) .agg(''.join, 1) ) 0 123x56 1 1234xx 2 x2xx5x 3 123456 4 xx3456 5 1x3456 dtype: object
type: Answer
answers question: http://stackoverflow.com/q/50578481
has comment: http://stackoverflow.com/comment/88177243
accepted answer of: http://stackoverflow.com/q/50578481
upvote count: 4
has comment: http://stackoverflow.com/comment/88167600

http://stackoverflow.com/q/50695051
has body: I want to make a registration form using flask_wft but this line never executed if request.method == 'POST' and form.validate(): because form.validate() return False the reason is csrf_token. this is my code: `@app.route('/', methods=['GET', 'POST']) def form(): form = RegistrationForm(request.form) if request.method == 'POST' and form.validate(): user = Person(f_name=form.firstName.data, l_name=form.lastName.data, email=form.email.data,city=form.city.data) db.session.add(user) db.session.commit() return redirect(url_for('welcome')) print('errors: '+ str(form.errors)) return render_template('form.html', form=form)` I got this error: 'csrf_token': ['The CSRF token is missing.'] How to solve the problem?
has answer: http://stackoverflow.com/a/50695978
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88399909
has comment: http://stackoverflow.com/comment/88399896
has title: 'csrf_token': ['The CSRF token is missing.'] >> flask_wtf
tagged with: flask
tagged with: flask-sqlalchemy
favorite count: 0
accepted answer: http://stackoverflow.com/a/50695978
has comment: http://stackoverflow.com/comment/88399493
linked to: http://stackoverflow.com/q/21501058
type: Question
tagged with: python
duplicate of: http://stackoverflow.com/q/21501058
has comment: http://stackoverflow.com/comment/88399658
tagged with: flask-wtforms
score: 0
upvote count: 1
downvote count: 1
answer count: 1

http://stackoverflow.com/comment/88209077
has text: I am musing on the idea of suggesting changing working `working_days` to a list and using `(searched_date_week_day + 1) % len(working_days)` as your 'iterator'. What do you think? You'd need to change how you find the current entry, but it might work.
comment on: http://stackoverflow.com/q/50599584
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88344929
type: AnswerComment
comment on: http://stackoverflow.com/a/50667462
type: Comment
has text: Glad to hear it. Happy coding :)
score: 0

http://stackoverflow.com/q/50611940
tagged with: ping
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88234725
has body: How is it possible to make Computer A and Computer B do an action at exactly the same timing in Python, such as play a sound? Note: I'm looking for a maximum timing error of 50 milliseconds They are not on the same local network In my application, the soundfile will already be in RAM, and the audio buffering time is supposed to be identical in Computer A and B I was thinking about synchronizing the clock of both computers with an Internet time server, such as time.nist.gov, available here on Windows 7: and then launch a task from Python at 14:00:00.000 (there are libraries for that) but I fear the synchronization might be good up to an error of timeserver_computer_A_ping + timeserver_computer_B_ping which is maybe too much. Application: I want to play a beep: pygame.init() pygame.mixer.Sound('beep.wav').play() at the same time on Computer A and Computer B distant of each other of 3 kilometers, and record this beep with a pocket recorder like Zoom H2 as well as the sound of a nearby church bell. With the difference between "church bell timing - beep timing" for both Computer A and B and GPS coordinates, I would like to test if I'm able to confirm or infirm General relativity do basic triangulation.
score: 0
has comment: http://stackoverflow.com/comment/88235679
favorite count: 0
tagged with: synchronization
has title: Synchronize an action on two computers connected by internet
type: UnansweredQuestion
tagged with: time
tagged with: python
has comment: http://stackoverflow.com/comment/88234178
answer count: 0
has comment: http://stackoverflow.com/comment/88239402
has comment: http://stackoverflow.com/comment/88246423
upvote count: 1
tagged with: ntp

multi-gpu
type: Tag
tag name: multi-gpu
tags question: http://stackoverflow.com/q/50651996

http://stackoverflow.com/q/50653035
downvote count: 1
type: Question
score: 3
possible better answer: http://stackoverflow.com/a/50655848
upvote count: 4
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/88317408
has answer: http://stackoverflow.com/a/50653614
favorite count: 0
tagged with: python
has body: I have numpy array like this, where I have one column and one row of ZEROS : ([[0. , 2.8, 3.5, 0. , 2.5, 1. , 0.8], [0. , 0. , 0. , 0. , 0. , 0. , 0. ], [3.5, 2.5, 0. , 0. , 2.8, 1.3, 1.1], [3.6, 3.8, 3.3, 0. , 2.5, 0.6, 0.4], [2.5, 1.5, 2.8, 0. , 0. , 3.1, 1.9], [1. , 0.8, 1.3, 0. , 3.1, 0. , 2.8], [0.8, 1.6, 1.1, 0. , 1.9, 2.8, 0. ]]) I want to shift the zero-row to the top and the zero-column either to the left or remove it : ([[0. , 0. , 0. , 0. , 0. , 0. ] [0. , 2.8, 3.5, 2.5, 1. , 0.8], [3.5, 2.5, 0. , 2.8, 1.3, 1.1], [3.6, 3.8, 3.3, 2.5, 0.6, 0.4], [2.5, 1.5, 2.8, 0. , 3.1, 1.9], [1. , 0.8, 1.3, 3.1, 0. , 2.8], [0.8, 1.6, 1.1, 1.9, 2.8, 0. ]]) any quick and easy way to do it ? BTW I know the col&amp;row-number, so i doesnt have to search for it.
type: AnsweredQuestion
tagged with: row
has title: shift numpy array column and row?
accepted answer: http://stackoverflow.com/a/50653614
has comment: http://stackoverflow.com/comment/88316958
has answer: http://stackoverflow.com/a/50655848

nltk
tags question: http://stackoverflow.com/q/50633718
tags question: http://stackoverflow.com/q/50591856
tags question: http://stackoverflow.com/q/50642738
tags question: http://stackoverflow.com/q/50570511
tags question: http://stackoverflow.com/q/50644702
tags question: http://stackoverflow.com/q/50559652
tags question: http://stackoverflow.com/q/50646956
tags question: http://stackoverflow.com/q/50668970
tags question: http://stackoverflow.com/q/50657013
tags question: http://stackoverflow.com/q/50685343
tags question: http://stackoverflow.com/q/50560453
tags question: http://stackoverflow.com/q/50655203
tag name: nltk
tags question: http://stackoverflow.com/q/50611148
tags question: http://stackoverflow.com/q/50694066
tags question: http://stackoverflow.com/q/50629057
tags question: http://stackoverflow.com/q/50617254
type: Tag
tags question: http://stackoverflow.com/q/50560182

http://stackoverflow.com/comment/88326091
has text: Oh. Interesting. I guess I need to find some more documentation on classes and self. There are several things I am unclear on that I just found out about. Thanks again as always your input is educational.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50656996
type: AnswerComment

http://stackoverflow.com/comment/88132192
type: Comment
score: 2
comment on: http://stackoverflow.com/a/50560850
type: AnswerComment
has text: why complicate something so simple like that? That's just a double for loop

http://stackoverflow.com/q/50667036
possible better answer: http://stackoverflow.com/a/50667123
tagged with: python
has body: I am reading data from Twitter analytics with CSV and DataFrames. I want to extract url from certain cell The output is this process is the following tweet number tweet id tweet link tweet text 1 1.0086341313026E+018 "tweet link goes here" tweet text goes here https://example.com" How can I slice this "tweet text" to get the url of it? I cannot slice it using [-1:-12] because there are many tweets with different characters number.
has answer: http://stackoverflow.com/a/50667123
linked to: http://stackoverflow.com/q/37807244
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50667050
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50667108
accepted answer: http://stackoverflow.com/a/50667050
answer count: 3
tagged with: pandas
downvote count: 0
has title: Dataframe slicing from cell after reading csv
tagged with: string
favorite count: 0
tagged with: series
tagged with: python-3.x

http://stackoverflow.com/q/50654215
answer count: 1
has title: How to make sleep a file and use its function from another file in python
type: UnansweredQuestion
has body: I have have python file a.py which has a function fun(). fun() uses some libraries and global variables from a.py. The execution of a.py takes a lot of time but the execution of fun() is very fast once the libraries and global variables are ready. So I want to run a.py only once and use this variables and libraries every time I call the function fun() from another file. For example I want to call fun() for every 2 seconds from another file. But I can't do this because a.fun() is taking more time to execute. I want to setup 'a.py' in such way that after importing libraries and executing __main__ it sleeps or stops. After that whenever I am calling a.fun() from outside it should use the libraries already imported and the global variables calculated by __main__. How to do this in python?
tagged with: caching
linked to: http://stackoverflow.com/q/1186789
tagged with: function
tagged with: python-3.x
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/88318786
has comment: http://stackoverflow.com/comment/88318775
has answer: http://stackoverflow.com/a/50654471
score: 0
has comment: http://stackoverflow.com/comment/88453282
tagged with: multithreading
has comment: http://stackoverflow.com/comment/88318880

http://stackoverflow.com/comment/88222600
score: 0
comment on: http://stackoverflow.com/q/50605738
type: QuestionComment
has text: Now you have a Windows user googling that for you:https://www.thecodeship.com/deployment/deploy-django-apache-virtualenv-and-mod_wsgi/ ;))
type: Comment

http://stackoverflow.com/q/50562606
tagged with: pandas
tagged with: python
linked to: http://stackoverflow.com/q/17591104
has body: I don't understand why this renaming operation affects the original dataframe when the copy command is used. Why is df_copy a view of df and not really a copy? I would expect the print statement to output 'x' not 'y'. df = pandas.DataFrame({'x': [0, 1]}) df_copy = df.copy(deep=True) df_copy.columns.values[0] = 'y' print(df.columns)
favorite count: 0
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88135896
has title: Renaming pandas dataframe column on copy affects the original dataframe
has comment: http://stackoverflow.com/comment/88136193
linked to: http://stackoverflow.com/q/43291781
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50562856
accepted answer: http://stackoverflow.com/a/50562856
tagged with: dataframe
type: Question
upvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/88136147
has comment: http://stackoverflow.com/comment/88136352

http://stackoverflow.com/comment/88183047
type: QuestionComment
comment on: http://stackoverflow.com/q/50584736
has text: Plotly is using Javascript, so unless your game runs in a browser, it won't work.
score: 0
type: Comment

http://stackoverflow.com/q/50694693
has title: sy.sympify(str(expression)) is not equal to expression
tagged with: type-conversion
favorite count: 0
has answer: http://stackoverflow.com/a/50700463
tagged with: python
has comment: http://stackoverflow.com/comment/88402127
type: AnsweredQuestion
score: 3
upvote count: 3
has body: As I understand it, str converts a SymPy expression into a string and sympify converts a string into a SymPy expression. Thus, I would expect the following to hold (for reasonable expressions). &gt;&gt;&gt; sy.sympify(str(expr)) == expr True I tried this and indeed this is the case for simple examples (e.g., expr = x+y). However, when I tried it with the following expression, it did not work: import sympy as sy a = sy.symbols("a") A = sy.Matrix(3,3, a) c0,c1,c2 = sy.symbols("c0 c1 c2", positive = True) c1*c2**2*a(0, 1)**2*a(1, 2)*a(2, 2) - c1*c2**2*a(0, 1)**2*a(2, 2)**2 - c1*c2**2*a(0, 1)*a(0, 2)*a(1, 1)*a(2, 2) + c1*c2**2*a(0, 1)*a(0, 2)*a(2, 1)*a(2, 2) - c1*c2**2*a(0, 1)*a(1, 1)*a(1, 2)*a(2, 2) + c1*c2**2*a(0, 1)*a(1, 1)*a(2, 2)**2 + c1*c2**2*a(0, 2)*a(1, 1)**2*a(2, 2) - c1*c2**2*a(0, 2)*a(1, 1)*a(2, 1)*a(2, 2) - c1*a(0, 0)**2*a(1, 1)*a(2, 1) + c1*a(0, 0)**2*a(2, 1)**2 + c1*a(0, 0)*a(0, 1)*a(1, 1)*a(2, 0) - c1*a(0, 0)*a(0, 1)*a(2, 0)*a(2, 1) + c1*a(0, 0)*a(1, 0)*a(1, 1)*a(2, 1) - c1*a(0, 0)*a(1, 0)*a(2, 1)**2 - c1*a(0, 0)*a(1, 1)**2*a(2, 0) + c1*a(0, 0)*a(1, 1)*a(2, 0)*a(2, 1) - c2**2*a(0, 0)*a(0, 1)*a(1, 2)*a(2, 2) + c2**2*a(0, 0)*a(0, 1)*a(2, 2)**2 + c2**2*a(0, 0)*a(0, 2)*a(1, 1)*a(2, 2) - c2**2*a(0, 0)*a(0, 2)*a(2, 1)*a(2, 2) + c2**2*a(0, 1)*a(1, 0)*a(1, 2)*a(2, 2) - c2**2*a(0, 1)*a(1, 0)*a(2, 2)**2 - c2**2*a(0, 2)*a(1, 0)*a(1, 1)*a(2, 2) + c2**2*a(0, 2)*a(1, 0)*a(2, 1)*a(2, 2) + c2*a(0, 0)**2*a(1, 2)*a(2, 1) - c2*a(0, 0)**2*a(2, 1)*a(2, 2) - c2*a(0, 0)*a(0, 1)*a(1, 2)*a(2, 0) + c2*a(0, 0)*a(0, 1)*a(2, 0)*a(2, 2) - c2*a(0, 0)*a(1, 0)*a(1, 2)*a(2, 1) + c2*a(0, 0)*a(1, 0)*a(2, 1)*a(2, 2) + c2*a(0, 0)*a(1, 1)*a(1, 2)*a(2, 0) - c2*a(0, 0)*a(1, 1)*a(2, 0)*a(2, 2) Can somebody tell me why it doesn't work for this expression? PS: I know I'm supposed to put a minimal working example, but I just didn't find which part of the expression is causing the problem.
accepted answer: http://stackoverflow.com/a/50700463
type: Question
has comment: http://stackoverflow.com/comment/88402386
tagged with: sympy
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/88150994
comment on: http://stackoverflow.com/q/50570632
type: QuestionComment
has text: You may have a site package. https://stackoverflow.com/a/12737010/5509575 Also, there are many internal commands. Try looking for the output of `print 3` instead of doing math first.
score: 0
type: Comment

http://stackoverflow.com/comment/88355058
comment on: http://stackoverflow.com/q/50672643
has text: Do you actually just want to print the values in dataframeB['columnY'] (and no need to store them for later) or do you want, for example, a Series that you can print.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50663605
has body: The first form as it reads easier. Without any specific context, you should explicitly test for the default value, to avoid potential truthiness issues with the passed in value. def f(a, b=None): if b is None: b = [] pass From PEP 8, Programming Recommendations: Also, beware of writing if x when you really mean if x is not None -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context! You can see examples of this approach throughout the cpython repository: Lib/bdb.py Lib/argparse.py Lib/base64.py
answers question: http://stackoverflow.com/q/50663327
accepted answer of: http://stackoverflow.com/q/50663327
score: 5
type: AcceptedAnswer
upvote count: 5
type: Answer
downvote count: 0

http://stackoverflow.com/q/50572348
upvote count: 2
linked to: http://stackoverflow.com/q/21075999
accepted answer: http://stackoverflow.com/a/50572526
has comment: http://stackoverflow.com/comment/88154356
type: Question
has body: I am trying to read WGIData.csv file in a pandas dataframe. WGIData.csv is present inside a zip file which i am downloading from this url http://databank.worldbank.org/data/download/WGI_csv.zip But when i tried to read, it throws error BadZipFile: File is not a zip file Here is my python code import pandas as pd from urllib.request import urlopen from zipfile import ZipFile class Get_Data(): def Return_csv_from_zip(self, url): self.zip = urlopen(url) self.myzip = ZipFile(self.zip) self.myzip = self.zip.extractall(self.myzip) self.file = pd.read_csv(self.myzip) self.zip.close() return self.file url = 'http://databank.worldbank.org/data/download/WGI_csv.zip' data = Get_Data() df = data.Return_csv_from_zip(url)
tagged with: unzip
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88154292
has comment: http://stackoverflow.com/comment/88154481
favorite count: 0
has comment: http://stackoverflow.com/comment/88154389
has title: Create Dataframe from a csv inside a zip file
tagged with: pandas
has comment: http://stackoverflow.com/comment/88154342
tagged with: python
has comment: http://stackoverflow.com/comment/88154322
has comment: http://stackoverflow.com/comment/88154398
score: 2
has answer: http://stackoverflow.com/a/50572526
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/zip

http://stackoverflow.com/q/50667903
has comment: http://stackoverflow.com/comment/88374890
has comment: http://stackoverflow.com/comment/88347066
has comment: http://stackoverflow.com/comment/88345642
upvote count: 2
type: UnansweredQuestion
tagged with: python
downvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/88352517
tagged with: scipy
type: Question
linked to: http://stackoverflow.com/q/17559897
has body: How do I get P Value at different confidence level other than the default (95%) in python scipy t test or other statistical tests? For example: import scipy from scipy import stats data = [10,12,34,34,45,67,56,78,90,67,80,45,47,58] stats.ttest_1samp(data,40) Results are as below -- Out[7]: Ttest_1sampResult(statistic=1.808, pvalue=0.093) but I need p-value at 90% and 99% confidence level too. Only one answer is there but not very clear about where its confidence level is specified. Python p-value from t-statistic Is there any other alternate to Scipy in Python for it, if it can't be done with Scipy?
has answer: http://stackoverflow.com/a/50668019
answer count: 1
has comment: http://stackoverflow.com/comment/88383687
favorite count: 0
has title: How to get P Value at different confidence levels other than default in python scipy t test

http://stackoverflow.com/q/50571152
has answer: http://stackoverflow.com/a/50930270
has body: [My Development environment] root@kali:~# python Python 2.7.3 (default, Mar 14 2014, 11:57:14) [GCC 4.7.2] on linux2 Reference Url [This is example source code] git_trojan.py import json import base64 import sys import time import imp import random import threading import Queue import os from github3 import login trojan_id = "abc" trojan_config = "%s.json" % trojan_id data_path = "data/%s/" % trojan_id trojan_modules= [] task_queue = Queue.Queue() configured = False class GitImporter(object): def __init__(self): self.current_module_code = "" def find_module(self,fullname,path=None): if configured: print("[*] Attempting to retrieve %s" % fullname) new_library = get_file_contents("modules/%s" % fullname) if new_library is not None: self.current_module_code = base64.b64decode(new_library) return self return None def load_module(self,name): module = imp.new_module(name) exec self.current_module_code in module.__dict__ sys.modules[name] = module return module def connect_to_github(): gh = login(username="yourusername",password="password") repo = gh.repository("yourusername","chapter7") branch = repo.branch("master") return gh,repo,branch def get_file_contents(filepath): gh,repo,branch = connect_to_github() tree = branch.commit.commit.tree.recurse() for filename in tree.tree: if filepath in filename.path: print("[*] Found file %s" % filepath) blob = repo.blob(filename._json_data['sha']) return blob.content return None def get_trojan_config(): global configured config_json = get_file_contents(trojan_config) config = json.loads(base64.b64decode(config_json)) configured = True for task in config: if task['module'] not in sys.modules: exec("import %s" % task['module']) return config def store_module_result(data): gh,repo,branch = connect_to_github() remote_path = "data/%s/%d.data" %(trojan_id,random.randint(1000,100000)) repo.create_file(remote_path,"Commit message",base64.b64encode(data)) return def module_runner(module): task_queue.put(1) result = sys.modules[module].run() …
downvote count: 2
type: Question
score: 3
upvote count: 5
has title: what is this AttributeError: recurse? related black hat python chapter7 github command and control
tagged with: github-api
answer count: 1
has comment: http://stackoverflow.com/comment/88157598
tagged with: github
favorite count: 0
tagged with: linux
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88163026
tagged with: python

http://stackoverflow.com/a/50674639
score: 20
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/133967739
type: Answer
upvote count: 20
answers question: http://stackoverflow.com/q/50621832
has body: Finally I Understood how do I upload file to google drive using api. first you need to install python library which gives the methods to use drive api. installing the library: pip install google-api-python-client then code as below. from __future__ import print_function from apiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools from apiclient.http import MediaFileUpload,MediaIoBaseDownload import io # Setup the Drive v3 API SCOPES = 'https://www.googleapis.com/auth/drive.file' store = file.Storage('credentials.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) drive_service = build('drive', 'v3', http=creds.authorize(Http())) above code snippet is to create object/variable which allow you to get inside the drive with a right credential. here drive_service does that work. File uploading code is below here. def uploadFile(): file_metadata = { 'name': 'fileName_to_be_in_drive.txt', 'mimeType': '*/*' } media = MediaFileUpload('Filename_of_your_local_file.txt', mimetype='*/*', resumable=True) file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute() print ('File ID: ' + file.get('id')) The file ID is important because if you want to download the file from the drive you need the file ID.
has comment: http://stackoverflow.com/comment/113489148
accepted answer of: http://stackoverflow.com/q/50621832

http://stackoverflow.com/comment/88189112
comment on: http://stackoverflow.com/q/50589333
has text: Have you asked in https://stats.stackexchange.com/?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50689067
has comment: http://stackoverflow.com/comment/88388219
duplicate of: http://stackoverflow.com/q/6287092
type: Question
possible better answer: http://stackoverflow.com/a/50689233
answer count: 2
linked to: http://stackoverflow.com/q/6287092
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/88387886
has body: I have this payload that I wish to extract a field from: {"encrypted_sender_transaction_id":"514658451","donation_info":{"tid":321654658,"ppgf_donation_id":4654564,"pp_transaction_id":19446119405222584,"nonprofit_id":6454,"amount":1,"gross_amount":1,"currency_code":"USD","type":"U","party_id":"2313654","product_type":"DN","is_recurring":false,"transaction_time":"2018-06-04","donor_name":"Foo Bar","donor_email_address":"foo.bar@foobar.com","is_donor_sharing_contact":true,"product_description":"PayPal Donations with PPGF","partner_name":"PayPal","receiver_transaction_id":13214,"encrypted_transaction_id":"4564","receiver_account_number":"123","methodof_donation":"4001","encrypted_pptxn_id":"123","update":false},"payout_date":"2018-06-25","charity_type":"PPGF","charity_info":{"name":"Comic Relief Red Nose Day","address":{"line1":"123 Foobar Ave, 123th Floor","line2":"","city":"New York","state":"NY","postal_code":"123123","country_code":"US","phone":"123418","latitude":"123.45675876","longitude":"-7213.97493"},"state":"Confirmed","confirmation_date":"2016-04-19","logo_url":"https://pics.paypal.com/00/s/Mjg0ZDUwOWMtY2U3ZS00NjVhLWJkMDUtMGE2Y2RiZDIxODc4/file.JPG","mission_area":[{"id":1015,"name":"Philanthropy, Grants, Other","is_primary":true},{"id":1012,"name":"Human Services","is_primary":false}],"adhoc_ppgf":false,"mission":"Philanthropy, Grants, Other"},"payout_status":1,"isResult":true,"convertedpytdate":"Jun 25, 2018","convertedtransactdate":"Jun 4, 2018","transaction_id":"43934096XX104234C"} The field I wish to extract is "amount":1, the 1 value in particular. I know that regex is the obvious way to go here, but it's so confusing to me! Should I be searching the string and using str[:::] indices instead? (Also: I changed all the values in this example but it's the exact format).
has answer: http://stackoverflow.com/a/50689120
tagged with: python
tagged with: regex
favorite count: 0
tagged with: parsing
has title: How to extract a field from this payload with a regex?
downvote count: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50689120
has answer: http://stackoverflow.com/a/50689233
linked to: http://stackoverflow.com/q/12593411

http://stackoverflow.com/q/50645414
has body: i'm still learning scrapy and i am trying to use scrapy with scrapyd inside a Django Project. But i am noticing that the spider just wont enter the def(parse) import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule class NewsSpider(CrawlSpider): print("Start SPIDER") name = 'detik' allowed_domains = ['news.detik.com'] start_urls = ['https://news.detik.com/indeks/all/?date=02/28/2018'] def parse(self, response): print("SEARCH LINK") urls = response.xpath("//article/div/a/@href").extract() for url in urls: url = response.urljoin(url) yield scrapy.Request(url=url, callback=self.parse_detail) def parse_detail(self,response): print("SCRAPEEE") x = {} x['breadcrumbs'] = response.xpath("//div[@class='breadcrumb']/a/text()").extract() x['tanggal'] = response.xpath("//div[@class='date']/text()").extract_first() x['penulis'] = response.xpath("//div[@class='author']/text()").extract_first() x['judul'] = response.xpath("//h1/text()").extract_first() x['berita'] = response.xpath("normalize-space(//div[@class='detail_text'])").extract_first() x['tag'] = response.xpath("//div[@class='detail_tag']/a/text()").extract() x['url'] = response.request.url return x The print("Start Spider") is in the log but the print("Search Link") is not. i also have this kind of error [Launcher,3804/stderr] Unhandled error in Deferred: Please help. PS : When i run it outside the Django it work just fine Thank you
tagged with: scrapyd
upvote count: 2
has comment: http://stackoverflow.com/comment/88301791
tagged with: django
tagged with: scrapy
type: AnsweredQuestion
has title: Using scrapy with scrapyd in Django not entering def(parse)
has comment: http://stackoverflow.com/comment/88315257
type: Question
has comment: http://stackoverflow.com/comment/88301390
has answer: http://stackoverflow.com/a/50858549
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88307225
tagged with: python
score: 2
accepted answer: http://stackoverflow.com/a/50858549

http://stackoverflow.com/comment/88284205
has text: Thanks I'll try this out and let you know if it works
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50606625

http://stackoverflow.com/q/50673092
tagged with: django
tagged with: python
has body: I use the Django as my backend, when I register the user, there return the error message, that is:"A user with that username already exists". But how can I convert it to other language? if I use Korean or Spanish?
answer count: 0
has comment: http://stackoverflow.com/comment/88364257
has comment: http://stackoverflow.com/comment/88363657
type: Question
has comment: http://stackoverflow.com/comment/88356280
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/88356021
has title: Convert the Django traceback message to other language
score: 0
has comment: http://stackoverflow.com/comment/88356361
has comment: http://stackoverflow.com/comment/88360190
type: UnansweredQuestion

http://stackoverflow.com/comment/88251411
comment on: http://stackoverflow.com/a/50620661
has text: @MarkusMeskanen Sorry - yes - what I mean is that it's writeable in the sense that you can assign something to it but nothing changes
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50647167
accepted answer: http://stackoverflow.com/a/50647227
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50647577
tagged with: list
upvote count: 26
type: Question
has title: Stepping with multiple values while slicing an array in Python
score: 26
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/50647440
has answer: http://stackoverflow.com/a/50647247
has answer: http://stackoverflow.com/a/50649490
has answer: http://stackoverflow.com/a/50647203
has answer: http://stackoverflow.com/a/50647227
has comment: http://stackoverflow.com/comment/88318778
has answer: http://stackoverflow.com/a/50650184
answer count: 7
possible better answer: http://stackoverflow.com/a/50647203
favorite count: 0
has comment: http://stackoverflow.com/comment/88317849
has body: I am trying to get m values while stepping through every n elements of an array. For example, for m = 2 and n = 5, and given a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] I want to retrieve b = [1, 2, 6, 7] Is there a way to do this using slicing? I can do this using a nested list comprehension, but I was wondering if there was a way to do this using the indices only. For reference, the list comprehension way is: b = [k for j in [a[i:i+2] for i in range(0,len(a),5)] for k in j]
tagged with: python

http://stackoverflow.com/comment/88159150
comment on: http://stackoverflow.com/a/50574778
type: Comment
has text: @ donkopotamus Thank you!
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88349444
comment on: http://stackoverflow.com/a/50669602
score: 0
type: AnswerComment
type: Comment
has text: Ok, so what is the correct split of the first 3-4 columns in the line starting with 3?

http://stackoverflow.com/q/50664853
tagged with: python
has comment: http://stackoverflow.com/comment/88343862
score: 2
has comment: http://stackoverflow.com/comment/88342876
answer count: 0
upvote count: 2
type: UnansweredQuestion
has title: How to implement __repr__ for a C# class to be used in python.net?
type: Question
tagged with: c#
has comment: http://stackoverflow.com/comment/88343067
has comment: http://stackoverflow.com/comment/88344727
tagged with: python.net
tagged with: pythonnet
downvote count: 0
tagged with: .net
has body: I have pythonnet v 2.3.0 installed. I have a C# class library which I use in Python. I have a Point class (a code snippet): public Point(double x, double y) { this.x = x; this.y = y; } public override string ToString() { return $"Point({x}, {y})"; } When I work with this class library in Python (in Python shell): &gt;&gt;&gt; p1 = Point(10,15) &gt;&gt;&gt; p1 &lt;Geometry.Point object at 0x000000000558F828&gt; &gt;&gt;&gt; str(p1) 'Point(10, 15)' Because I override the ToString(), when I run str(p1) I see my custom view of the object. However, when I just access a variable p1, then it goes to the __repr__() method under the hood which gives me ugly &lt;Geometry.Point object at 0x000000000558F828&gt;. Is there a method in C# class that is possible to override so that pythonnet would use that method when getting the __repr__? https://github.com/pythonnet/pythonnet/issues/680
favorite count: 0
has comment: http://stackoverflow.com/comment/88343196

http://stackoverflow.com/a/50662783
has comment: http://stackoverflow.com/comment/88335749
has body: df.values.max() - df.values.min() calculates the scalar difference between the highest &amp; lowest values in the data frame. for this data frame, this gives the output: 2.0412909999999997
has comment: http://stackoverflow.com/comment/88335730
has comment: http://stackoverflow.com/comment/88335720
upvote count: 1
has comment: http://stackoverflow.com/comment/88335727
has comment: http://stackoverflow.com/comment/88335955
answers question: http://stackoverflow.com/q/50662745
type: Answer
has comment: http://stackoverflow.com/comment/88335755
downvote count: 0
score: 1

http://stackoverflow.com/a/50671363
answers question: http://stackoverflow.com/q/50664932
type: Answer
upvote count: 1
score: 1
downvote count: 0
has body: The output of "your" model is not at all related with anything regarding VGG, caffe, etc. It's "you" who define it when you create your model. So, if your model's outputs must be between 0 and 255, one possibility is to have its last layers as: Activation('sigmoid') Lambda(lambda x: x*255) You'd then need the preprocess_input function inside perceptual loss: def perceptual_loss(y_true, y_pred): y_true = preprocess_input(y_true) y_pred = preprocess_input(y_pred) vgg = VGG16(include_top=False, weights='imagenet', input_shape=(resize_size, resize_size, 3)) loss_model = Model(inputs=vgg.input, outputs=vgg.get_layer('block3_conv3').output) loss_model.trainable = False return K.mean(K.square(loss_model(y_true) - loss_model(y_pred))) Another possibility is to postprocess your model's output. (But again, the range of the output is totally defined by you).

http://stackoverflow.com/comment/88151622
type: QuestionComment
has text: Ok, can you give me an example of how to create more objects of the same kind? i don't want it to be something like instance1= myClass, instance2= myClass, instead i want to use a function to create more objects when called
comment on: http://stackoverflow.com/q/50568880
score: 0
type: Comment

http://stackoverflow.com/comment/88221230
comment on: http://stackoverflow.com/q/50605601
score: 0
type: Comment
type: QuestionComment
has text: It may not be what OP wants, but it is what this question asks for. Unless it is edited to ask for the actual problem (showing in how far the linked solution doesn't help) I would agree it's a duplicate.

http://stackoverflow.com/a/50585113
has comment: http://stackoverflow.com/comment/88181051
accepted answer of: http://stackoverflow.com/q/50584703
has comment: http://stackoverflow.com/comment/88180628
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88180240
downvote count: 0
has comment: http://stackoverflow.com/comment/88179535
type: Answer
has comment: http://stackoverflow.com/comment/88179655
upvote count: 3
has comment: http://stackoverflow.com/comment/88180552
has comment: http://stackoverflow.com/comment/88180214
answers question: http://stackoverflow.com/q/50584703
score: 3
has comment: http://stackoverflow.com/comment/88180930
has body: You do not need to iterate all the tags if you just need to update a single tag. Try: import xml.etree.ElementTree as ET tree = ET.parse(filename) root = tree.getroot() for AAA in root.findall('AAA'): if AAA.find('CCC'): BBB = AAA.find('CCC').find('BBB') BBB.text = '33333' + BBB.text tree.write('C:\\test\\python test\\output.xml')

http://stackoverflow.com/q/50616152
accepted answer: http://stackoverflow.com/a/50616274
type: AnsweredQuestion
tagged with: queue
type: Question
has title: Is Python's Queue.PriorityQueue not automatically sorted?
answer count: 2
has body: I am new to using queues in Python and I recently started working with the PriorityQueue. I was expecting that elements would be inserted in the queue according to the a priority number. That is, if I did something like: from Queue import PriorityQueue q = PriorityQueue() q.put((1, '1')) q.put((4, 'last')) q.put((2, '2')) q.put((3, '3')) print q.queue I was expecting this output: [(1, '1'), (2, '2'), (3, '3'), (4, 'last')]. Instead I get: [(1, '1'), (3, '3'), (2, '2'), (4, 'last')] However, if I get the elements out of the queue by something like: while not q.empty(): item = q.get() print item I do get the output I would expect: (1, '1') (2, '2') (3, '3') (4, 'last') I was trying to debug something by printing the queue at some points and noticed the elements were not in the order I would expect. Unless I missed it, Queue's docs don't mention anything about sorting. Was I just wrong to expect it to be sorted? Could it be simply not be implemented that way for efficiency reasons?
downvote count: 0
tagged with: python-2.7
tagged with: priority-queue
has answer: http://stackoverflow.com/a/50616274
tagged with: python
upvote count: 6
favorite count: 0
has answer: http://stackoverflow.com/a/50616270
score: 6
possible better answer: http://stackoverflow.com/a/50616270

http://stackoverflow.com/q/50626710
duplicate of: http://stackoverflow.com/q/36894191
has body: For a research project I am working on, I need to generate a set of random (or pseudo-random) data (say 10,000 datum) with the following parameters: Maximum value = 35; Minimum Value = 1.5; Mean = 9.87; Standard Deviation = 3.1; Now clearly this distribution will look somewhat like that generated with scipy.stats.maxwell.rvs(locs=1.5,scale=3.1) However this does not give the necessary mean or max value. Is there an a possible solution to this?
tagged with: scipy
type: Question
linked to: http://stackoverflow.com/q/36894191
duplicate of: http://stackoverflow.com/q/27831923
has answer: http://stackoverflow.com/a/50628583
accepted answer: http://stackoverflow.com/a/50628583
tagged with: statistics
upvote count: 4
tagged with: random
answer count: 1
has title: Generating random numbers with predefined mean, std, min and max
favorite count: 0
has comment: http://stackoverflow.com/comment/88266934
linked to: http://stackoverflow.com/q/27831923
has comment: http://stackoverflow.com/comment/88263447
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 2

http://stackoverflow.com/comment/88321740
comment on: http://stackoverflow.com/a/50652770
type: Comment
has text: @ChemaSarmiento yes 2M rows is pretty long for a loop for! check my EDIT, it's a more general solution but don't know how efficient it is on such a large df
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88389729
score: 0
type: Comment
has text: Thanks for the tip, I've got it working now! I figured it was something like that, but I wasn't quite sure how to fix the problem.
comment on: http://stackoverflow.com/a/50672475
type: AnswerComment

http://stackoverflow.com/a/50606172
type: Answer
has comment: http://stackoverflow.com/comment/88222406
has body: You should use the storage-agnostic Storage.exists() method. The storage object should be available on the FieldFile itself, so something like return self.file.storage.exists(self.file.name) should do the trick.
answers question: http://stackoverflow.com/q/50606068
downvote count: 1
accepted answer of: http://stackoverflow.com/q/50606068
upvote count: 36
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/135737010
score: 35

http://stackoverflow.com/comment/88159960
type: AnswerComment
has text: Have you checked this https://stackoverflow.com/questions/20986631/how-can-i-scroll-a-web-page-using-selenium-webdriver-in-python?
comment on: http://stackoverflow.com/a/50570338
score: 0
type: Comment

http://stackoverflow.com/q/50615078
has body: I'm trying to use the Airbrake logger in a Django project following the steps described in https://github.com/airbrake/pybrake#django-integration. I've configured my LOGGING setting like so: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'airbrake': { 'level': 'ERROR', 'class': 'pybrake.LoggingHandler', } }, 'loggers': { 'lucy_web': { 'handlers': ['airbrake'], 'level': 'ERROR', 'propagate': True, } } } Then, in a particular file in the lucy_web hierarchy called lucy_web/lib/session_recommendation.py, I have the following test function: import logging logger = logging.getLogger(__name__) def log_something(): logger.error("Logging something...") However, if I try to call this function from the Django shell, pybrake itself logs an error: strconv.ParseInt: parsing "None": invalid syntax Here is the full sequence of commands: (venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ python manage.py shell Python 3.6.4 (v3.6.4:d48ecebad5, Dec 18 2017, 21:07:28) Type 'copyright', 'credits' or 'license' for more information IPython 6.3.1 -- An enhanced Interactive Python. Type '?' for help. In [1]: from lucy_web.lib.session_recommendation import * In [2]: log_something() In [3]: 2018-05-30 17:25:32,201 - pybrake - ERROR - strconv.ParseInt: parsing "None": invalid syntax It would appear from https://golang.org/pkg/strconv/#ParseInt that strconv.ParseInt is actually a built-in function of the Go language, so I don't understand why pybrake, which is a Python package, is throwing this error, or how to debug it. Can anyone explain this error?
tagged with: go
answer count: 1
favorite count: 0
tagged with: airbrake
tagged with: django
tagged with: python
tagged with: logging
has answer: http://stackoverflow.com/a/50615756
type: AnsweredQuestion
type: Question
upvote count: 4
has title: Airbrake throwing error "pybrake - ERROR - strconv.ParseInt: parsing "None": invalid syntax"
downvote count: 0
accepted answer: http://stackoverflow.com/a/50615756
score: 4

http://stackoverflow.com/comment/88095727
type: QuestionComment
has text: @cdarke To call it datetime might also not be the best idea, when you import the module `datetime` :)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50542195

http://stackoverflow.com/a/74588729
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/50624003
downvote count: 0
type: Answer
has body: You don't need the ehlo call. These days, you do need an app password with Gmail. And crucially, you need the right server address. I stupidly copied smtp.google.com from some bad instructions, and the call hung. Changing to smtp.gmail.com fixed it. Duh.

http://stackoverflow.com/a/50614402
has comment: http://stackoverflow.com/comment/88238642
score: 0
answers question: http://stackoverflow.com/q/50614310
type: Answer
has body: Another way to this: df[(df.duplicated(subset=['subcase','elm_id']))&amp;(df['cid']&gt;1)] case_id cid elm_id fx fy fz 2 1050 2 101 98.8 798.3 948.3 3 1050 2 102 158.5 452.0 523.9 6 1051 2 101 333.4 526.7 890.7 7 1051 2 102 104.2 119.4 422.1

http://stackoverflow.com/a/50626582
type: AcceptedAnswer
has body: I think you're looking for this: &gt;&gt;&gt; data.plot(x="Time") However, to achieve this, I had to reformat your data.csv file to replace white spaces with commas, as it is the default separator in a Comma Separated Values file. Maybe your original file is tabulated and in this case, your need to specify sep='\t' to the read_csv() call.
has comment: http://stackoverflow.com/comment/88263599
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50626458
has comment: http://stackoverflow.com/comment/88263366
accepted answer of: http://stackoverflow.com/q/50626458

http://stackoverflow.com/q/50664769
answer count: 1
has body: I have written a function that scans a list of strings by index for regex matches in the current and next two indexes of the list. If a match is found across three indexes, those elements in the list are joined. import re from nltk.tokenize import MWETokenizer s = ['Here','be', 'dragons', 'Captain', '23', 'March', '2018', 'and', 'Oct', '22', '2018'] pattern = [r'\d{2}|[a-zA-Z]{3,5}', r'\d{2}|[a-zA-Z]{3,5}', r'\d{4}'] def un_tokenize(pattern, sep, toks): tokenizer = MWETokenizer([], separator=sep) for i in list(range(0, len(toks)-len(pattern)+1)): if bool(re.match(pattern[0], toks[i])) and \ bool(re.match(pattern[1], toks[i+1])) and \ bool(re.match(pattern[2], toks[i+2])): tup = (toks[i], toks[i+1], toks[i+2]) tokenizer.add_mwe(tup) return tokenizer.tokenize(toks) print(un_tokenize(pattern, '+', s)) which correctly returns ['Here', 'be', 'dragons', 'Captain', '23+March+2018', 'and', 'Oct+22+2018'] I want to know, 1) How can I change the if statement to include a variable number of 'and's, so that I can put in a pattern of 2 regexes or 4 regexes etc.? 2) I am sure this is not the most pythonic way of doing this, so I other methods are welcome.
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50664891
accepted answer: http://stackoverflow.com/a/50664891
tagged with: python
tagged with: regex
type: AnsweredQuestion
type: Question
tagged with: function
has title: How to change a function based on the length of an input variable
score: 0

http://stackoverflow.com/comment/88112838
type: Comment
type: QuestionComment
has text: @AyodhyankitPaul tuple has an order and a set doesn't. Therefore, the function tuple({0,1,2}) might return (0,1,2), but also (0,2,1). My test could just be because of some implementation, but as long as it is not documented somewhere i have no guarantee that this happens for truly all cases (now and in future versions, unless changelogs state different)
score: 0
comment on: http://stackoverflow.com/q/50550887

http://stackoverflow.com/comment/88277537
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/50633643
has text: `__int__` is not `__init__`.
type: Comment

http://stackoverflow.com/comment/88410560
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50695038
has text: @Chris_Rands, I think I make my question detailed.

http://stackoverflow.com/comment/88260459
comment on: http://stackoverflow.com/a/50623608
score: 0
type: Comment
has text: Thank you. I made a mistake while asking the question and didnt indicate that also needed combinations like 2,1,1 where the 1st number can be greater than the rest. I don't know if this can be achieved with itertools, but the answer provided by Yakym worked for what I needed.
type: AnswerComment

http://stackoverflow.com/q/50690683
has title: basemap set_bad() for Nan values
type: Question
tagged with: contourf
has comment: http://stackoverflow.com/comment/88393150
score: 0
tagged with: raster
tagged with: matplotlib-basemap
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88420636
has body: I have tried to use numpy masked array and basemap module to plot raster data with no-data values. I defined a color map as cmap and then used cmap.set_bad(color='grey') to set no-data value to color gray. I then use contourf(...,cmap=cmap) to plot the raster, however, the no-data is still shown as white color. I have been searching a lot of examples of "set_bad", it looks like it works fine for imshow() function. I wonder does anyone have any experience using contourf and set_bad to show the raster images with nodata values? Thanks a lot for your help.
tagged with: python

http://stackoverflow.com/comment/88169064
comment on: http://stackoverflow.com/a/50579722
has text: @PetPan Yes, it is the most efficient solution here.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88363177
score: 1
type: Comment
type: QuestionComment
has text: What is Guidewire Software? If it is a third party API/app contact with their customer service.
comment on: http://stackoverflow.com/q/50676656

http://stackoverflow.com/a/50631576
score: 0
has body: You will need a variable number of outputs which would require a recurrent network on the prediction side. Let's try building one on the existing network: # first we'll add an extra input telling how many outputs we need num_outs = Input(shape=(1,), dtype='int') # ... continuing from answer = LSTM(32)(answer) # (samples, 32) # answer is your encoded context-query, we will decode it into a sequence answers = RepeatVector(num_outs[0])(answer) # (samples, num_outs, 32) # Another RNN to give us decoding (optional) answers = LSTM(32, return_sequences=True)(answers) # note return_sequences answers = TimeDistributed(Dense(vocab_size, activation='softmax'))(answers) # we have (samples, num_outs, vocab_size) so num_outs words # ... Now your targets have to be 3D shape as well. Important, you have to append a end-of-answer token to every answer so you know when to stop at prediction time. Equally, you would pad the number of answers within a batch to get a tensor after end-of-answer token. Now at prediction time, you can ask for 10 words and chop words after end-of-answer token, similar to how machine translation is done using seq2seq models. For reference, have a look at Dynamic Memory Networks.
type: Answer
has comment: http://stackoverflow.com/comment/88279926
answers question: http://stackoverflow.com/q/50630123
has comment: http://stackoverflow.com/comment/88456840
has comment: http://stackoverflow.com/comment/88457544
has comment: http://stackoverflow.com/comment/88461016
has comment: http://stackoverflow.com/comment/88290082

http://stackoverflow.com/q/50687879
has comment: http://stackoverflow.com/comment/88386041
has comment: http://stackoverflow.com/comment/88385766
has comment: http://stackoverflow.com/comment/88386109
has comment: http://stackoverflow.com/comment/88415280
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88386819
has title: Variables inside clean() method aren't saved in Django
accepted answer: http://stackoverflow.com/a/50891441
has comment: http://stackoverflow.com/comment/88385895
type: AnsweredQuestion
has body: In models.py I have a model with custom clean() method. However, any variables I save in it aren't stored. If I try to save the variable outside of the clean() method, everything works well. class MenuItem(SortableMixin): item_internal = models.ForeignKey(Page, on_delete=models.CASCADE, blank=True, null=True) item_external = models.CharField(max_length=500000, blank=True, null=True) def clean(self): if self.item_external is not None and self.item_internal is not None: raise ValidationError('Error') elif self.item_external is None and self.item_internal is None: raise ValidationError('Error') else: if self.item_external is not None: self.item_link = self.item_external elif self.item_internal is not None: self.item_link = '/' + self.item_internal.title_text.replace(' ', '%20') Anything inside item_link is not saved. Why? How to fix it?
type: Question
has comment: http://stackoverflow.com/comment/88385723
has comment: http://stackoverflow.com/comment/88386133
tagged with: django-models
has comment: http://stackoverflow.com/comment/88386220
has comment: http://stackoverflow.com/comment/88385708
score: 0
has answer: http://stackoverflow.com/a/50891441
answer count: 1
has comment: http://stackoverflow.com/comment/88385426

http://stackoverflow.com/q/50559078
tagged with: python
has answer: http://stackoverflow.com/a/50559079
has answer: http://stackoverflow.com/a/50672169
possible better answer: http://stackoverflow.com/a/50559321
upvote count: 74
answer count: 9
has title: Generating random dates within a given range in pandas
has answer: http://stackoverflow.com/a/50668285
has answer: http://stackoverflow.com/a/50724574
has answer: http://stackoverflow.com/a/76509771
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/50559136
favorite count: 0
tagged with: random
type: Question
tagged with: pandas
score: 74
tagged with: datetime
accepted answer: http://stackoverflow.com/a/50668285
linked to: http://stackoverflow.com/q/49522397
has body: This is a self-answered post. A common problem is to randomly generate dates between a given start and end date. There are two cases to consider: random dates with a time component, and random dates without time For example, given some start date 2015-01-01 and an end date 2018-01-01, how can I sample N random dates between this range using pandas?
has answer: http://stackoverflow.com/a/53214155
linked to: http://stackoverflow.com/q/553303
has answer: http://stackoverflow.com/a/50707178
has answer: http://stackoverflow.com/a/50559321

http://stackoverflow.com/a/50614447
score: 0
answers question: http://stackoverflow.com/q/50614263
has comment: http://stackoverflow.com/comment/88238991
has comment: http://stackoverflow.com/comment/88238925
has comment: http://stackoverflow.com/comment/88239114
has comment: http://stackoverflow.com/comment/88238859
has comment: http://stackoverflow.com/comment/88239284
has body: Hi use this regex. https:(.*?)(&gt;|") You can test your regex online in this link I test your text with my regex and got 4 matchs.
type: Answer
has comment: http://stackoverflow.com/comment/88239151
has comment: http://stackoverflow.com/comment/88239384

http://stackoverflow.com/a/50556551
type: Answer
answers question: http://stackoverflow.com/q/50556341
has body: To access name and coordinates by index, use a list of tuples. Note that you need to name these explicitly. You should preferably avoid this step by using a list of tuples to store your name-coordinate pairs from the beginning. To access by name, use a dictionary. i, j, k, l = (1953.2343076828638, 730.0513627132909),\ (1069.4232335022705, 5882.057343563125),\ (2212.5767664977293, 3335.942656436875),\ (4386.765692317136, 1318.948637286709) K = [(name, var) for name, var in zip('ijkl', (i, j, k, l))] ## ACCESS BY INDEX name_coord = K[0] # ('i', (1953.2343076828638, 730.0513627132909)) name = K[0][0] # 'i' coord = K[0][1] # (1953.2343076828638, 730.0513627132909) ## ACCESS BY NAME d = dict(K) coord = d['i'] # (1953.2343076828638, 730.0513627132909)
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/50556341
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50550639
tagged with: beautifulsoup
tagged with: lxml
tagged with: http://stackoverflow.com/tag/csv
has title: Scraping HTML table in CSV file using python in specific format
tagged with: python
favorite count: 0
possible better answer: http://stackoverflow.com/a/50553396
score: -3
type: AnsweredQuestion
downvote count: 3
has answer: http://stackoverflow.com/a/50554326
accepted answer: http://stackoverflow.com/a/50554326
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50553396
upvote count: 0
has body: I want to extract below HTML table content from a link in specific format. HTML Code on the web page: name brand description abcd abcd123 abcd 123 (1g) efgh efgh456 efgh 456 (2g) ijkl ijkl789 ijkl 789 (3g) Required output format in CSV file like below: Link,name,brand,description http://abcd.com,abcd,abcd123,abcd 123 (1g) http://efgh.com,efgh,efgh456,efgh 456 (2g) http://ijkl.com,ijkl,ijkl789,ijkl 789 (3g) Below is my code: rows = doc.xpath("//table") for tr in rows: tds = tr.xpath("//td") for td in tds: Link = td.xpath("//td[1]/a/@href") name = td.xpath("//td[1]//text()") brand = td.xpath("//td[2]//text()") description = td.xpath("//td[3]//text()") results = [] results.append(Link) results.append(name) results.append(brand) results.append(description) for result in results: writer.writerow(result) Here, I can't work out how to get the data in above specific format in CSV.

http://stackoverflow.com/q/50565297
tagged with: file
upvote count: 1
has answer: http://stackoverflow.com/a/50567967
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88141128
score: -1
has title: Write few lines just before the last line in a large file using Python
type: Question
linked to: http://stackoverflow.com/q/620367
answer count: 1
accepted answer: http://stackoverflow.com/a/50567967
has comment: http://stackoverflow.com/comment/88141141
favorite count: 0
tagged with: io
tagged with: python
has body: I have a very large file(5 MB) and I need to add few lines just before the last line. e.g. file.txt text-1 text-2 text-3 text-10 After adding few lines just before the last line. file.txt text-1 text-2 text-3 few-text-1 few-text-2 text-10 What are best ways to do it in python.
downvote count: 2

http://stackoverflow.com/comment/88104214
has text: Do you have a question?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50546760
score: 0

http://stackoverflow.com/q/50688737
type: Question
has body: May be it's stupid question, but I'm begginer in django. I have a problem with error: "PartyNumView() missing 1 required positional argument: 'pk'" views.py: from description.models import Part from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.shortcuts import render_to_response, get_object_or_404 def PartyNumView(request, pk, page_number = 1): all_parties = Part.objects.all() current_page = Paginator(all_parties, 10) try: context = current_page.page(page_number) except PageNotAnInteger: context = current_page.page(1) except EmptyPage: context = current_page.page(current_page.num_pages) onePart = get_object_or_404(Part, pk = pk) return render_to_response('part_list.html', {'PartyNum': context, 'onePart': onePart}) urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^parties/(\d+)/$', PartyNumView), url(r'^parties', PartyNumView), url(r'parties/(?P<pk>[\d]+)$', PartyNumView, name='onePart'), url(r'^main/', TemplateView.as_view(template_name='main.html')), #static html url(r'^measures/', TemplateView.as_view(template_name='IcDesc.html')), #static html ] And a little bit of part_list.html: {% for object in PartyNum %} {{ forloop.counter }} {{ object.Party_number }} {{ object.Film }} {{ object.Thick }} {{ object.Critical_temperature }} {{ object.R_s }} {% endfor %} In Models.py I have a class Part(models.Model) Help me please find a mistake.
possible better answer: http://stackoverflow.com/a/50688905
has answer: http://stackoverflow.com/a/50688905
has answer: http://stackoverflow.com/a/50688899
accepted answer: http://stackoverflow.com/a/50688899
has answer: http://stackoverflow.com/a/50689019
score: 0
answer count: 3
tagged with: python
has title: Missing 1 required positional argument - issue
tagged with: django
type: AnsweredQuestion

http://stackoverflow.com/comment/88143988
type: Comment
score: 2
has text: Launch the script at startup and put `sleep 20` as your first command.
type: QuestionComment
comment on: http://stackoverflow.com/q/50566993

http://stackoverflow.com/q/50610405
favorite count: 0
type: UnansweredQuestion
has title: Creating a new column with ifelse condition (python)
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/88230603
has body: I am trying to create a new column 'New' that: 1) if 'y' values is different from zero, give me 'y' 2) if 'y' is equal zero, give me 'yhat' value ds y ds yhat 0 1999-03-05 45.0 1999-03-05 37.168417 1 1999-03-06 45.0 1999-03-06 37.109215 2 1999-03-07 45.0 1999-03-07 37.049726 3 1999-03-08 45.0 1999-03-08 36.987036 4 1999-03-09 45.0 1999-03-09 36.926852 5 1999-03-10 45.0 1999-03-10 36.864715 6 1999-03-11 45.0 1999-03-11 36.771622 7 1999-03-12 45.0 1999-03-12 36.712117 8 1999-03-13 45.0 1999-03-13 36.646144 9 1999-03-14 45.0 1999-03-14 36.578244 ... ... ... ... ... 7356 NaT 0 2019-04-25 8.321119 7357 NaT 0 2019-04-26 8.315796 In order to do that, I am using this function: df['New'] = np.where(df['y']!=0, df['y'], df['yhat']) But I get an error saying: KeyError: 'y'
score: -1
type: Question
tagged with: numpy
tagged with: if-statement
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88230791
has answer: http://stackoverflow.com/a/50610502
has comment: http://stackoverflow.com/comment/88230615

http://stackoverflow.com/q/50686655
downvote count: 1
has answer: http://stackoverflow.com/a/50686688
favorite count: 0
has answer: http://stackoverflow.com/a/50686740
tagged with: python
type: AnsweredQuestion
has body: I have an input file with sentences like this: I like apples My mother is called Anna. I transfer these sentences to a list and then I want to remove words that have the length &lt; 3. I've tried this: with open("fis.txt", "r", encoding="utf8") as f: lst = [w.lower() for w in f.readlines() if len(w) &gt;= 3] print(lst) but it gives me ['i like apples', 'my mother is called anna.'] and I want to obtain ['like apples', 'mother called anna.'] What seems to be the problem here?
has comment: http://stackoverflow.com/comment/88383310
tagged with: file
possible better answer: http://stackoverflow.com/a/50686688
type: Question
score: 1
has answer: http://stackoverflow.com/a/50686720
accepted answer: http://stackoverflow.com/a/50686720
upvote count: 2
has title: Remove words form list sentences that have length < 3
answer count: 3

http://stackoverflow.com/q/50696446
tagged with: python-3.x
type: Question
accepted answer: http://stackoverflow.com/a/50696529
has comment: http://stackoverflow.com/comment/88402147
tagged with: python
has comment: http://stackoverflow.com/comment/88402061
upvote count: 2
has comment: http://stackoverflow.com/comment/88402203
answer count: 1
downvote count: 1
has title: What is the side effect of importing something inside a loop in python?
linked to: http://stackoverflow.com/q/296036
has body: I have been maintaining a project. I found that someone wrote a function where he has made an import statement inside a for loop like so for obj in obj_list: from Levenshtein._levenshtein import distance if distance(obj.title, "some string") &lt;= 2: do something I assume that importing something inside a for loop causes unnecessary instruction execution. Hence, I want to refactor the code. But to do that I need a rationale to support my assumption that importing inside a for loop is not a good practice. Is my assumption correct?
has comment: http://stackoverflow.com/comment/88402069
tagged with: python-import
tagged with: for-loop
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50696529
score: 1
favorite count: 0

http://stackoverflow.com/q/50608723
has body: This question concerns processing a large dataset of observations in time. Later-stage work requires a common time step between observations, but in practice, the raw data often misses timesteps. Given a time step (say 1 second), the objective of this question is, within the full range observed in the raw data, to add rows corresponding to any missing timesteps using Pyspark. I've achieved this by: Generating a new sequence of time values using the min and max observed times and the assumed common time step in Python Creating a new Spark dataframe from this sequence, and joining this onto the raw data. My question is whether there is a more efficient or natural way to solve this problem in Pyspark (or if not whether there are any obvious improvements to my approach)? I'm specifically interested in whether this can be solved efficiently in Pyspark as opposed to in Spark with code in Java as in this question. I've detailed my solution, as well as setup and creation of reproducible test data below. My solution spark = SparkSession \ .builder \ .appName("Spark StackOverflow Test") \ .getOrCreate() df = spark.read\ .options(header=True, inferSchema=True)\ .csv('test_data.csv') # find min and max observed times after timesteps have been subsampled df.createOrReplaceTempView('test_view') tmin = spark.sql('select min(date) from test_view').collect()[0]['min(date)'] tmax = spark.sql('select max(date) from test_view').collect()[0]['max(date)'] # create full second-by-second index new_date_index = takewhile(lambda x: x &lt;= tmax, date_seq_generator(tmin, datetime.timedelta(seconds=1))) # create Spark dataframe for new time index index_schema = StructType([StructField("date", StringType())]) time_rdd = sc.parallelize([datetime.datetime.strftime(t, '%Y-%m-%d %H:%M:%S') for t in new_date_index]) df_dates = spark.createDataFrame(time_rdd.map(lambda s: s.split(',')), schema=index_schema) # cast new index type from string to timestamp df_dates = df_dates.withColumn("date", df_dates…
tagged with: pyspark
tagged with: apache-spark
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/55230052
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/42411184
score: 2
upvote count: 2
has title: Reindexing (adding rows) in Pyspark at scale
type: Question
has comment: http://stackoverflow.com/comment/88227711
tagged with: apache-spark-sql

http://stackoverflow.com/q/50660109
accepted answer: http://stackoverflow.com/a/50661253
has body: I am trying to solve a question on graphs. However, a really strange error is happening while I try to build the adjacency matrix. This is the task: This is the input in an easy copy/paste format: 4 4 1 2 3 2 4 3 1 4 1 4 These are the steps so far that I did trying to solve the problem: Read the input data Make edges like a pair (tuple) of two vertexes, for instance, (v1, v2) express that there is an edge between vertex 1 and 2. Based on the "n" number of Edges, I created a "nxn" quadratic matrix. I filled all the items as 0s. On the next step, I try to change "0" to "1" if there is a connection between vertexes. Observation: I created two functions. One to create a adjacency matrix to be filled. Another, named fill_matrix to change zeros (0) to ones (1) when appropriate. Now is where the problem appears. I tried to iterate over my edges and change the Adjacency Matrix. However, a bizarre thing happens. The same function, with the same parameters, provide different outputs. I really don't understand why this is happening! This is my code so far: #Uses python3 import sys input = sys.stdin.read() #print ("input", input) data = list(map (int, input.split())) #print ("data", data) nodes_num = data[0] #print ("number of nodes", nodes_num) edges_num = data[1] #print ("number of edges", edges_num) data = data[2:] #print ("data withou initial numbers", data) vertex_start = data[-2] #print ("initial node", vertex_start) vertex_end = data[-1] #print ("final node", vertex_end) data_edges = data[0:len(data)-2] #print ("list with the relation of the edges", data_edges) # this function cnverts the list of edges in appropriate pairs as tupples def make_edge_pairs(edges_list): edges_list_even = edges_list[::2] edges_list_odd = edges_list[1::2] # using zip function to interlacte odds and events as proper pairs edges_tuples_objects = zip(edges_list_even,edges_list_odd) edges_list_tuplas = [ ] for pair in edges_tuples_objects: edges_list_tuplas.append(pair) return edges_list_tuplas de…
has title: Correctly changing the values of an adjacency matrix to represent an undirect graph
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/50661253
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: adjacency-matrix
type: Question
tagged with: graph-theory

http://stackoverflow.com/comment/88218664
type: AnswerComment
type: Comment
has text: Okay, thank you. I will look into it again and try to solve with the new information I have now.
comment on: http://stackoverflow.com/a/50602026
score: 0

http://stackoverflow.com/a/50644424
upvote count: 1
downvote count: 0
type: Answer
has body: Complete fix : # ctc decoder flattened_input_x_width = keras.backend.reshape(input_x_widths, (-1,)) top_k_decoded, _ = keras.backend.ctc_decode(y_pred, flattened_input_x_width) self.decoder = keras.backend.function([input_x, flattened_input_x_width], [top_k_decoded[0]]) # decoded_sequences = self.decoder([input_x, flattened_input_x_width])
answers question: http://stackoverflow.com/q/50642676
score: 1

http://stackoverflow.com/q/50547593
downvote count: 0
tagged with: pyqt5
type: Question
score: 5
answer count: 2
tagged with: pyqt
favorite count: 0
tagged with: python-3.x
upvote count: 5
has answer: http://stackoverflow.com/a/79018526
has body: I want my PyQt5 program to be frameless and always be on top of the screen. When I use the WindowStayOnTopHint it works fine, but when I use it with the FramelessWindowHint it becomes frameless, but does not stay on top of the screen. After doing some research I found this, and it said to try to use setMask, but I could not get it to work. Here is my code: import sys from PyQt5.QtCore import Qt from PyQt5.QtGui import QFont from PyQt5.QtWidgets import QApplication, QLabel class Invisible(QLabel): def __init__(self, **kwargs): super().__init__(**kwargs) self.__press_pos = None self.initUI() def initUI(self): self.setWindowFlags(Qt.WindowStaysOnTopHint) self.setMask() #This is where I use the setMask function, but it raises an error self.setAttribute(Qt.WA_TranslucentBackground) self.setText("Drag me...") self.setFont(QFont("Times", 50, QFont.Bold)) self.adjustSize() self.move(QApplication.instance().desktop().screen().rect().center() - self.rect().center()) def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.__press_pos = event.pos() def mouseReleaseEvent(self, event): if event.button() == Qt.LeftButton: self.__press_pos = None def mouseMoveEvent(self, event): if self.__press_pos: self.move(self.pos() + (event.pos() - self.__press_pos)) def main(): app = QApplication(sys.argv) w = Invisible() w.show() return app.exec_() if __name__ == '__main__': sys.exit(main()) This code gives me the error: TypeError: arguments did not match any overloaded call: setMask(self, QBitmap): not enough arguments setMask(self, QRegion): not enough arguments It is asking for more arguments, but when I give it more arguments it says that there are too many arguments. How do I fix this?
has title: FramelessWindowHint & WindowStaysOnTopHint won't work
tagged with: python
has answer: http://stackoverflow.com/a/50547895
accepted answer: http://stackoverflow.com/a/50547895
possible better answer: http://stackoverflow.com/a/79018526
type: AnsweredQuestion

http://stackoverflow.com/comment/88149473
has text: It seems that you sent photo message in your code but the question ask about upload file
type: AnswerComment
comment on: http://stackoverflow.com/a/50569711
type: Comment
score: 0

http://stackoverflow.com/a/50636663
accepted answer of: http://stackoverflow.com/q/50636635
has comment: http://stackoverflow.com/comment/88283495
has comment: http://stackoverflow.com/comment/88283622
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88283427
has comment: http://stackoverflow.com/comment/88283271
upvote count: 2
type: Answer
has body: If use DataFrameGroupBy.resample is necessary DatetimeIndex set before groupby, also apply is not necessary, faster is resample sum, then divide final Series by 10 and then use np.sqrt: df = df.set_index(["date"]).sort_index() df1 = (np.sqrt(df.groupby("id")["val"] .resample(rule = "M", closed = "right", label = "right") .sum() .div(10))) print (df1) id date 1 2000-01-31 4.582576 2 2000-01-31 4.743416 Name: val, dtype: float64
score: 2
has comment: http://stackoverflow.com/comment/88283557
has comment: http://stackoverflow.com/comment/88283467
answers question: http://stackoverflow.com/q/50636635
has comment: http://stackoverflow.com/comment/88283280
downvote count: 0

http://stackoverflow.com/comment/88262192
type: QuestionComment
comment on: http://stackoverflow.com/q/50625583
score: 0
has text: Did not work for me, if I instace Window(), it constaly opens windows then recursion error.
type: Comment

http://stackoverflow.com/q/50671971
has answer: http://stackoverflow.com/a/50672023
has comment: http://stackoverflow.com/comment/88353826
tagged with: list
type: Question
has body: giant list That i need to print every 10 items on a new line so instead of me writing for a in range(0, 9): print(myList[a]) for b in range(10, 19): print(myList[b]) example input: myList = [1,2,3,4,5,6,7,8,10,11,12,13,14,15,16,171,8,19,20,21,22] for a in range(0, 9): print(myList[a]) for b in range(10, 19): print(myList[b]) for c in range(20, 29): print(myList[c] example output: &gt;&gt;&gt; 1,2,3,4,5,6,7,8,9 &gt;&gt;&gt; 10,11,12,13,14,15,16,17,18,19 &gt;&gt;&gt; 20,21,23,24,25,26,27,28,29 how could I write it in one line?
downvote count: 4
tagged with: for-loop
score: -2
favorite count: 0
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/50672035
has comment: http://stackoverflow.com/comment/88353705
has title: I have a list, that I need to print out 10 items on every new line?
tagged with: python-3.x
upvote count: 2
has answer: http://stackoverflow.com/a/50672020
type: UnansweredQuestion
tagged with: range
has answer: http://stackoverflow.com/a/50672011

http://stackoverflow.com/comment/88455981
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50711003
has text: @SaadH It works just fine for me if I copy-and-paste your code and mine. It's possibly related to [this](https://github.com/matplotlib/matplotlib/pull/10084) matplotlib issue, which was fixed late 2017. What version are you running?

http://stackoverflow.com/q/50611955
has body: Am Unable to sent the temp_k variable from my views to index.html. I have made a request from weather API and trying to pass it to my html. Please suggest how we are supposed to send the variable from views to template. views.py from django.template.loader import render_to_string import requests from django.shortcuts import render from django.http import HttpResponse def hello(request): my_dict = {'insert_me': "From andu.py"} return render(request, 'mywebapp/index.html', context=my_dict) def temperature(request): #zip=requests.form['zip']ss r=requests.get('http://samples.openweathermap.org/data/2.5/weather?zip=94040,us&appid=b6907d289e10d714a6e88b30761fae22') json_object=r.json() my_dict1={'temp_k' :json_object['main']['temp']} return render(request,'mywebapp/index.html', context=my_dict1) index.html {% load staticfiles%} Hey This is the Header Temperature:{{temp_k}}
has comment: http://stackoverflow.com/comment/88234868
has answer: http://stackoverflow.com/a/50613463
score: 0
has comment: http://stackoverflow.com/comment/88233965
answer count: 2
has comment: http://stackoverflow.com/comment/88234907
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88234076
has comment: http://stackoverflow.com/comment/88233913
has answer: http://stackoverflow.com/a/50614512
has comment: http://stackoverflow.com/comment/88233855
type: Question
has title: Unable to send variable from views to html python

http://stackoverflow.com/comment/88393150
type: QuestionComment
comment on: http://stackoverflow.com/q/50690683
score: 0
has text: https://stackoverflow.com/help/how-to-ask
type: Comment

http://stackoverflow.com/q/50685563
tagged with: unit-testing
has body: When programming in a scripting language (Python, Perl, Ruby or R), I try to write functions and keep them in separate files to keep my code modular. For debugging, I often put the arguments of the function inside the function body and un-comment them as soon as I'm done. Moreover, I often place a call to the function right after its definition, which I also uncomment when I'm done testing. So in the end, my file looks like this def add(a, b): # a = 1 # b = 2 c = a + b return c # add(1, 2) Is there a more elegant way to achieve this? Moreover, I think common practice would be to remove these comments when shipping the code to others. Is there a way to achieve this in a JavaDoc like manner, while keeping "real" comments (i.e. not uncommented code)? I should mention, that I often write wrapper functions around calls to plot functions in Matplotlib or R (ggplot, etc) and since in these cases the output is a graph, it doesn't fit so well into test-driven development frameworks.
score: 2
has comment: http://stackoverflow.com/comment/88386839
has comment: http://stackoverflow.com/comment/88381212
tagged with: tdd
type: Question
has comment: http://stackoverflow.com/comment/88381265
has title: Script Programming: Using arguments to develop functions in separate files
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88382291
favorite count: 0
has comment: http://stackoverflow.com/comment/88380985
tagged with: python
has comment: http://stackoverflow.com/comment/88381668
tagged with: modular-design
has answer: http://stackoverflow.com/a/50685827
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/88261617
has text: Your anwser looks cleaner then my solution. Will this prevent error's if the subject would be empty? Lets say there are no 'polarity' and 'subjectivity' for the subject 'sport'. Will my interactive plot still work?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50619955

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/50544831
tags question: http://stackoverflow.com/q/50545022
tags question: http://stackoverflow.com/q/50584908
tags question: http://stackoverflow.com/q/50683691
tags question: http://stackoverflow.com/q/50570040
tags question: http://stackoverflow.com/q/50689296
tags question: http://stackoverflow.com/q/50616240
tag name: kivy-language
tags question: http://stackoverflow.com/q/50660685
tags question: http://stackoverflow.com/q/50543028

http://stackoverflow.com/q/50558229
has comment: http://stackoverflow.com/comment/88127345
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88127617
has title: applying a function to a subset of columns in pandas groupby
type: Question
accepted answer: http://stackoverflow.com/a/50559590
has comment: http://stackoverflow.com/comment/88127415
has comment: http://stackoverflow.com/comment/88127506
has comment: http://stackoverflow.com/comment/88127457
has comment: http://stackoverflow.com/comment/88127470
has body: I have a df with many columns. I would like to group by id and transform a subset of those columns leaving the rest untouched. What is the optimal way to do this? In particular, I have a df with a bunch of id's and I would like to z-score columns a and b within each id. Column c should remain untouched. In my actual problem I have many more columns. The best I can think of is passing a dict of {col_name: function_name} to transform. For some reason this raises a TypeError. MWE: import pandas as pd import numpy as np np.random.seed(123) #reproducible ex df = pd.DataFrame(data = {"a": np.arange(10), "b": np.arange(10)[::-1], "c": np.random.choice(a = np.arange(10), size = 10)}, index = pd.Index(data = np.random.choice(a = [1,2,3], size = 10), name = "id")) #create a dict for all columns other than "c" and the function to do the transform fmap = {k: lambda x: (x - x.mean()) / x.std() for k in df.columns if k != "c"} df.groupby("id").transform(fmap) #yields error that "dict" is unhashable Turns out this is a known bug: https://github.com/pandas-dev/pandas/issues/17309
tagged with: pandas
has comment: http://stackoverflow.com/comment/88127366
has comment: http://stackoverflow.com/comment/88127444
has comment: http://stackoverflow.com/comment/88127592
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88127531
favorite count: 0
has comment: http://stackoverflow.com/comment/88127573
has comment: http://stackoverflow.com/comment/88127565
has answer: http://stackoverflow.com/a/50559590
tagged with: python
has comment: http://stackoverflow.com/comment/88127557
has comment: http://stackoverflow.com/comment/88127426
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88127541

http://stackoverflow.com/comment/88218063
score: 0
has text: So you mean, Nose Part knee and element will be the output?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50604402

pandas-groupby
tags question: http://stackoverflow.com/q/50679939
tags question: http://stackoverflow.com/q/50611772
tags question: http://stackoverflow.com/q/50657239
tags question: http://stackoverflow.com/q/50694739
tags question: http://stackoverflow.com/q/50611929
tags question: http://stackoverflow.com/q/50684171
tags question: http://stackoverflow.com/q/50622333
tags question: http://stackoverflow.com/q/50691568
tags question: http://stackoverflow.com/q/50675058
tags question: http://stackoverflow.com/q/50630569
tags question: http://stackoverflow.com/q/50576086
tags question: http://stackoverflow.com/q/50629848
tags question: http://stackoverflow.com/q/50542039
tags question: http://stackoverflow.com/q/50592762
tags question: http://stackoverflow.com/q/50552448
tag name: pandas-groupby
tags question: http://stackoverflow.com/q/50546737
tags question: http://stackoverflow.com/q/50661686
tags question: http://stackoverflow.com/q/50660820
tags question: http://stackoverflow.com/q/50657545
tags question: http://stackoverflow.com/q/50575056
type: Tag
tags question: http://stackoverflow.com/q/50628327
tags question: http://stackoverflow.com/q/50661814
tags question: http://stackoverflow.com/q/50693031
tags question: http://stackoverflow.com/q/50684086
tags question: http://stackoverflow.com/q/50602100
tags question: http://stackoverflow.com/q/50579596
tags question: http://stackoverflow.com/q/50594119
tags question: http://stackoverflow.com/q/50615643
tags question: http://stackoverflow.com/q/50683137
tags question: http://stackoverflow.com/q/50692000
tags question: http://stackoverflow.com/q/50662469
tags question: http://stackoverflow.com/q/50598984
tags question: http://stackoverflow.com/q/50569899
tags question: http://stackoverflow.com/q/50596307
tags question: http://stackoverflow.com/q/50558472
tags question: http://stackoverflow.com/q/50664128
tags question: http://stackoverflow.com/q/50661541
tags question: http://stackoverflow.com/q/50626601
tags question: http://stackoverflow.com/q/50594049
tags question: http://stackoverflow.com/q/50675844
tags question: http://stackoverflow.com/q/50652463

http://stackoverflow.com/q/50560207
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50560333
type: Question
accepted answer: http://stackoverflow.com/a/50560333
answer count: 1
has title: vincenty distance in series
score: 0
tagged with: pandas
has body: I have pandas dataframe with columns latitude and longitude, and want to calculate vincenty distance between two consecutive points pi and pi+1. lat long 1 39.9852833333333 116.307367 2 39.9852166666667 116.309550 3 39.9851333333333 116.309767 4 39.9850666666667 116.309883 5 39.9847333333333 116.309933 df['distance'] = vincenty( (df['lat'],df['long']), (df['lat'].shift(-1), df['long'].shift(-1)) ) I'm getting following error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
tagged with: python

http://stackoverflow.com/q/50642922
has title: Traverse nested dictionary from depth and move to top
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/50643168
answer count: 1
has comment: http://stackoverflow.com/comment/88296081
has comment: http://stackoverflow.com/comment/88296176
has comment: http://stackoverflow.com/comment/88296593
favorite count: 0
has body: I have below dictionary (generated from a report, so the structure can change). I need to go to the depth of the dictionary, find the id which in this case is 'id': u'ef3c8cf1-0987-4e56-a6d5-763c42be1f75', (there can be more than 1), delete that id and then move to one level up and repeat the same till I get to the top id which I finally delete. Since there is a dependency, I need to delete the orphan id first and then move to the top. Any help is appreciable. If any other file/information is needed, please let me know. { 'id': u'4c31d813-a989-47dd-b01b-9a27b8db2dfc', 'snapshots': [ { 'id': u'3ddc7ddd-02ca-4669-a0cb-fb0d56a4a6f5', 'volumes': [ { 'id': u'5488de90-50dc-4d72-a6aa-c995422fa179', 'snapshots': [], 'snapshot_id': u'3ddc7ddd-02ca-4669-a0cb-fb0d56a4a6f5' }, { 'id': u'e566645f-4fb3-4778-be67-447a5bdd678d', 'snapshots': [ { 'id': u'd637f6ea-4a41-448c-874f-ffe624ddc597', 'volumes': [ { 'id': u'ef3c8cf1-0987-4e56-a6d5-763c42be1f75', 'snapshots': [], 'snapshot_id': u'd637f6ea-4a41-448c-874f-ffe624ddc597' } ] } ], 'snapshot_id': u'3ddc7ddd-02ca-4669-a0cb-fb0d56a4a6f5'}, { 'id': u'196483ee-4f21-4d83-8e15-8caea532b2ab', 'snapshots': [], 'snapshot_id': u'3ddc7ddd-02ca-4669-a0cb-fb0d56a4a6f5' } ] } ], 'snapshot_id': None } Python code oh=openstack_helper.OpenstackHelper() def get_objects(item): items=None if item == 'stacks': items=oh.get_stacks() if item == 'volumes': items=oh.get_volumes() if item == 'snapshots': items=oh.get_snapshots() return items def dep_graph(volumes,snapshots,snapshot_id=None): vol_list=[] for volume in volumes: if volume.snapshot_id == snapshot_id: info={'id':volume.id,'snapshot_id':volume.snapshot_id,'snapshots':[], } vol_list.append(info) for snapshot in snapshots: for volume in vol_list: snap_list=[] if snapshot.volume_id == volume['id']: info={'id':snapshot.id, 'volumes':[]} info['volumes'].extend(dep_graph(volumes,snapshots,snapshot.id)) volume['snapshots'].append(info) return vol_list if __name__ == '__main__': volumes = get_objects('vo…
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
upvote count: 1
downvote count: 1
tagged with: openstack
type: Question
has comment: http://stackoverflow.com/comment/88295989

http://stackoverflow.com/a/50691776
has comment: http://stackoverflow.com/comment/88393213
answers question: http://stackoverflow.com/q/50691339
type: AcceptedAnswer
downvote count: 0
has body: Should there not be a steady incline which where the next element would ALWAYS be the higher than the previous element? Yes, the fit is a straight line, so higher values of x are always associated with higher (or lower, depending on the slope) values of p(x). What's happening in your case is that x is not sorted, and so p(x) isn't sorted either. In [18]: x Out[18]: array([ 9.95692606, 5.25372625, 9.84277793, 9.75691888, 3.53691402, 7.47732635, 13.26638669, 10.39011192, 11.86590794, 10.38592445, 0.5328471 , 7.69932299, ... As you can see, we're not starting on the left and moving to the right. We're first looking at some point in the middle, then jumping left a lot, then jumping right, then moving a little bit to the left, etc. The corresponding p(x) values are not going to be monotonic either. If you sort the points from left to right, you'll see that they indeed always move in the same vertical direction: In [20]: sorted(zip(x, p(x))) Out[20]: [(0.53284710066507301, 5.2982022878459842), (0.90494271648495472, 5.3490731826338447), (1.2383322417505211, 5.3946523906172272), (1.2542322226117251, 5.3968261497778585), (1.3243912128123114, 5.4064179064586044), (1.4506628234207115, 5.4236810763129437), (2.0368566039434102, 5.503822311163459), (2.8349103207704576, 5.6129278876274968), (3.0174136939304748, 5.637878759123244), (3.5369140229038196, 5.7089020269444219), (4.932863919562303, 5.8997487268324766), (4.943993127936622, 5.9012702518497351), (4.9500689452818589, 5.9021009046491208), ...
has comment: http://stackoverflow.com/comment/88393186
has comment: http://stackoverflow.com/comment/88393307
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88393244
accepted answer of: http://stackoverflow.com/q/50691339
has comment: http://stackoverflow.com/comment/88393268

http://stackoverflow.com/q/50602569
has title: Pycharm plot windows doesn't open with 'Agg' backend
answer count: 0
tagged with: pycharm
has comment: http://stackoverflow.com/comment/88215037
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/88214802
type: Question
has body: I am pretty new to Pycharm (community edition), which I am using via Thinlinc client on a remote desktop server. The issue I am having is that I am not able to create interactive plots. On my local computer with Canopy, after importing matplotlib and calling the plot( ... ) command on the console with some variable X inside, the plot window opens. However, in my remote machine on the Pycharm console, calling plot() does not give errors, but does not open a window (not even when calling .show()). By contrast, plt.savefig() works perfectly. I tried to get the following info: matplotlib.is_interactive() Out[8]: True matplotlib.get_backend() Out[10]: 'agg'
score: 0
linked to: http://stackoverflow.com/q/5091993
has comment: http://stackoverflow.com/comment/88214932
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88214695
tagged with: python
tagged with: backend
tagged with: plot

pip
tags question: http://stackoverflow.com/q/50639973
tags question: http://stackoverflow.com/q/50661925
tags question: http://stackoverflow.com/q/50598220
tags question: http://stackoverflow.com/q/50615386
tags question: http://stackoverflow.com/q/50591842
tags question: http://stackoverflow.com/q/50623283
tags question: http://stackoverflow.com/q/50692816
tags question: http://stackoverflow.com/q/50685300
tags question: http://stackoverflow.com/q/50616566
tags question: http://stackoverflow.com/q/50643166
tags question: http://stackoverflow.com/q/50557963
tags question: http://stackoverflow.com/q/50596400
tags question: http://stackoverflow.com/q/50655774
tags question: http://stackoverflow.com/q/50548627
tags question: http://stackoverflow.com/q/50548050
tags question: http://stackoverflow.com/q/50602212
tags question: http://stackoverflow.com/q/50615591
tags question: http://stackoverflow.com/q/50680029
tags question: http://stackoverflow.com/q/50609005
tags question: http://stackoverflow.com/q/50569710
tags question: http://stackoverflow.com/q/50626401
tags question: http://stackoverflow.com/q/50625882
tags question: http://stackoverflow.com/q/50606352
tags question: http://stackoverflow.com/q/50616770
tags question: http://stackoverflow.com/q/50631713
tags question: http://stackoverflow.com/q/50591149
tag name: pip
tags question: http://stackoverflow.com/q/50547218
tags question: http://stackoverflow.com/q/50686268
tags question: http://stackoverflow.com/q/50568796
tags question: http://stackoverflow.com/q/50668854
tags question: http://stackoverflow.com/q/50604463
tags question: http://stackoverflow.com/q/50579739
tags question: http://stackoverflow.com/q/50668973
tags question: http://stackoverflow.com/q/50657368
tags question: http://stackoverflow.com/q/50671671
tags question: http://stackoverflow.com/q/50616037
tags question: http://stackoverflow.com/q/50674689
tags question: http://stackoverflow.com/q/50572094
tags question: http://stackoverflow.com/q/50647391
tags question: http://stackoverflow.com/q/50608944
tags question: http://stackoverflow.com/q/50629482
tags question: http://stackoverflow.com/q/50563964
tags question: http://stackoverflow.com/q/50685218
tags question: http://stackoverflow.com/q/50615201
tags question: http://stackoverflow.com/q/50650433
tags question: http://stackoverflow.com/q/50683895
tags question: http://stackoverflow.com/q/50652030
tags question: http://stackoverflow.com/q/50692162
tags question: http://stackoverflow.com/q/50575113
tags question: http://stackoverflow.com/q/50591617
tags question: http://stackoverflow.com/q/50585246
tags question: http://stackoverflow.com/q/50667575
tags question: http://stackoverflow.com/q/50571372
type: Tag
tags question: http://stackoverflow.com/q/50669306
tags question: http://stackoverflow.com/q/50573089
tags question: http://stackoverflow.com/q/50676046
tags question: http://stackoverflow.com/q/50570312
tags question: http://stackoverflow.com/q/50667413
tags question: http://stackoverflow.com/q/50593199
tags question: http://stackoverflow.com/q/50634751
tags question: http://stackoverflow.com/q/50642086
tags question: http://stackoverflow.com/q/50578654
tags question: http://stackoverflow.com/q/50616411
tags question: http://stackoverflow.com/q/50622990
tags question: http://stackoverflow.com/q/50642909
tags question: http://stackoverflow.com/q/50613139
tags question: http://stackoverflow.com/q/50562965
tags question: http://stackoverflow.com/q/50649044
tags question: http://stackoverflow.com/q/50637089
tags question: http://stackoverflow.com/q/50627125
tags question: http://stackoverflow.com/q/50563984
tags question: http://stackoverflow.com/q/50664541
tags question: http://stackoverflow.com/q/50591098
tags question: http://stackoverflow.com/q/50573741

http://stackoverflow.com/a/50555258
answers question: http://stackoverflow.com/q/50555179
type: AcceptedAnswer
downvote count: 0
has body: Use the labels parameter on your boxplot call. labels = ['nok', 'msft', 'ibm', 'appl'] ax.boxplot(data, widths = 0.6, patch_artist = True, labels=labels)
accepted answer of: http://stackoverflow.com/q/50555179
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/88139022
type: Comment
type: QuestionComment
has text: And what is the expected output? You have a grid in this image, in which format are you expecting output ?
score: 0
comment on: http://stackoverflow.com/q/50564242

http://stackoverflow.com/comment/88347812
has text: Please post a [mcve].
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50669016
score: 1

http://stackoverflow.com/q/50572587
tagged with: conditional-statements
score: -1
tagged with: for-loop
answer count: 1
downvote count: 1
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has title: how to write an empty column in a csv based on other columns in the same csv file
tagged with: python
has answer: http://stackoverflow.com/a/50572671
accepted answer: http://stackoverflow.com/a/50572671
type: AnsweredQuestion
upvote count: 0
type: Question
has body: I don't know whether this is a very simple qustion, but I would like to do a condition statement based on two other columns. I have two columns like: the age and the SES and the another empty column which should be based on these two columns. For example when one person is 65 years old and its corresponding socio-economic status is high, then in the third column(empty column=vitality class) a value of 1 is for example given. I have got an idea about what I want to achieve, however I have no idea how to implement that in python itself. I know I should use a for loop and I know how to write conditons, however due to the fact that I want to take two columns into consideration for determining what will be written in the empty column, I have no idea how to write that in a function and furthermore how to write back into the same csv (in the respective empty column) [ ]

http://stackoverflow.com/comment/88113450
type: Comment
comment on: http://stackoverflow.com/q/50550899
type: QuestionComment
has text: @Andersson I have updated the question, hope now you can withdraw your close request.
score: 0

http://stackoverflow.com/comment/88223450
comment on: http://stackoverflow.com/a/50603359
type: AnswerComment
score: 0
type: Comment
has text: After several tests, it seems that the cpu/gpu are working 50%-100% harder. There is also a significant decrease in the step times.

http://stackoverflow.com/comment/90969889
score: 1
comment on: http://stackoverflow.com/a/50679524
type: AnswerComment
type: Comment
has text: That did now work for me. still had the same shape afterwards

http://stackoverflow.com/comment/88240299
comment on: http://stackoverflow.com/a/50596116
type: AnswerComment
has text: If `std_log` is a big list (result from another routine?) you can still use copies of it: `thedict = {i+1: std_log[:] for i in range(8)}`. `[:]` effectively creates a copy. But beware it may not work with other structures, e.g. numpy arrays. Using `.copy()` should be safer...
type: Comment
score: 0

http://stackoverflow.com/q/50683637
tagged with: javascript
has comment: http://stackoverflow.com/comment/88381421
has comment: http://stackoverflow.com/comment/88381630
has comment: http://stackoverflow.com/comment/88380076
favorite count: 0
has comment: http://stackoverflow.com/comment/88383126
tagged with: beautifulsoup
has body: html = title text" Code = class Client(QWebPage): def __init__(self, url): self.app = QApplication(sys.argv) QWebPage.__init__(self) self.loadFinished.connect(self.on_page_load) self.mainFrame().load(QUrl(url)) self.app.exec_() def on_page_load(self): self.app.quit() client_response = Client(url) source = client_response.mainFrame().toHtml() soup = bs.BeautifulSoup(source, 'lxml') for link in soup.findAll('a', class_='js-pop'): href = link.get('href') print(href) print(link.text) I want it to return the href link and the title text. When I run it prints every class that has the text "js-pop" in it and there are multiple classes named "js-pop" that aren't classes I want to scrape. I've attempted scraping the page in selenium and it prints "none" when I try to locate the href on class='js-pop' the elements I'm trying to scrape all have unique ID's, CSS selectors, and xpaths How should I go about locating this element?
has comment: http://stackoverflow.com/comment/88384102
upvote count: 2
tagged with: web-scraping
tagged with: python
has answer: http://stackoverflow.com/a/50687267
score: 2
type: AnsweredQuestion
has title: How to locate duplicate JS elements BeautifulSoup Python
tagged with: selenium
accepted answer: http://stackoverflow.com/a/50687267
has comment: http://stackoverflow.com/comment/88383346
type: Question
has comment: http://stackoverflow.com/comment/88381499
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/88179355
comment on: http://stackoverflow.com/q/50584986
type: Comment
type: QuestionComment
has text: Python doesn't skip values by itself so the problem (whatever it is) is in your code - obviously in some part you didn't post (the for loop's body being an obvious suspect).
score: 0

http://stackoverflow.com/q/50568796
has comment: http://stackoverflow.com/comment/88215329
has body: I have created a python repository on machine 10.x.x.x and it's accessible over a web browser (set up an Apache server). I am verifying its successful operation from a different machine and it's failing with the error mentioned below [root@localhost ~]# pip install --index-url=http://10.x.x.x/repos/python/python2 -r requirement.txt --trusted-host 10.x.x.x Looking in indexes: http://10.x.x.x/repos/python/python2 Collecting Flask==1.0.2 (from -r requirement.txt (line 1)) Could not find a version that satisfies the requirement Flask==1.0.2 (from -r requirement.txt (line 1)) (from versions: ) No matching distribution found for Flask==1.0.2 (from -r requirement.txt (line 1)) [root@localhost ~]# The requirement file has the package [root@localhost ~]# cat requirement.txt Flask==1.0.2 [root@localhost ~]# Python version is 2.7.5 and the pip version on both the repository machine and the test machine are as follows: # pip -V pip 10.0.1 from /usr/lib/python2.7/site-packages/pip-10.0.1-py2.7.egg/pip (python 2.7) [root@localhost ~]# Any ideas on how to fix this?
has comment: http://stackoverflow.com/comment/88206806
type: Question
has comment: http://stackoverflow.com/comment/88206960
has comment: http://stackoverflow.com/comment/88147871
has title: pip install of a package from a manually created repository is failing
score: 0
has comment: http://stackoverflow.com/comment/88149199
has comment: http://stackoverflow.com/comment/88214910
answer count: 0
type: UnansweredQuestion
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/88207012

http://stackoverflow.com/q/50560463
tagged with: python
has answer: http://stackoverflow.com/a/50568932
tagged with: tensorflow
type: Question
has title: Channel dimension Found 'None', however through tensor.get_shape() it has been defined
score: 0
answer count: 1
tagged with: keras
tagged with: tensor
type: UnansweredQuestion
has body: I get to a problem when I'm trying to concatenate some same shape of tensor together to process through some operation (some fully connected layer etc.) I concatenate them as followed: x_con = KL.concatenate([x1, x2, x3, x4], axis=-1,name='P3_concatenate') x=Squeeze_excitation(x_con, origin_x=x, out_dim=256 * 4, ratio=16, layer_name='x_con') and the Squeeze_exicitation is the function where I defined the processing with the tensor: def Squeeze_excitation(input_x, origin_x, out_dim, ratio, layer_name): print("input shape:",input_x.get_shape().as_list()) squeeze = KL.GlobalAveragePooling2D(name=layer_name+'_Squeeze_Layer')(input_x) excitation = KL.Dense(units=out_dim // ratio, name=layer_name + '_fully_connected1')(squeeze) excitation = KL.Activation('relu',name=layer_name+'_relu')(excitation) excitation = KL.Dense(units=out_dim, name=layer_name + '_fully_connected2')(excitation) excitation = KL.Activation('sigmoid', name=layer_name+'_sigmoid')(excitation) excitation = KL.Reshape((1, 1, out_dim))(excitation) print("exicitation shape:", excitation.get_shape().as_list()) scale = KL.multiply([input_x,excitation], name=layer_name+'_multiply') print("scale shape:",scale.get_shape().as_list()) index = K.constant(value=out_dim//4,dtype=tf.int32) scale = KL.add([scale[:, :, :, 0:index], scale[:, :, :, index:2 * index], scale[:, :, :, 2 * index:3 * index], scale[:, :, :, 3 * index:]],name=layer_name+'_Add_n') print("scale shape:", scale.get_shape().as_list()) return scale After the processing of the tensor, I try to add a convolutional layer to this tensor: x = KL.Conv2D(256, (3, 3), padding="SAME")(x) and it raised an error: ValueError: The channel dimension of the inputs should be defined. Found `None`. To check with the dimensions of the tensor when processing with it, I add some output to keep an eye with its dimension, here is the output in the function Squueze_excitation: input shape: [None, 32, 32, 1024] exicitation shape: [None, 1, 1, 1024] scale shape: [None, 32, 32, …

http://stackoverflow.com/q/50596813
has comment: http://stackoverflow.com/comment/88203370
tagged with: python
has comment: http://stackoverflow.com/comment/88203030
has answer: http://stackoverflow.com/a/50596833
type: AnsweredQuestion
has title: Merge data frame issue
downvote count: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88202869
has comment: http://stackoverflow.com/comment/88203420
tagged with: dataframe
score: -1
has comment: http://stackoverflow.com/comment/88203104
accepted answer: http://stackoverflow.com/a/50596833
tagged with: pandas
upvote count: 0
has comment: http://stackoverflow.com/comment/88203333
answer count: 1
has body: I have 2 data frames , first one is +------------------------------------------+ | ID CustomerType Choice | +------------------------------------------+ | 0 1.0 Durability OEM | | 1 2.0 Price OEM | | 2 3.0 Durability OEM | | 3 4.0 Durability OEM | | 4 5.0 Durability OEM | | 5 6.0 ManufacturerCredibility OEM | | 6 7.0 Warranty OEM | | 7 8.0 ManufacturerCredibility OEM | | 8 9.0 Durability OEM | | 9 10.0 Price OEM | | 10 11.0 Durability TPN | | 11 12.0 Warranty OEM | | 12 13.0 Durability TPN | +------------------------------------------+ and second one is; --------------------------------------------------------+ | Price Durability Warranty Manufacture Type | +--------------------------------------------------------+ | OEM 1.00 4.0 4.0 4.0 OEM | | TPN 0.80 4.0 1.0 1.0 TPN | | Reman 0.55 4.0 0.5 1.0 Reman | | Reuse 0.45 2.5 0.0 1.0 Reuse | +--------------------------------------------------------+ I need to join these 2 data frames by using "Choice" from the first dataframe and "Type" from the second dataframe . Currently I'm using data = pd.merge(survey,rel_attr, left_on = 'Choice', right_on = 'Type',how='left') and having awkward result like this. +------------------------------------------------------------------------------+ | Price Durability Warranty Manufacture CustomerType Choice | +------------------------------------------------------------------------------+ | 0 1.0 4.0 4.0 4.0 Durability OEM | | 1 1.0 4.0 4.0 4.0 Price OEM | | 2 1.0 4.0 4.0 4.0 Durability OEM | | 3 1.0 4.0 4.0 4.0 Durability OEM | | 4 1.0 4.0 4.0 4.0 Durability OEM | | 5 1.0 4.0 4.0 4.0 ManufacturerCredibility OEM | | 6 1.0 4.0 4.0 4.0 Warranty OEM | | 7 1.0 4.0 4.0 4.0 ManufacturerCredibility OEM | | 8 1.0 4.0 4.0 4.0 Durability OEM | | 9 1.0 4.0 4.0 4.0 Price OEM | | 10 1.0 4.0 4.0 4.0 Warranty OEM | | 11 1.0 4.0 4.0 4.0 Price OEM | | 12 1.0 4.0 4.0 4.0 Warranty OEM | | 13 1.0 4.0 4.0 4.0 ManufacturerCredibility OEM | +----------------------------------------------------------------------…
favorite count: 0

http://stackoverflow.com/comment/88109045
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50549011
has text: I replaced the code for val2 with another approach that yields the same list...`val2 = x.groupby('ID').nth(1)['location']` and that worked! But I do not understand why the first approach was throwing that error.
score: 0

directed-acyclic-graphs
type: Tag
tags question: http://stackoverflow.com/q/50567100
tag name: directed-acyclic-graphs

http://stackoverflow.com/a/50616084
has body: Replace if len(sys.argv) &gt;= 1: with: if len(sys.argv) &gt; 1: If you run your script as python myPythonScript.py, len(sys.argv) is 1. This is because program name itself is the first argument. So you may need to check if len is &gt; 1 to check for optional arguments from command line.
has comment: http://stackoverflow.com/comment/88242205
has comment: http://stackoverflow.com/comment/88242399
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50616031
answers question: http://stackoverflow.com/q/50616031
type: Answer
has comment: http://stackoverflow.com/comment/88242280
score: 2
upvote count: 2

http://stackoverflow.com/comment/88374311
type: Comment
has text: This is an implementation of the "consider only sorted numbers, expand permutations later" idea from comments, right? Nice. Are `m` and `nums` in the performance test the small values from the quesiton? How about somewhat larger values for `m` and more numbers to choose from?
comment on: http://stackoverflow.com/a/50679883
score: 0
type: AnswerComment

http://stackoverflow.com/q/50689810
answer count: 1
has body: I have the following code to load a .wav file and play it: import base64 import winsound with open('file.wav','rb') as f: data = base64.b64encode(f.read()) winsound.PlaySound(base64.b64decode(data), winsound.SND_MEMORY) It plays the file no problem but now I would like to extract a 'chunk' let's say from 233 to 300 and play that portion only. seg = data[233:300] winsound.PlaySound(base64.b64decode(seg), winsound.SND_MEMORY) I Get: TypeError: 'sound' must be str or None, not 'bytes'
tagged with: python
favorite count: 0
tagged with: python-3.x
downvote count: 0
tagged with: winsound
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/88389366
score: 1
has answer: http://stackoverflow.com/a/50690702
has title: Extract a segment from a .wav file
upvote count: 1

http://stackoverflow.com/a/50636709
answers question: http://stackoverflow.com/q/50636598
score: 2
has comment: http://stackoverflow.com/comment/88283825
has body: Use enumerate: for x, item in enumerate(fileList): fileList[x] = item.replace(',', "").replace('.', "") Note: item.replace() returns replaced string which you need to store in the right index of list. enumerate helps you keep track of index while iterating through the list.
has comment: http://stackoverflow.com/comment/88283510
has comment: http://stackoverflow.com/comment/88283931
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/88283778
downvote count: 0

http://stackoverflow.com/q/50669306
downvote count: 1
score: 2
accepted answer: http://stackoverflow.com/a/50670142
type: AnsweredQuestion
tagged with: pypi
has comment: http://stackoverflow.com/comment/88349080
type: Question
has comment: http://stackoverflow.com/comment/88348432
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50670142
has comment: http://stackoverflow.com/comment/88349196
has title: Why doesn't pip install dependencies specified in setup.py?
has comment: http://stackoverflow.com/comment/88349760
has body: I built a Python package with a setup.py that looks like: from setuptools import setup, find_packages setup( name='my_package', version='0.1', url='https://github.com/me/my_package', download_url='https://github.com/dwnlod.tar.gz', author='me', author_email='myname@email.com', license='MIT', packages=['my_package'], install_requires=[ 'numpy', 'other_package' ] ) When I install the package locally with pip install . Pip installs all the dependencies in install_requires. However, when I register the package through PyPI, and use pip install my_package Pip does not install the dependencies. (I did this with a fresh environment, so the packages are not installed already; the install fails.) What's going on? Reading through the documentation, it looks like maybe something like install_requires=[ 'numpy==1.14.1', 'other_package==ve.rs.ion' ] Might work better, because the versions are specified. Could this be the problem? Here is a link to the repo: PyCDA on GitHub PyCDA on PyPI
upvote count: 3
tagged with: pip
tagged with: python

http://stackoverflow.com/q/50594392
tagged with: python-requests
has answer: http://stackoverflow.com/a/50595307
type: Question
has answer: http://stackoverflow.com/a/50594567
has title: Trouble fetching all the names from a webpage with messy layout
possible better answer: http://stackoverflow.com/a/50594567
has comment: http://stackoverflow.com/comment/88198000
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/88198108
tagged with: beautifulsoup
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/88198089
accepted answer: http://stackoverflow.com/a/50595307
type: AnsweredQuestion
has body: I've written a script to parse all the mobile shop names from a webpage. When I run my script I an get a very few of them. How can I get all the names from that page where last name at this moment is Parkway Mobile Home Park - Alabama? webpage link This is what I've tried so far with: import requests from bs4 import BeautifulSoup url = "replace with above link" r = requests.get(url) soup = BeautifulSoup(r.text,"lxml") items = soup.select_one("table tr") name = '\n'.join([item.get_text(strip=True) for item in items.select("td p strong") if "alabama" in item.text.lower()]) print(name) Output are like: Roberts Trailer Park - Alabama Cloverleaf Trailer Park - Alabama Longview Mobile Home Park - Alabama
tagged with: web-scraping

http://stackoverflow.com/comment/88173699
type: Comment
has text: I understand that. I was confused by the fact that I can use classmethods both as `B.cm()` and `b.cm()`, and `self` will be automatically resolved for me, which @Aran-Fey explained in their answer.
type: AnswerComment
comment on: http://stackoverflow.com/a/50582097
score: 0

http://stackoverflow.com/comment/88405193
score: 0
comment on: http://stackoverflow.com/a/50696442
type: Comment
has text: hmmm, there is problem with `Range` columns, because categoricals. Give me some time for solution.
type: AnswerComment

http://stackoverflow.com/q/50664672
tagged with: django
tagged with: python
tagged with: django-views
score: 1
has answer: http://stackoverflow.com/a/50664752
tagged with: django-forms
type: Question
tagged with: django-queryset
has comment: http://stackoverflow.com/comment/88339401
upvote count: 1
has comment: http://stackoverflow.com/comment/88339397
answer count: 1
has title: get a multiple choice queryset in Django view and save it
favorite count: 0
has body: I have a multiple choice field with a foreign key. I want to save which keeper was attending a training session and I want to list all keepers as a multiple choice field. class AddAttendance(forms.ModelForm): attendanceKeeper = Attendance.objects.only("keeper","present").all() keeperValues = Attendance.objects.values_list("keeper__id", flat=True).distinct() keeper = forms.ModelMultipleChoiceField(widget=forms.widgets.CheckboxSelectMultiple, queryset=Keeper.objects.filter(id__in=keeperValues, status=1)) class Meta: model = Attendance fields = ('keeper',) def __init__(self, *args, **kwargs): super(AddAttendance, self).__init__(*args, **kwargs) self.initial["keeper"] = Keeper.objects.all() However my problem is, I am not familiar how to handle a queryset in the view and how to loop through it and to save every instance with the value True or False. I always get the value error that a queryset cannot be assigned "Attendance.keeper" must be a "Keeper" instance Can you help me how I access the queryset values and save them def new_attendance(request, team_pk, package_pk): if request.method == "POST": form = AddAttendance(request.POST) if form.is_valid(): for item in form: attendance = item.save(commit=False) attendance.keeper = get_object_or_404(AddAttendance.keeper) attendance.team = get_object_or_404(Team, pk=team_pk) attendance.created_date = timezone.now() attendance.save() return redirect(reverse('select_package', args=[package_pk, team_pk])) else: form = AddAttendance() return render(request, 'attendance/new_attendance.html', {'form': form}) In the end I want to match keeper from the queryset and save True/False into the field present in my model class Attendance(models.Model): session = models.ForeignKey(Session) keeper = models.ForeignKey(Keeper) team = models.ForeignKey(Team) present = models.BooleanField() created_date = models.DateTimeField(default=timezone.now) edited_date = models.DateTimeField(default=timezone.now)
has comment: http://stackoverflow.com/comment/88339391
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88339438

http://stackoverflow.com/a/50642268
score: 1
upvote count: 1
downvote count: 0
has body: You can always convert to a list, slice off the end and convert back to a set: s = {1, '2', 'three', 4, (5,), 6} print(s) required_length = len(s) - 2 s = set(list(s)[:required_length]) print(s) Output: {1, 4, 'three', 6, (5,), '2'} {1, 4, 'three', 6}
type: Answer
answers question: http://stackoverflow.com/q/50642150

http://stackoverflow.com/comment/88128536
has text: @coldspeed prop is a masking factor. Makes it difficult to trace back to the input date, by applying any simple formula on the output.
score: 0
comment on: http://stackoverflow.com/q/50558867
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88155844
comment on: http://stackoverflow.com/a/50557989
type: AnswerComment
has text: they need to be roated in 2D space of image. I have updated my question. You can check it. I assume now it is clear what the question is. How can I reshape center.x and center.y image to 8D space?
score: 0
type: Comment

http://stackoverflow.com/q/50667397
has comment: http://stackoverflow.com/comment/88344812
accepted answer: http://stackoverflow.com/a/50667655
tagged with: matplotlib
tagged with: pandas
answer count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50667655
tagged with: python
has body: Im totally new in this field and almost everything is still a mistery to me. I have the following data frame: usersPerWeek date date 2018-03-07 127 2018-03-07 2018-03-14 3177 2018-03-14 2018-03-21 8758 2018-03-21 2018-03-28 16770 2018-03-28 2018-04-04 17964 2018-04-04 And I am trying to plot this on as a simple bar chart: import pandas as pd import matplotlib.pyplot as plt figPerWeek = plt.figure(dpi=80, figsize=(8,1)) axis = figPerWeek.add_subplot(1,1,1) axis.bar(x=data.index, height=data.usersPerWeek) This results in the error message Axis must havefreqset to convert to Periods When I add (just before calling axis.bar) axis.xaxis_date() I then get the error message 'Period' object has no attribute 'toordinal'. Im hoping that I am missing something really simple, but so far Google has been less than helpful. Cheers
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/20109391
upvote count: 3
score: 1
downvote count: 2
has title: Plotting a DataFrame (that has a date index) as a bar chart
type: Question

http://stackoverflow.com/comment/88567687
has text: Btw, your advices are really helpful cuz I don't even know what the `-P eventlet` means. Is it common case to use `-P eventlet` this option? that might depend on the computer I use?
type: Comment
comment on: http://stackoverflow.com/a/50776181
score: 0
type: AnswerComment

collections
tags question: http://stackoverflow.com/q/50557208
tags question: http://stackoverflow.com/q/50571488
type: Tag
tags question: http://stackoverflow.com/q/50687892
tag name: collections

http://stackoverflow.com/q/50569453
has answer: http://stackoverflow.com/a/59000283
favorite count: 0
linked to: http://stackoverflow.com/q/28437071
has answer: http://stackoverflow.com/a/61757677
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/60098820
tagged with: pylint
tagged with: python
tagged with: pygame
has body: This is the code I have: import pygame pygame.init() I'm very confused because if I try to run the file, then there seems to be no issue, but pylint says the following: E1101:Module 'pygame' has no 'init' member I have searched thoroughly for a solution to this "error". In every relevant case I found, the solution was to make sure that I have not made another file or folder with the name "pygame", because in that case, I would just be importing my own file or folder. However, I have not made a folder or file with a name even close to "pygame", so I don't know what the problem is. As said earlier, it seems like I'm able to run the file without any issues and having errors like this confuses me in my learning process. I write code in Visual Studio Code, I'm using python 3.6, I'm using pygame 1.9.3 and have updated my pylint. Any help would be appreciated.
has answer: http://stackoverflow.com/a/54885767
has answer: http://stackoverflow.com/a/77449410
has comment: http://stackoverflow.com/comment/88153264
has comment: http://stackoverflow.com/comment/88153223
has answer: http://stackoverflow.com/a/52600893
has comment: http://stackoverflow.com/comment/88149107
has comment: http://stackoverflow.com/comment/88150267
has title: Why does it say that module pygame has no init member?
has comment: http://stackoverflow.com/comment/88154596
has comment: http://stackoverflow.com/comment/88153723
has answer: http://stackoverflow.com/a/63210293
has answer: http://stackoverflow.com/a/61642335
type: Question
has answer: http://stackoverflow.com/a/52927347
tagged with: visual-studio-code
upvote count: 53
has comment: http://stackoverflow.com/comment/88153694
has answer: http://stackoverflow.com/a/53235302
has answer: http://stackoverflow.com/a/61721258
answer count: 13
has answer: http://stackoverflow.com/a/51144665
score: 53
has answer: http://stackoverflow.com/a/54892222
downvote count: 0

http://stackoverflow.com/q/50582782
tagged with: python
has comment: http://stackoverflow.com/comment/88176069
type: AnsweredQuestion
score: 3
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50582972
has title: merge a string column to a set of list using Python
has comment: http://stackoverflow.com/comment/88176788
possible better answer: http://stackoverflow.com/a/50582824
upvote count: 4
tagged with: numpy
has answer: http://stackoverflow.com/a/50582824
answer count: 3
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50582972
favorite count: 0
has answer: http://stackoverflow.com/a/50582879
has comment: http://stackoverflow.com/comment/88176878
has body: I have a Pandas DataFrame like this : id fruits 01 Apple, Apricot 02 Apple, Banana, Clementine, Pear 03 Orange, Pineapple, Pear How can i get a list of fruits like this by deleting duplicates? ['Apple','Apricot','Banana','Clementine','Orange','Pear','Pineapple']

http://stackoverflow.com/q/50686320
has answer: http://stackoverflow.com/a/50690339
has comment: http://stackoverflow.com/comment/88386717
has comment: http://stackoverflow.com/comment/88382408
tagged with: shellcode
has comment: http://stackoverflow.com/comment/88383376
answer count: 1
has comment: http://stackoverflow.com/comment/88384197
tagged with: x86-64
has comment: http://stackoverflow.com/comment/88386266
favorite count: 0
linked to: http://stackoverflow.com/q/47949930
tagged with: linux
tagged with: assembly
type: UnansweredQuestion
tagged with: python
score: 1
upvote count: 3
downvote count: 2
has comment: http://stackoverflow.com/comment/88384270
has body: I'm using Python 2.7 on 64-bit Linux. I have the following Python script witch should execute a simple Hello World shellcode. import urllib2 import ctypes shellcode = "\xb8\x01\x00\x00\x00\xbf\x01\x00\x00\x00\x48\xbe\xd8\x00\x60\x00\x00\x00\x00\xba\x0e\x00\x00\x00\x0f\x05\xb8\x3c\x00\x00\x00\xbf\x00\x00\x00\x00\x0f\x05" #Create buffer in memory shellcode_buffer = ctypes.create_string_buffer(shellcode, len(shellcode)) #Funktionszeiger shellcode_func = ctypes.cast(shellcode_buffer, ctypes.CFUNCTYPE(ctypes.c_void_p)) #Shellcode execute shellcode_func() If i run python Scriptname.py I get a memory access error. Anybody here have an idea why my script isn't working? EDIT: Original ASM Code: section .data text db "Hello",10 section .text global _start _start: ;syscall sys_write(1, text, 14) mov rax, 1 mov rdi, 1 mov rsi, text mov rdx, 14 syscall ;syscall sys_exit(0) mov rax, 60 mov rdi, 0 syscall
type: Question
has comment: http://stackoverflow.com/comment/88382550
has title: x86_64 Executing Shellcode fails:

http://stackoverflow.com/comment/88317170
type: QuestionComment
comment on: http://stackoverflow.com/q/50653293
score: 0
has text: I can't reproduce the error, are you sure it's an issue with the script?
type: Comment

http://stackoverflow.com/comment/88197075
has text: I realized that when I type in the full line I'm looking for, I'm able to locate it, but not when I just type in the key words.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50593629

http://stackoverflow.com/comment/88127366
score: 0
type: Comment
type: QuestionComment
has text: the expected output here is just to add 1 to columns a and b, and return c without modification (again, i realize the groupby is not necessary for this operation but in my use case it is necessary)
comment on: http://stackoverflow.com/q/50558229

http://stackoverflow.com/comment/88178511
has text: I am not sure to understand what you mean by replication of rows. But in the end I would have the rows duplicated depending on the lenght of the parameter in the linspace function. But the value in the column result is going to be different for each row
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50584059

http://stackoverflow.com/q/50601232
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/88211618
type: Question
has title: botocore.errorfactory.AuthorizationErrorException
has body: I am getting error like this: botocore.errorfactory.AuthorizationErrorException: An error occurred (AuthorizationError) when calling the Subscribe operation: User: arn:aws:iam::904851140766:user/xxxxx is not authorized to perform: SNS:Subscribe on resource: arn:aws:sns:us-east-1:141796722983 When using the following code: def subscribe_numbers_to_topic(self, data): #print data nums = data.get('numbers') result = {} topic_arn = data.get('topic_arn') def req(number): r = self.sns.subscribe( TopicArn=topic_arn, Protocol='sms', Endpoint=number )
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88212202
tagged with: python
has comment: http://stackoverflow.com/comment/88211857

http://stackoverflow.com/q/50696420
accepted answer: http://stackoverflow.com/a/50703879
type: AnsweredQuestion
has title: scala count word co-occurrence performance is really low
has body: While I was trying to implement a function to count word co-occurrences in scala, I found my function performance is really low. The word co-occurrences is: That's say we have a List[List[Int]] (actually a list of word list), we will generate a combination for each List[Int], then we merge all combination into a map and sum the value for each duplicate keys. Combination: [0,1,2] -> [((0,1),1),((0,2),1),((1,2),1)] Merge combination: [((0,1),1),((0,2),1),((1,2),1)] + [((0,1),1),((0,2),1),((1,2),1)] = HashMap{(0,1):2,(0,2):2,(1,2):2} Here's scala version: val arr = Array.range(0, 1000) val counter = scala.collection.mutable.HashMap[(Int, Int), Int]( ) arr.combinations(2).toArray.map{ row=&gt; val key = (row(0), row(1)) if (!counter.contains(key)) { counter(key) = 1 } else { counter(key) += 1 } } assert(counter.size == 499500) Scala version 2: val counter = arr.combinations(2).map(x =&gt; ((x(0),x(1)), 1)).toArray .groupBy(_._1).mapValues(_.map(_._2).sum) Here's python version: import itertools arr = range(0, 1000) combs = list(itertools.combinations(arr, 2)) counter = dict() for key in combs: try: counter[key] += 1 except KeyError: counter[key] = 1 assert len(counter) == 499500 Both scala version costs 9 seconds, while python version costs 1 seconds. I think I am definitely doing something wrong with the code, but I couldn't think of other ways to improve it (I am quite new to scala). Also, the reason I was using a mutable.HashMap is that I want to reduce memory usage. Any help would be appreciated, thanks.
type: Question
tagged with: performance
has comment: http://stackoverflow.com/comment/88402261
possible better answer: http://stackoverflow.com/a/50698160
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50703879
has answer: http://stackoverflow.com/a/50698160
tagged with: scala
tagged with: python

http://stackoverflow.com/q/50661736
has comment: http://stackoverflow.com/comment/88333688
tagged with: popen
tagged with: stdout
has body: I'm trying to use a python script to automate an interactive console application. (it's called BLEConsole and it's a microsoft store app https://www.microsoft.com/en-us/p/bleconsole/9p5662fdq58v , not sure if that's important. ) So I've been using os.popenX and subprocess.popen to launch and interact with it, and it's working fine... mostly ! inp,outp = os.popen4('BLEConsole.exe') inp.write('ls\n') # this one work inp.write('open #01\n') # this one don't generate any output for some reason inp.write('format hex\n') # and it's working again ?? inp.write('quit\n') print outp.read() some commands work and print to stdout but some other don't. they do work (the bluetooth device connects just fine) but i'm just unable to capture any output other than line breaks when executing this specific command. (yes it's supposed to output stuff, it does when I do it manually) edit : yes I'm checking both stdout and stderr Also I'm not able to capture the "BLE:" prompt using this method, I don't really need it but I don't understand why. Thanks for your help
has comment: http://stackoverflow.com/comment/88347167
type: Question
has comment: http://stackoverflow.com/comment/88333620
has comment: http://stackoverflow.com/comment/88343964
score: 0
tagged with: python-2.x
answer count: 0
tagged with: subprocess
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88334983
tagged with: python
has title: Unable to get the "whole" childprocess output when using Popen

sitemap
type: Tag
tag name: sitemap
tags question: http://stackoverflow.com/q/50687327

http://stackoverflow.com/comment/88182184
type: Comment
has text: I recommend using the Visual Studio IDE only version and telling it how to compile Python code.
type: QuestionComment
comment on: http://stackoverflow.com/q/50584900
score: 0

http://stackoverflow.com/comment/88168430
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50579572
score: 1
has text: You also could pass variable to Python scripts: `python 1.py "variable-value"`

http://stackoverflow.com/comment/88123643
score: 0
type: QuestionComment
has text: May be `plt.xticks(rotation=90)`?
type: Comment
comment on: http://stackoverflow.com/q/50556352

http://stackoverflow.com/q/50623184
has body: How can I parse all links in html, which contain link to *.rar file and download all these files? There are 3 links from html which I need to parse: &lt;a class="zlink" href="http://example.com/lv/20180530/L10.rar"&gt; &lt;a class="zlink" href="http://example.com/est/20180530/ES10.rar"&gt; &lt;a class="zlink" href="http://example.com/pol/20180530/PL10.rar"&gt; Html consists to another file type, like favicon or hmtl. import requests import urllib import random import threading from BeautifulSoup import BeautifulSoup user_agent_list = [ #Windows 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:60.0) Gecko/20100101 Firefox/60.0', #Linux 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:60.0) Gecko/20100101 Firefox/60.0', ] url = 'http://example.com' #Using Requests # establishing session s = requests.session() user_agent = random.choice(user_agent_list) headers = { 'login_username': 'user', 'login_password': 'pass', 'User-Agent': user_agent} response = requests.get(url,headers=headers) print(response.content) soup = BeautifulSoup(response.content) for link in soup.findAll('a', attrs={'href': re.compile("$rar")}) r = requests.get('href')
answer count: 0
favorite count: 0
tagged with: beautifulsoup
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/48227100
tagged with: parsing
has comment: http://stackoverflow.com/comment/88257843
has comment: http://stackoverflow.com/comment/88256359
has comment: http://stackoverflow.com/comment/88261806
has comment: http://stackoverflow.com/comment/88256873
score: 0
upvote count: 1
has title: How can I get href links from HTML and download files using Python?
downvote count: 1
has comment: http://stackoverflow.com/comment/88268719
type: UnansweredQuestion

http://stackoverflow.com/q/50593048
has comment: http://stackoverflow.com/comment/88195772
has body: So, what I want to do is a module which can automatically look for some things, but for that I need to take outputs from NMAP, specifically the Software Version. I have only written this, I just want to know how could i make this or if it is possible def check(): while True: cmd = raw_input("smb(check) &gt; ") This is an actual scan of NMAP PORT STATE SERVICE VERSION 21/tcp open ftp ProFTPD 1.3.5b What i want to do is to set that ProFTPD 1.3.5b as an object
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88195736
linked to: http://stackoverflow.com/q/89228
tagged with: python
has comment: http://stackoverflow.com/comment/88195449
has title: Take the output of another program in python
duplicate of: http://stackoverflow.com/q/89228
answer count: 0
score: 0
tagged with: nmap
has comment: http://stackoverflow.com/comment/88195789
has comment: http://stackoverflow.com/comment/88195813
type: Question
has comment: http://stackoverflow.com/comment/88195491
has comment: http://stackoverflow.com/comment/88195692
has comment: http://stackoverflow.com/comment/88195573
has comment: http://stackoverflow.com/comment/88195516

http://stackoverflow.com/q/50601877
score: 4
has comment: http://stackoverflow.com/comment/88212954
upvote count: 4
has comment: http://stackoverflow.com/comment/88213614
answer count: 2
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/72674843
has answer: http://stackoverflow.com/a/72674843
tagged with: tex
tagged with: python
has title: use format with tex fraction expression in matplotlib python
has answer: http://stackoverflow.com/a/50602072
type: AnsweredQuestion
has body: I use matplotlib. I need to get xlabels like: [1/8,2/8,3/8,4/8..14/8]. I want to make it in a loop. Therefore, for better view I use TEX in Python. For rendering the fraction expression in the loop I use .format method. But it doesn't work properly. There is some conflict between using of {} in TEX and .format method. I tried to use double {} but it as well doesn't work. import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) xax = ax.xaxis # get x axis labels = ['0'] for i in range(0, 14): labels.append(r'$\frac{}{8}$'.format(i)) # when trying to insert i an error occurs xax.set_ticklabels(labels) plt.show()
tagged with: matplotlib
type: Question
accepted answer: http://stackoverflow.com/a/50602072

http://stackoverflow.com/q/50584924
has comment: http://stackoverflow.com/comment/88201289
answer count: 0
tagged with: plotly
has title: Plotly county choropleth map
has comment: http://stackoverflow.com/comment/88179350
upvote count: 1
downvote count: 1
type: Question
score: 0
tagged with: visualization
has body: I was able to use county choropleth map created using create_choropleth function ( https://plot.ly/python/county-choropleth/ ). When we hover over county it shows data using County, State, FIPS and Value tag. Is there a way to customized this text so that it displays only county name and another tag attribute with a value. For example :- desired output - County : Westmoreland , Attribute1 : Value1 , Attribute 2 ;Value2. Example:- Original County Choloropleth Map Hover Text County: xx State:xx FIPS:xx Value:xx Expected County Choloropleth Map Hover Text County : xx Attribute 1 :Value 1 Attribute 2 :Value 2
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50687623
accepted answer: http://stackoverflow.com/a/50688669
answer count: 1
has body: I have a spatial and temporal df: 'date' 'spatial_pixel' 'column_A' ... ---- ----- --- 2012-04-01 | 1000 | 5 2012-04-01 | 1001 | 1 ... ... ... I want a column (groupedby 'spatial_pixel' and 'date') that counts the days-in-a-row a boolean is met. Say 'column_A' &lt; 2: 'date' 'spatial_pixel' 'column_A' 'days-in-a-row' ... ---- ----- --- ---- 2012-03-30 | 1001 | 5 | 0 2012-04-01 | 1001 | 1 | 1 2012-04-02 | 1001 | 1 | 2 2012-04-03 | 1001 | 3 | 0 ... ... ... ... My Attempts: First, I made a new dataframe that when the boolean is True ('column_A'&lt; 2) the monthly day number (e.g. 1,2,3,....28,29,30) is written. (However, I need it to range from 1-365, so that end of months and beginning of months are easily identified as consecutive). 'date' 'spatial_pixel' 'column_A' 'day' ... ---- ----- --- ---- 2012-03-30 | 1001 | 5 | NaN 2012-04-01 | 1001 | 1 | 1 2012-04-02 | 1001 | 1 | 2 2012-04-03 | 1001 | 3 | NaN 2012-04-30 | 1001 | 1 | 30 2012-04-31 | 1001 | 1 | 31 ... ... ... ... Second, I have unsuccessfully tried to create a new column that counts how many consecutive month days, using modified code from @ZJS: Pandas: conditional rolling count. def rolling_count(val): if val == rolling_count.previous + 1 : rolling_count.count +=1 else: rolling_count.previous = val rolling_count.count = 1 return rolling_count.count rolling_count.count = 0 #static variable rolling_count.previous = None #static variable df['count'] == df.groupby(['spatial_pixel','date'])['day'].apply(rolling_count) KeyError: 'count' Any help would be greatly appreciated!
has comment: http://stackoverflow.com/comment/88386924
tagged with: time-series
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/25119524
has comment: http://stackoverflow.com/comment/88385101
type: Question
has title: Calculating time series days-in-a-row that fit certain criteria
tagged with: pandas
tagged with: geospatial
tagged with: python
has answer: http://stackoverflow.com/a/50688669
score: 0

http://stackoverflow.com/q/50560801
downvote count: 0
has answer: http://stackoverflow.com/a/50578748
answer count: 1
has body: So I'm a little new to bonobo and am trying to figure it out. I am also new to python a little bit so this project has been a little intimidating. I am trying to convert a mysql (using SQLAlchemy as a service) input stream into an XML output. I have successfully set up my database stream, but I am kinda lost on how to create a transformation that will iterate over the result of my select. Anyone know of some examples of this? The official examples are simply calling built in writer functions (CsvWriter, etc). I need to write one that will write out XML. I have looked at the internal code for the build in bonobo writer functions, but I'm still confused on how to write my own writer. Does anyone know of some examples of a custom writer that's simple enough for a beginner. Or maybe can write a quick example of a VERY simple example that iterates over the results of a query? I am using bonobo_sqlalchemy.Select('SELECT * FROM UserData') as my first transformation in my chain, and I have been able to prettyprint the results of my select... so that's working. I just need an example transformation which iterates over the collection.
favorite count: 0
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
upvote count: 2
type: UnansweredQuestion
tagged with: etl
score: 2
has title: Need help writing a bonobo XML writer transformation after reading from MySQL(SQLAlchemy)
tagged with: mysql
type: Question
tagged with: bonobo-etl

http://stackoverflow.com/a/50568776
has body: Use map with a list-comprehension: [[int(''.join(map(str, x)))] for x in A] # [[123], [345], [357]]
answers question: http://stackoverflow.com/q/50568647
type: Answer
score: 0

http://stackoverflow.com/q/50551752
type: Question
has body: As i am new to python and ldap, please hep me convert the below shell code into python(version 2.6.6). can some pls explain what this below shell code does and what is the use of -b option here Shell code : ldapsearch -x -h ldap.bbc.network.lcl -p 3477 -b "DC=bbc,DC=network,DC=lcl" -D "CN=LDAP\, Mine,OU=Resource Accounts,OU=Enterprise,DC=bbc,DC=network,DC=lcl" -w f2oH@LQ^911 "center=1234"
has comment: http://stackoverflow.com/comment/88114403
has comment: http://stackoverflow.com/comment/88114458
has comment: http://stackoverflow.com/comment/88115099
has comment: http://stackoverflow.com/comment/88484566
has comment: http://stackoverflow.com/comment/88116036
tagged with: ldap
tagged with: bash
has answer: http://stackoverflow.com/a/50552385
answer count: 1
favorite count: 0
has title: Shell script to python script convertion
linked to: http://stackoverflow.com/q/89228
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50552385
upvote count: 2
score: 1
downvote count: 1

http://stackoverflow.com/q/50566855
has comment: http://stackoverflow.com/comment/88143906
has comment: http://stackoverflow.com/comment/88143838
has comment: http://stackoverflow.com/comment/88397895
type: Question
has comment: http://stackoverflow.com/comment/88143869
linked to: http://stackoverflow.com/q/27396781
has comment: http://stackoverflow.com/comment/88146129
duplicate of: http://stackoverflow.com/q/27396781
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88404691
has comment: http://stackoverflow.com/comment/88399575
has body: I know that there are some similar questions that already have been answered, but from what I understood, they were too specific, in order to be of any use for my problem. I also thought this might be interesting to anybody facing a similar problem in the future since a possible solution to this problem will most probably not be able to rely on any special characters, but solely on alpha-numeric characters. Link to the regex on regex101 If the link doesn't work, here's what I want to do: I want to extract Hello I want this to be matched World from this string: blablabla Hello blablablabla blablabla Hello blablabla blablabla blablabla Hello I want this to be matched World blablabla blablablablablablablablablablablabla in the shortest possible fashion. The problem here is that my regex will match from the very first occurence of Hello, which results in Hello blablablabla blablabla Hello blablabla blablabla blablabla Hello I want this to be matched World My problem is I don't know how many Hellos might occur between the first Hello and the Hello right before I want this... Does anybody know an elegant solution for this problem? Thanks in advance!
has comment: http://stackoverflow.com/comment/88143660
tagged with: python
tagged with: regex
has title: Is there a general way to match a non-greedy Regex from right to left?
answer count: 0
type: UnansweredQuestion
score: 0

http://stackoverflow.com/a/50615147
downvote count: 0
has comment: http://stackoverflow.com/comment/88241062
type: Answer
has comment: http://stackoverflow.com/comment/88240641
has comment: http://stackoverflow.com/comment/88240455
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88240636
has body: At a guess from the error that you're returning it could be to do with the datetime objects that are stored in your list, not converting to a string representation correctly. Wrapping these in str() might be the cause of your issue. Note the following example: &gt;&gt;&gt; import datetime &gt;&gt;&gt; datetime.datetime.now() datetime.datetime(2018, 5, 31, 8, 42, 48, 172575) &gt;&gt;&gt; str(datetime.datetime.now()) '2018-05-31 08:42:53.192586' Another option might be able to get rid your error by using json.dumps the list element to a json string format. But it depends on how you want to store your data in your database. See the following: &gt;&gt;&gt; import json &gt;&gt;&gt; element = ( ... 'AS0001', '1170', '1', '1', 'Unknown', '442', '1', '2018-05-28 23:00:00', '2018-03-15 11:15:00', '2018-03-15 10:56:00', ... '2018-05-28 23:18:26', '2018-05-28 23:59:22', '15177.3184', '15185.7562', '8.4378', '1313.0547', '1313.6179', '0.5632', ... '0.0000', '0.0000', '0.0000', '0.0000', '0.0000', '0.0000', '24.6518', '24.6518', '15101.7062', '0.0', '0.0', '0.0', ... '24.6563') &gt;&gt;&gt; json.dumps(element) '["AS0001", "1170", "1", "1", "Unknown", "442", "1", "2018-05-28 23:00:00", "2018-03-15 11:15:00", "2018-03-15 10:56:00", "2018-05-28 23:18:26", "2018-05-28 23:59:22", "15177.3184", "15185.7562", "8.4378", "1313.0547", "1313.6179", "0.5632", "0.0000", "0.0000", "0.0000", "0.0000", "0.0000", "0.0000", "24.6518", "24.6518", "15101.7062", "0.0", "0.0", "0.0", "24.6563"]' When retrieving this data you could then use json.loads to load it back into a python object format
has comment: http://stackoverflow.com/comment/88240271
answers question: http://stackoverflow.com/q/50615060

http://stackoverflow.com/q/50688943
has title: Appending a value to a list of lists
answer count: 1
type: UnansweredQuestion
has body: Here is a mock-example of what I'm trying to achieve: I have initially a list of empty lists of size 5: l = [[] for _ in range(5)] Then, in a for loop that does 4 iterations, I have function that returns a list of indexes. I'd like to append "t" to the lists with those indexes. Something like: for t in range(4): idx = function_that_gives_indexes() l[idx].append(t) Let's say that function_that_gives_indexes(), gives for each loop these value: [1], [2, 4], [] and [0, 1]. I'd like l to be: l = [[3], [0, 3], [1], [], [1]] What's the most pythonic way of doing this?
tagged with: python
tagged with: append
tagged with: list
type: Question
score: 0
has answer: http://stackoverflow.com/a/50689020

http://stackoverflow.com/a/50681870
score: 1
accepted answer of: http://stackoverflow.com/q/50681101
upvote count: 1
answers question: http://stackoverflow.com/q/50681101
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Your question is a bit unclear, but I think this is what you want to achieve - taking pairs of dates simultaneously and moving onto the next pair (n iterations), as opposed to two nested for loops (n2 iterations): #Create date lists first a = pd.date_range(start= '02/02/2017', end='06/02/2018', freq = 'D') b = pd.date_range(start= '02/01/2017', end='06/2/2018', freq = 'D') c = a.format(formatter=lambda x: x.strftime('%Y-%m-%d')) d = b.format(formatter=lambda x: x.strftime('%Y-%m-%d')) # Single for loop iterating over pairs of elements of c,d for date_to,date_from in zip(c,d): print("date_to has been picked up") print('date_from has been picked up') df = ek.get_news_headlines('R:AAPL.O AND Language:LEN', date_from = date_from , date_to = date_to, count=100) You may want to read up on how zip() works: https://docs.python.org/3.4/library/functions.html#zip

http://stackoverflow.com/q/50673163
favorite count: 0
score: 0
downvote count: 1
tagged with: python
tagged with: spacy
has answer: http://stackoverflow.com/a/50673194
accepted answer: http://stackoverflow.com/a/50673194
has body: Below is a function that marks verbs in sentences by adding an 'X' at the end of the verb word. This is done using spaCy for POS tagging. The function has an if-else statement inside a for loop (see below). The if statement checks whether a word is a verb to be marked, or not. However, I want to be able to skip the IF part once an n number of verbs has been found, and then only continue running with the rest of the function. I am aware this might be a simple or silly question and tried a while loop and continue but could not get this working. Is there a way to achieve this? def marking(row): chunks = [] for token in nlp(row): if token.tag_ == 'VB': # I would like to specify the n number of VB's to be found # once this is met, only run the else part chunks.append(token.text + 'X' + token.whitespace_) else: chunks.append(token.text_with_ws) L = "".join(chunks) return L
type: Question
type: AnsweredQuestion
tagged with: if-statement
tagged with: for-loop
upvote count: 1
has title: Given an IF-ELSE statement inside a for loop, can I only skip the IF when the condition is met once? python
answer count: 1

http://stackoverflow.com/a/50659467
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50656716
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50656716
has comment: http://stackoverflow.com/comment/88336666
type: Answer
has body: If super doesn't find something while looking through the method resolution order (MRO) to delegate to (or if you're looking for the attribute __class__) it will check its own attributes. Because object is always the last type in the MRO (at least to my knowledge it's always the last one) you effectively disabled the delegation and it will only check the super instance. I found the question really interesting so I went to the source code of super and in particular the delegation part (super.__getattribute__ (in CPython 3.6.5)) and I translated it (roughly) to pure Python accompanied by some additional comments of my own: class MySuper(object): def __init__(self, klass, instance): self.__thisclass__ = klass self.__self__ = instance self.__self_class__ = type(instance) def __repr__(self): # That's not in the original implementation, it's here for fun return 'hoho' def __getattribute__(self, name): su_type = object.__getattribute__(self, '__thisclass__') su_obj = object.__getattribute__(self, '__self__') su_obj_type = object.__getattribute__(self, '__self_class__') starttype = su_obj_type # If asked for the __class__ don't go looking for it in the MRO! if name == '__class__': return object.__getattribute__(self, '__class__') mro = starttype.mro() n = len(mro) # Jump ahead in the MRO to the passed in class # excluding the last one because that is skipped anyway. for i in range(0, n - 1): if mro[i] is su_type: break # The C code only increments by one here, but the C for loop # actually increases the i variable by one before the condition # is checked so to get the equivalent code one needs to increment # twice here. i += 2 # We're at the end of the MRO. Check if super has this attribute. if i &gt;= n: return object.__getattribute__(self, name) # Go up the MRO while True: tmp = mro[i] dict_ = tmp.__dict__ try: res = dict_[name] except: pass else: # We found a match, now go through the descriptor protocol # so that we get a bound method (or whatever is applicable) # for t…

http://stackoverflow.com/comment/88290935
has text: @jpp this isn't really surprising. Iterating over a generator takes a lot of overhead, but once you start working with something the size of `range(1000000)` then the generator expression beats the list-comprehension.
comment on: http://stackoverflow.com/a/50639183
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88191740
type: QuestionComment
comment on: http://stackoverflow.com/q/50591126
has text: Wait, how is this possible? Doesn't an array of identically shaped arrays automatically become a higher-dimensional array?
score: 1
type: Comment

http://stackoverflow.com/comment/88332226
comment on: http://stackoverflow.com/q/50646412
score: 0
type: Comment
type: QuestionComment
has text: @EdwardNedHarvey: no, this is something the child process does to the pipe on a SIGHUP. It may mean it is incompatible with your use-cases.

http://stackoverflow.com/comment/88379023
score: 1
type: QuestionComment
has text: Matplotlib automatically interrupts the line, where a NaN value is. To overcome this, is topic of [some question on SO](https://stackoverflow.com/q/14399689/8881141). So I don't know, why you need specific code for it.
type: Comment
comment on: http://stackoverflow.com/q/50683576

http://stackoverflow.com/q/50692568
has comment: http://stackoverflow.com/comment/88394582
answer count: 2
possible better answer: http://stackoverflow.com/a/50692629
accepted answer: http://stackoverflow.com/a/50692627
downvote count: 0
has body: In txt file, the data is written like this: A1|Auditorium1|Prote G A2|Auditorium1|Prote G A1 stands for label of auditorium, Auditorium1 stands for description, Prote G stands for address. Now, I want to make function for replacing label of auditorium with new one. I wanted to use the inputs: def label_change(): label_old = input("Enter label u wanna change: ") label_new = input("Enter new one: ") with open("aud.txt","r") as f1: for i in f1.readlines(): r = i.split("|") label = r[0] desc = r[1] adr = r[2] if label_old == label: label_new = label #now not sure how to continue For example, If I input A1 as an old label and A5 as a new label, can I somehow replace A1 with A5 without deleting or changing description and address in my file? After this I tried opening file in 'w' mode, so i can write, but it deletes every line and 'a' mode adds whole line instead of changing wanted label. Is there any easier method?
has answer: http://stackoverflow.com/a/50692629
favorite count: 0
tagged with: python-3.x
has title: changing part of file with input - python
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88394671
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50692627
type: Question
has comment: http://stackoverflow.com/comment/88394569

http://stackoverflow.com/comment/88307425
has text: i don't understand but may be `decimal` module in python or `numpy.nextafter()` can help.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50648329

http://stackoverflow.com/q/50690947
has body: I wrote the following code to generate a couple of charts using the plotly library: #Read the excel file from local spreadsheet df = pd.read_excel(r'C:\Users\llopez\Documents\Temp\Python finished goods.xlsx', sheet_name='Sheet1') #Create a dictionary of tuples by year dict_of_fgs = dict(tuple(df.groupby('Year'))) #Loop through the elements of the dictionary of finished goods and plots them grouping FG, type and calculating the sum of quantities. Stacking by type for k in dict_of_fgs: df_grouped = dict_of_fgs[k].groupby(['Finished_Good','Type'],sort=False)['Qty'].sum().unstack('Type').iplot(kind='bar',barmode='stack', title='FG Chart') It yields the following charts: The charts are exactly what I need, so now I'm looking for a way to generate a web-based report and share it with users. I looked into the following tutorial but I can't seem to adapt my code to this since my code loops through a dictionary and generates a plot for each key(Year). How can I generate a web-based report given the charts I've created? Thanks in advance to all of you subject matter experts for all the great ideas on how to achieve this. I appreciate the help.
score: -2
has comment: http://stackoverflow.com/comment/88393266
tagged with: stacked-chart
answer count: 2
tagged with: pandas
upvote count: 0
linked to: http://stackoverflow.com/q/9622163
has title: How to generate web based report from my python charts
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50710891
has answer: http://stackoverflow.com/a/50703885
tagged with: plotly
linked to: http://stackoverflow.com/q/50191208
downvote count: 2
type: Question

http://stackoverflow.com/q/50570040
has answer: http://stackoverflow.com/a/50570200
score: -1
upvote count: 0
answer count: 1
favorite count: 0
has title: conditional expression in kivy lang
accepted answer: http://stackoverflow.com/a/50570200
tagged with: python
tagged with: kivy
tagged with: kivy-language
downvote count: 1
type: Question
type: AnsweredQuestion
has body: I'm trying to chance the opacity of a button through "on-press" function. For example, on the kv file code below, I want to chance the opacity of the button (bt1) by pressing the Button A. So, by pressing the Button A it should check if the opacity of (bt1) is equal to 0, if its true, change it to 1, if its false it should change the opacity of (bt2) from 0 to 1. Any idea how to do it? Thanks in advance. FloatLayout: size_hint: None, None Button: id: bt1 pos: 200, 300 opacity: 0 on_press: self.opacity = 0 Button: id: bt2 pos: 300, 300 opacity: 0 on_press: self.opacity = 0 Button: id: bt3 pos: 400, 300 opacity: 0 on_press: self.opacity = 0 Button: pos: 0, 0 text: 'A' on_press: bt3.opacity = 1 if bt2.opacity == 1 else 0 bt2.opacity = 1 if bt1.opacity == 1 else 0 bt1.opacity = 1 if bt1.opacity == 0 else 1 Button: pos: 100, 0 text: 'B' on_press: bt3.opacity = 1 if bt2.opacity == 1 else 0 bt2.opacity = 1 if bt1.opacity == 1 else 0 bt1.opacity = 1 if bt1.opacity == 0 else 1 Button: pos: 200, 0 text: 'C' on_press: bt3.opacity = 1 if bt2.opacity == 1 else 0 bt2.opacity = 1 if bt1.opacity == 1 else 0 bt1.opacity = 1 if bt1.opacity == 0 else 1

http://stackoverflow.com/a/50682383
answers question: http://stackoverflow.com/q/50680355
has comment: http://stackoverflow.com/comment/88397425
has comment: http://stackoverflow.com/comment/88400377
has body: This is one way using np.random.randint with pd.Series.apply. Note I assume no reordering, which seems to be implied by your desired output. np.random.seed(0) def random_num(i): return str(np.random.randint(10**(i-1), 10**i)) df['Value'] = df['String'] + df['Length'].apply(random_num) print(df) String Length Value 0 A 2 A42 1 B 4 B3708 2 C 3 C906 3 D 2 D13
score: 0
has comment: http://stackoverflow.com/comment/88392921
type: Answer
has comment: http://stackoverflow.com/comment/88400172

http://stackoverflow.com/a/50551475
has body: It's a little bit difficult to read through the error without code blocks, but after sifting a bit, the trace reads, FileNotFoundError: [Errno2] No such file or directory: '\Users\Alex\Documents\Python\Übung\example1.xlxs' And in your code, you have wb = openpyxl.load_workbook("\Users\Alex\Documents\Python\Übung\example1.xlxs") So, it seems you haven't supplied the full path, you're missing the C:\ portion. Could it be as easy as that? Feel free to post back after confirming you've correctly entered the file path.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50551404

http://stackoverflow.com/comment/88285752
type: QuestionComment
comment on: http://stackoverflow.com/q/50625163
type: Comment
has text: Still not seeing where you print the User object.
score: 0

http://stackoverflow.com/comment/124680373
comment on: http://stackoverflow.com/a/50554223
type: AnswerComment
has text: I tried this but all my dates came out as NaT. Suggestions?
score: 0
type: Comment

http://stackoverflow.com/q/50606874
has title: How to find a specific substring in a specific range in Python
type: Question
score: -2
has comment: http://stackoverflow.com/comment/88223802
downvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/50607012
tagged with: string
accepted answer: http://stackoverflow.com/a/50607012
linked to: http://stackoverflow.com/q/509211
favorite count: 0
has comment: http://stackoverflow.com/comment/88223626
has comment: http://stackoverflow.com/comment/88223740
tagged with: python
has comment: http://stackoverflow.com/comment/88223442
type: AnsweredQuestion
upvote count: 0
has body: I have a file that contains a String and i want to search for a substring in a specific range, This is my string: newick; ((raccoon,bear),((sea_lion, seal),((monkey,cat), weasel)),dog); And this is my code for it: def removeNewick(tree): for x in tree: new_set = x.replace('newick;', '') print(new_set) filepath = "C:\\Users\\msi gaming\\Desktop\\small_tree.tre" tree = open(filepath) removeNewick(tree) But i know for sure that if this string 'newick' is going to appear, then it would be in the first 10 characters of the string so how do i edit my for loop only to loop over the first ten characters?
has comment: http://stackoverflow.com/comment/88223580

http://stackoverflow.com/q/50677554
type: Question
score: 3
has comment: http://stackoverflow.com/comment/88365179
tagged with: dataframe
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/88365223
has comment: http://stackoverflow.com/comment/88365102
answer count: 1
has comment: http://stackoverflow.com/comment/88364730
favorite count: 0
upvote count: 3
has body: I have a dataframe having column a,b,c. And column c has data in list datatype. So I want to unwind/unpacked/explode the each element of list as new row. so, our input is like below. a b c 0 1 2 [1, {'k': 1}, 2] 1 3 2 [{'m': 2}, {'k': 2}, 2] And our output should be like below. a b c 0 1 2 1 1 1 2 {'k': 1} 2 1 2 2 3 3 2 {'m': 2} 4 3 2 {'k': 2} 5 3 2 2 Sp, as you can in output, each element of list is in row and other column a and b values are repeating corresponding to list element
has comment: http://stackoverflow.com/comment/88446407
tagged with: pandas
has comment: http://stackoverflow.com/comment/88364640
tagged with: python
has title: unpack list in pandas dataframe python
duplicate of: http://stackoverflow.com/q/27263805
downvote count: 0
has answer: http://stackoverflow.com/a/70230580
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88364892
linked to: http://stackoverflow.com/q/27263805

http://stackoverflow.com/a/50563551
answers question: http://stackoverflow.com/q/50562822
type: Answer
has comment: http://stackoverflow.com/comment/104134838
has body: Seems to work ok for me? This is my implementation of your code import datetime def create_url(check_in): """take date such as '2018-06-05' and transform to format '06%2F05%2F2018'""" _check_in = check_in.strftime("%Y-%m-%d") _check_in = _check_in.split("-") _check_in = _check_in[1] + "%2F" + _check_in[2] + "%2F" + _check_in[0] return "https://www.website.com/?arrival={0}".format(_check_in) today = datetime.date.today() print(create_url(today)) &gt;&gt;&gt; https://www.website.com/?arrival=05%2F28%2F2018
has comment: http://stackoverflow.com/comment/88137496
score: 0

http://stackoverflow.com/comment/88128885
has text: The `?` in the string is making an issue. You need a mechanism to make an exact match for that string. You can do `ind = i.index('?') ; i = i[:ind] + "\\" + i[ind:]` to append `\\` in the string so that it will take ``?` as an actual character in your search.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50559045

http://stackoverflow.com/comment/88102622
score: 0
type: Comment
has text: Shoot, you're totally right, I added an extra quotation mark
comment on: http://stackoverflow.com/a/50545715
type: AnswerComment

http://stackoverflow.com/a/50557221
has body: Use requests library instead, this works: import requests #opening up connection and grabbing page response = requests.get(atd_url,headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'}) #html parsing page_soup = soup(response.content, "html.parser")
downvote count: 0
answers question: http://stackoverflow.com/q/50556841
score: 4
type: AcceptedAnswer
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50556841

http://stackoverflow.com/q/50587076
tagged with: flask
score: 0
has comment: http://stackoverflow.com/comment/88183488
has title: 'Bad request' error on flask
linked to: http://stackoverflow.com/q/39996133
duplicate of: http://stackoverflow.com/q/39996133
has comment: http://stackoverflow.com/comment/88184363
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/88183471
has body: I think my problem is that flask can't find the key and value of my java script. So, how can I fix it? Here is my python: def ledStudy_handler(): if request.form['study'] == "on": GPIO.output(11, GPIO.HIGH) print("lights on") elif request.form['study'] == "off": GPIO.output(11, GPIO.LOW) print("lights off") return render_template("home.html") And here is my js: function ledStudy() { var checkStudy = document.getElementById("checkStudy"); if (checkStudy.checked == true){ var checkStudy.study = "on"; } else { var checkStudy.study = "off"; } }
type: Question
tagged with: javascript

http://stackoverflow.com/a/50645249
type: Answer
downvote count: 1
upvote count: 1
score: 0
has body: You don't need to pickle it, h2o provides its own persistence methods: http://docs.h2o.ai/h2o/latest-stable/h2o-docs/save-and-load-model.html # build the model model = H2ODeepLearningEstimator(params) model.train(params) # save the model model_path = h2o.save_model(model=model, path="/tmp/mymodel", force=True) print(model_path) # outputs: /tmp/mymodel/DeepLearning_model_python_1441838096933 # load the model saved_model = h2o.load_model(model_path) be warned though, persisted models are NOT compatible between even the most minor version changes i.e. if you train and save a model in 3.18.0.1 you won't be able to load it in 3.18.0.2
has comment: http://stackoverflow.com/comment/88335494
answers question: http://stackoverflow.com/q/50642358

http://stackoverflow.com/a/50660621
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50657628
answers question: http://stackoverflow.com/q/50657628
type: Answer
score: 0
has body: ✓ @vidit02100, the problem is really very interesting. As I understood from your code, you want to only print the name of image files present inside 10k directory. In image, you have not commented the lines which you have commented in the problem's code. If you will show full code and tell about the number of images inside 10k directory then it would be much better for me to help you. May be your code will be printing the images in reverse order if there will be +10000 images inside 10k. Please check and let me know. ✓ As I know, jpg, jpeg &amp; png are the most popular image file extensions that ends with g. ✓ So place all these extensions in one list and use another for loop to iterate over it and place your code inside it. Please comment if my suggestion doesn't satisfy your need. I will update my answer based on your provided inputs and outputs. ✓ Here is your modified code. main_file = '10k' file_formats = ["png", "jpg", "jpeg"] for file_format in file_formats: path = os.path.join(main_file, '*.' + file_format ) files = glob.glob(path) for f1 in files: fstr = str(f1) print(fstr)

http://stackoverflow.com/comment/106707185
comment on: http://stackoverflow.com/a/50586265
score: 0
type: AnswerComment
type: Comment
has text: idxmax() will give you the maximum value which happen to be the first value of the columns (top-down) in this case. What would be the best way to detect the first non-zero value?

http://stackoverflow.com/comment/88312868
has text: @Chrysna Refer to Andrii Glukhyi's solution below if you want to perform the check on all the sublists.
type: Comment
comment on: http://stackoverflow.com/a/50634316
type: AnswerComment
score: 0

http://stackoverflow.com/q/50543136
has comment: http://stackoverflow.com/comment/88097455
type: AnsweredQuestion
upvote count: 0
linked to: http://stackoverflow.com/q/5658369
type: Question
answer count: 2
duplicate of: http://stackoverflow.com/q/5658369
score: -2
has answer: http://stackoverflow.com/a/50543224
has body: I'm trying to match, last letter in string 'onlin' as any and then replace it if it matches with word offline. No luck. Please give advice, cheers. import mitmproxy import re def response(flow): old = b'Onlin\w{1}' new = b'Offline' flow.response.content = flow.response.content.replace(old, new)
tagged with: wildcard
has answer: http://stackoverflow.com/a/50543198
downvote count: 2
accepted answer: http://stackoverflow.com/a/50543198
possible better answer: http://stackoverflow.com/a/50543224
tagged with: mitmproxy
tagged with: regex
favorite count: 0
has comment: http://stackoverflow.com/comment/88097524
has comment: http://stackoverflow.com/comment/88097401
tagged with: python
has comment: http://stackoverflow.com/comment/88097447
has title: Python regex help :)?

http://stackoverflow.com/comment/88179752
comment on: http://stackoverflow.com/q/50584589
type: Comment
has text: The output I expect is all the pairs of coordinates.
score: 0
type: QuestionComment

http://stackoverflow.com/q/50635610
has title: 'Axes3DSubplot' object has no attribute 'voxels'
upvote count: 3
answer count: 2
has answer: http://stackoverflow.com/a/50635740
accepted answer: http://stackoverflow.com/a/50638840
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50638840
tagged with: voxels
type: AnsweredQuestion
score: 3
downvote count: 0
tagged with: matplotlib
possible better answer: http://stackoverflow.com/a/50635740
type: Question
has body: I'm trying to use matplotlib to display some 3d perlin noise. I have read that the voxels method from Axes3DSubplot could be used to simply display values. However, when I try and call ax.voxels(voxels, facecolors=colors, edgecolor='k'), it throws the exception AttributeError: 'Axes3DSubplot' object has no attribute 'voxels'. Here is my code: import noise import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D x, y, z = np.indices((8,8,8)) voxels = np.zeros((8,8,8), dtype=np.bool) for xp in range(8): for yp in range(8): for zp in range(8): voxels[xp,yp,zp] = True if abs(noise.pnoise3(xp/8,yp/8,zp/8)) &gt; 0.5 else False colors = np.empty(voxels.shape, dtype=object) colors[voxels] = 'green' fig = plt.figure() ax = fig.gca(projection='3d') ax.voxels(voxels, facecolors=colors, edgecolor='k') #EXCEPTION plt.show() My python version is 3.6.2 (Anaconda 64-bit). My matplotlib version is 2.0.2. I have used both the ipynb (module://backend_interagg) and Qt5Agg backends, which both give the same problem. I'm running Windows 10.

http://stackoverflow.com/comment/88337158
type: Comment
comment on: http://stackoverflow.com/a/50602377
has text: you can store the company name in the same way, either having a different variable keep the company name for highest value or store both in dict as key value pair.
type: AnswerComment
score: 0

http://stackoverflow.com/q/50565860
has body: I am trying to write a part of program where the user inputs a Target Word (targetWord = input()), assigns a nested Dictionary with the key being the same as the input word. For example: mainDict = { 'x': {'one': 1, 'blue': 1, 'green' :1}, 'y': {'red': 1, 'blue': 2, 'two': 1}, 'z': {'one': 1, 'green': 1, 'red': 1} } where all the values in the nested dictionary are assigned integers. The user may input 'x', to which the program will assign: targetDict = mainDict['x'] The program should then allow the user to input words again, but this time every single word from input is appended to a lookup list, for example user inputs 'y', then 'z': lookup = ['y', 'z'] Then the program should run through the nested dictionary and for every value with the corresponding key as in the targetDict, append just values to a new nested list and add whatever value the nested Dictionary values are. So the output of this section should be: targetOutput = [[2], [1, 1]] because in nested dict 'y', only 'blue' was a common key, to which its value 2 was put in a list, then appended onto targetOutput. The same case with dict 'z', where the keys 'one' and 'green' were present in both 'x' and 'z', putting their values, 1 and 1 into a nested list. Here is a representation of the dysfunctional code I have for: targetOutput = [] targetDict = mainDict[targetWord] for tkey in targetDict: tt = [] for word in lookup: for wkey in primaryDict[word]: if tkey == wkey: tt.append(targetDict[tkey]) tl.append(sum(tt)) print((pl)) The sum function at the end is because my actually final output should be the sum of the values in the nested list, akin to: tl = [[2], [2]] I am also trying to make the reverse happen, where in another list for every key in the lookup, it returns a nested list containing the sum of every value the targetWord dictionary also has a key for, like: ll = [[2], [2]] My question is, how do I fix my code so that it outputs the 2 above lists? I'm quite new with dictionaries.
has answer: http://stackoverflow.com/a/50566015
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/88142023
tagged with: dictionary
type: AnsweredQuestion
score: 3
tagged with: list
accepted answer: http://stackoverflow.com/a/50566015
downvote count: 1
type: Question
upvote count: 4
tagged with: sum
has comment: http://stackoverflow.com/comment/88142220
has title: Getting Lists of Summed Nested Dictionary Values

http://stackoverflow.com/a/50655866
score: 6
has comment: http://stackoverflow.com/comment/125113744
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/50654620
has body: I recently proposed an easy way to add a legend to a scatter, see GitHub PR. This is still being discussed. In the meantime you need to manually create your legend from the unique labels in y. For each of them you'd create a Line2D object with the same marker as is used in the scatter plot and supply them as argument to plt.legend. scatter = plt.scatter(xs * scalex,ys * scaley, c = y) labels = np.unique(y) handles = [plt.Line2D([],[],marker="o", ls="", color=scatter.cmap(scatter.norm(yi))) for yi in labels] plt.legend(handles, labels)
answers question: http://stackoverflow.com/q/50654620
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88221861
score: 1
comment on: http://stackoverflow.com/q/50606139
type: QuestionComment
has text: Try printing `AdaBoost`. What does it look like?
type: Comment

relative-path
type: Tag
tag name: relative-path
tags question: http://stackoverflow.com/q/50578323

http://stackoverflow.com/q/50593590
has comment: http://stackoverflow.com/comment/88221030
linked to: http://stackoverflow.com/q/4956984
linked to: http://stackoverflow.com/q/17710748
tagged with: pandas
has comment: http://stackoverflow.com/comment/88218233
has comment: http://stackoverflow.com/comment/88197735
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88197987
tagged with: python-3.x
tagged with: exception
has comment: http://stackoverflow.com/comment/88196520
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has body: I am getting a memory error every time I am trying to write into csv. So the first 5 GB of Data works fine but then I get an Memory error. I dont know why because I am trying to clear every time my elem from the memory so it should not happen. def writeDataCSV(file): try: with open('Data/csv/'+file+'.csv','w') as fp: for evt, elem in iterparse('dumpData/'+str(filename)+'.xml', events=('end',)): if elem.tag == 'row': element_fields = elem.attrib data = [] if(file== "Comments"): data = commentsXML(element_fields) wr = csv.writer(fp, dialect='excel') wr.writerow(data) elem.clear() fp.close except UnicodeEncodeError as uniError: print(uniError) try: if(file== "Comments"): df = pd.read_csv('Data/csv/Comments.csv', names=["Id","PostId","Score","Text","Date","Time","UserID"]) df.to_csv("Data/csv/Comments.csv") except UnicodeDecodeError as uniDeError: print(uniDeError) MemoryError
tagged with: python
has answer: http://stackoverflow.com/a/50594012
has comment: http://stackoverflow.com/comment/88197665
linked to: http://stackoverflow.com/q/519633
score: -1
has comment: http://stackoverflow.com/comment/88220981
linked to: http://stackoverflow.com/q/25962114
upvote count: 2
downvote count: 3
has comment: http://stackoverflow.com/comment/88197562
has title: MemoryError while writing huge CSV file
has comment: http://stackoverflow.com/comment/88221069
type: Question
has comment: http://stackoverflow.com/comment/88196914
has comment: http://stackoverflow.com/comment/88197653
has comment: http://stackoverflow.com/comment/88197542
linked to: http://stackoverflow.com/q/44122943

http://stackoverflow.com/q/50695427
has answer: http://stackoverflow.com/a/50702671
has body: I'm trying out Watson Studio model for Naive Bayes model.In my app I need to delete old deployment model and add new one. Is it possible to delete such model using the python API?
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50702671
has title: How to delete model - IBM Watson
type: Question
tagged with: ibm-cloud
tagged with: naivebayes
tagged with: watson
score: 0
answer count: 1

http://stackoverflow.com/q/50662745
answer count: 2
has comment: http://stackoverflow.com/comment/88336070
tagged with: pandas
has body: I have this dataframe: a b c Utah 0.907184 0.000049 0.550308 NY 0.129423 1.606726 2.041340 DC 0.228202 1.041567 0.007727 Texas 0.947254 0.000211 0.346336 I want to apply this function to my dataframe: func=lambda x: max(x)-min(x) When I call df.apply(func), it applies the function to each column: a 0.817831 b 1.606677 c 2.033613 dtype: float64 I want to calculate the maximum value in my dataframe (2.041340, NY) minus the minimum value (0.000049, Utah) and return 2.041291
favorite count: 0
possible better answer: http://stackoverflow.com/a/50662783
has comment: http://stackoverflow.com/comment/88335662
tagged with: python
has comment: http://stackoverflow.com/comment/88335681
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50662795
accepted answer: http://stackoverflow.com/a/50662795
downvote count: 3
upvote count: 1
type: Question
has title: Calculate maximum-minimum of DataFrame
has comment: http://stackoverflow.com/comment/88336081
has answer: http://stackoverflow.com/a/50662783
score: -2

http://stackoverflow.com/a/50567555
downvote count: 0
has body: Use melt, filter 1 and last join values per groups with ,: df = pd.DataFrame({ 'id': ['01','02','03'], 'Apple': [1,0,0], 'Apricot': [1,0,0], 'Banana': [0,1,0], 'Climentine': [0,1,0], 'Orange': [0,1,1], 'Pear': [0,1,0], 'Pineapple': [0,0,1] }) df = (df.melt('id', var_name='fruits').query('value == 1') .groupby('id')['fruits'] .apply(', '.join) .reset_index()) print (df) # id fruits #0 1 Apple, Apricot #1 2 Banana, Climentine, Orange, Pear #2 3 Orange, Pineapple For better performance use dot for matrix multiplication: df = df.set_index('id') df = df.dot(df.columns + ', ').str.rstrip(', ').reset_index(name='fruit') print (df) id fruit 0 01 Apple, Apricot 1 02 Banana, Climentine, Orange, Pear 2 03 Orange, Pineapple
score: 5
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50559480
accepted answer of: http://stackoverflow.com/q/50559480
type: Answer
upvote count: 5

http://stackoverflow.com/comment/88145239
type: QuestionComment
has text: I'd locate the "?" token, and would extract the tokens (with an even number of open/close parens) to get the left & right tokens, then same thing for the rightmost token of `:`. Works if there aren't any nested "?" expressions
comment on: http://stackoverflow.com/q/50567457
score: 0
type: Comment

http://stackoverflow.com/q/50599934
downvote count: 0
has body: I have a dataframe like - FileName PageNo LineNo EntityName 1 17743633 - 1 TM000002 69 Ambuja Cement Limited 2 17743633 - 1 TM000003 14 Vessel Name 3 17743633 - 1 TM000003 12 tyre Chips (Shredded Tyres) 4 17743633 - 1 TM000006 22 ambuja Cement Limited 5 17743633 - 1 TM000006 28 Binani Cement Limited I have to remove those rows from the datframe in which EntityName column's first letter is lowercase. i.e I have to retain values that start with a upper case. I have used to methods till now - df['EntityName'] = map(lambda x: x[0].isupper(), df['EntityName']) but it is giving NaN values. another thing that i tried was regex. df['EntityName'] = df['EntityName'].str.replace('^[a-z]+$','') but it is showing no effect. another one was - qw = df.EntityName.str[0] df = df[qw.isupper()] but it is showing error - 'Series' object has no attribute 'isupper' Can someone suggest me the correct code snippet or any kind of hint?
has answer: http://stackoverflow.com/a/50600501
tagged with: string
favorite count: 0
possible better answer: http://stackoverflow.com/a/50600854
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50600854
tagged with: python
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50600019
type: Question
has title: Removing rows from dataframe whose first letter is in lowercase
upvote count: 5
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88209025
has comment: http://stackoverflow.com/comment/88208998
has answer: http://stackoverflow.com/a/50600020
score: 5
accepted answer: http://stackoverflow.com/a/50600019
tagged with: pandas

http://stackoverflow.com/q/50698180
tagged with: pandas
has comment: http://stackoverflow.com/comment/88412790
has title: sort_values() got an unexpected keyword argument 'by'
has answer: http://stackoverflow.com/a/50698492
favorite count: 0
has body: for i in str_list: #str_list is a set contain some strings df.loc[i].sort_values(by = 'XXX') **TypeError**: sort_values() got an unexpected keyword argument 'by' ". &gt;&gt;&gt; type(df.loc[i]) &gt;&gt;&gt; pandas.core.frame.DataFrame But it works outside the for loop! df.loc['string'].sort_values(by = 'XXX') &gt;&gt;&gt; type(df.loc['string']) &gt;&gt;&gt; pandas.core.frame.DataFrame I'm confused.
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/60261384
type: Question
answer count: 2
score: 18
downvote count: 0
tagged with: dataframe
upvote count: 18

http://stackoverflow.com/comment/88339716
type: QuestionComment
comment on: http://stackoverflow.com/q/50664425
score: 0
has text: Welcome to Stack Overflow! Please apply a title that summarizes the problem instead of code as explained in [ask].
type: Comment

http://stackoverflow.com/comment/88407895
type: Comment
comment on: http://stackoverflow.com/a/50698328
has text: Updated with a better one-liner
type: AnswerComment
score: 0

http://stackoverflow.com/q/50591619
has comment: http://stackoverflow.com/comment/88194649
answer count: 0
tagged with: pycharm
type: Question
score: 5
upvote count: 5
has title: pycharm sqlalchemy Base constructor signature typing
has body: The suggestion is important on screenshot. How does pycharm know UserMessage's constructor signature and even its argument types from defined static properties? Can i achive the same static type checking for my classes, that work similar to Base (make constructor from class static props (types of which are also defined explicitly)) or it is pycharm compatibility with sqlalchemy? db.base: from sqlalchemy.ext.declarative import declarative_base Base = declarative_base()
has comment: http://stackoverflow.com/comment/88259366
has comment: http://stackoverflow.com/comment/88547044
downvote count: 0
tagged with: python-typing
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50565937
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/56091174
tagged with: normalization
answer count: 2
score: 18
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/50567308
favorite count: 0
tagged with: sklearn-pandas
has comment: http://stackoverflow.com/comment/88142164
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
upvote count: 19
has answer: http://stackoverflow.com/a/50567308
has title: How to normalize the Train and Test data using MinMaxScaler sklearn
has body: So, I have this doubt and have been looking for answers. So the question is when I use, from sklearn import preprocessing min_max_scaler = preprocessing.MinMaxScaler() df = pd.DataFrame({'A':[1,2,3,7,9,15,16,1,5,6,2,4,8,9],'B':[15,12,10,11,8,14,17,20,4,12,4,5,17,19],'C':['Y','Y','Y','Y','N','N','N','Y','N','Y','N','N','Y','Y']}) df'A','B' = min_max_scaler.fit_transform(df'A','B') df['C'] = df['C'].apply(lambda x: 0 if x.strip()=='N' else 1) After which I will train and test the model (A,B as features, C as Label) and get some accuracy score. Now my doubt is, what happens when I have to predict the label for new set of data. Say, df = pd.DataFrame({'A':[25,67,24,76,23],'B':[2,54,22,75,19]}) Because when I normalize the column the values of A and B will be changed according to the new data, not the data which the model will be trained on. So, now my data after the data preparation step that is as below, will be. data'A','B' = min_max_scaler.fit_transform(data'A','B') Values of A and B will change with respect to the Max and Min value of df'A','B'. The data prep of df'A','B' is with respect to Min Max of df'A','B'. How can the data preparation be valid with respect to different numbers relate? I don't understand how the prediction will be correct here.
possible better answer: http://stackoverflow.com/a/56091174

http://stackoverflow.com/q/50675417
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/89435500
accepted answer: http://stackoverflow.com/a/51230685
has title: Providing Backwards Compatability with Python 3.6 Variable Annotations
upvote count: 8
type: Question
tagged with: backwards-compatibility
has comment: http://stackoverflow.com/comment/89245678
has answer: http://stackoverflow.com/a/51230685
tagged with: python-3.6
answer count: 1
has comment: http://stackoverflow.com/comment/89252591
favorite count: 0
has body: I am trying to create a python package (not anywhere at the moment) and I want to use 3.6 python variable annotations, that is foo: int = 5 while still providing support for Python 3.5. Is there any way to provide these style of variable annotations inside Python 3.5, either through a from __future__ import variable_annotations or similar. I know it is possible to use comment type annotations, but I would like to be able to use this style.
tagged with: typechecking
tagged with: python
score: 8

http://stackoverflow.com/comment/88230869
has text: `def __iter__(self): return self` in `IterATOR`: done
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50610455

http://stackoverflow.com/q/50629805
tagged with: generate
type: Question
has comment: http://stackoverflow.com/comment/88269696
tagged with: formula
score: 0
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/50630033
type: UnansweredQuestion
has body: I'm manipulating some excel files, merging them en calculating balances. Because after the script is done some changes could be required I prefer a formula for balance over a calculated balance amount (this is working already). So I need python to create formulas which I will put into a pandas column and replace the old column with the new one. Now I don't understand how to generate the following: =IF(Q3="some text",W2,W2+U3)) =IF(Q4="some text",W3,W3+U4)) etc This formula works within Excel.
tagged with: python
has title: Writing sequence of formulas to Excel with Python

http://stackoverflow.com/a/50569617
downvote count: 0
has body: I found the answer myself, the default value for min_count is 5 and I had no words with a counter of 5 or more. I just had to change this line of code: model = Doc2Vec(min_count=0, alpha=0.025, min_alpha=0.025)
answers question: http://stackoverflow.com/q/50569110
has comment: http://stackoverflow.com/comment/88232429
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50569110
has comment: http://stackoverflow.com/comment/88248668
type: AcceptedAnswer

http://stackoverflow.com/comment/88164213
type: AnswerComment
comment on: http://stackoverflow.com/a/50577242
score: 0
type: Comment
has text: Perfect! Thank you very much for your help. It works great as exactly I want. Can you please try to explain how the names.pop(0) work in the codes?

http://stackoverflow.com/a/50704400
upvote count: 3
has body: I would recommend loading your original csv as a dataframe and then sorting it by a particular column. I've provided a fully reproducible example below that illustrates this. I make my own version of sort.csv for demonstration purposes, then read it in as a dataframe using pandas.read_csv, and then sort using pandas.DataFrame.sort_values. import pandas as pd sort = open('sort.csv', 'w+') sort.write('May, 5227\n') sort.write('June, 417\n') sort.write('Jan, 4\n') sort.write('Feb, 424\n') sort.write('Dec, 36\n') sort.write('Mar, 4981\n') sort.write('Apr, 3460\n') sort.close() df = pd.read_csv('sort.csv', names = ['words', 'Numbers']) df = df.sort_values(['Numbers'], ascending=[False]) writer = pd.ExcelWriter('wordsandnumbers.xlsx', engine='xlsxwriter') df.to_excel(writer, index=False, startrow=2) writer.save() Outputted sort.csv: Outputted wordsandnumbers.xlsx:
type: Answer
score: 3
answers question: http://stackoverflow.com/q/50698609
downvote count: 0

http://stackoverflow.com/comment/88414878
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50671502
has text: Are you trying to achieve an effect like in [this example](https://stackoverflow.com/a/42174811/6220679) (without the limit)?
score: 0

http://stackoverflow.com/comment/88115714
has text: @TommyOfinger: You can also use: `odeint` in `scipy` here: https://docs.scipy.org/doc/scipy-0.17.0/reference/generated/scipy.integrate.odeint.html
comment on: http://stackoverflow.com/a/50552395
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50553325
type: AcceptedAnswer
score: 0
has body: You may use a dictionary STD to store your data. Read the user inputs and store each input and it's corresponding data as key and value in a dictionary the_result. Finally, the key corresponding to the largest value in dictionary the_result is the largest item. import operator STD = {'seventy-five': 0.050, 'states': 0.719, 'drainage-basin': 0.037, 'scotland': 0.037, 'reading': 0.123, 'thirty-eight': 0.000, 'almost': 0.037, 'rhine': 0.000, 'proper': 0.037, 'contrary': 0.087} print("Enter query words, one per line. Blank line to end: ") result = [] while True: line = input() if line: result.append(line) else: break the_result = {} for each in result: if each in STD: the_result.update({each: STD[each]}) print("{} {}".format(each, STD[each])) else: print("{} not in list".format(each)) print("largest value is {}".format(max(the_result.items(), key=operator.itemgetter(1))[0]))
type: Answer
accepted answer of: http://stackoverflow.com/q/50552940
answers question: http://stackoverflow.com/q/50552940

http://stackoverflow.com/comment/88293419
score: 0
has text: I did as you said add `conf_mat = tf.confusion_matrix(y_true_cls, y_pred_cls, FLAGS.num_classes)` before starting my `tf.Session()` and within the loop I did `acc, loss , conf_m= sess.run([accuracy, cost, conf_mat], feed_dict={x: batch_tx, y_true: batch_ty})` but still getting confusion matrix for a batch and I need to sum up the confusion matrix of all batchs to get a full confusion matrix which results is exaclty same as I did before.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50640254

http://stackoverflow.com/comment/88315966
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50652620
has text: @Geek right -- that's part of the job of your pathfinding algorithm (not included here). This problem is generalized to "How can I find out what combination of an iterator maximizes a certain utility function."

http://stackoverflow.com/comment/88138947
type: Comment
type: QuestionComment
has text: Thank you that was helpful, you know any ALTS for amazon s3 that I can use?
comment on: http://stackoverflow.com/q/50564053
score: 0

http://stackoverflow.com/comment/88371048
comment on: http://stackoverflow.com/a/50680713
score: 0
has text: I am not fixed to the standard library "trace". I could use a different library, if it provides the needed feature.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88359389
type: Comment
has text: @user2675516 Yeah, I suspected something like that. I think it could be worthwhile to open an issue on the scipy bug tracker.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50660619

http://stackoverflow.com/a/50563764
accepted answer of: http://stackoverflow.com/q/50563497
type: Answer
has comment: http://stackoverflow.com/comment/88137938
answers question: http://stackoverflow.com/q/50563497
has body: Although the comment by @jonrsharpe is the right answer, it wasn't trivial to me, and maybe also to you, so I'll break it down: The expression is evaluated like this: 3 &gt; 5 in range(10) 3 &gt; 5 and 5 in range(10) False and 5 in range(10) == False (False and ... short circuits to False) The reason for 1 -&gt; 2 is explained in the documentation. To sum it up, it's like x &lt; y &lt; z means x &lt; y and y &lt; z. Trying something like (3 &gt; 5) in range(10) would be evaluated like this: (3 &gt; 5) in range(10) False in range(10) 0 in range(10) True The reason for 3 -&gt; 4 is that 0 resides inside the range(0,10) and the expression 0 in range(10) is evaluated to a Boolean result (i.e. True or False) depends on whether the left side (0) is indeed in the right side (range(0,10))
upvote count: 5
score: 5
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50673120
has body: I am trying to parse titles, and I can't quite figure out how to isolate the last numbers in the string, I think I got the delimiter figured out (with those nested if statements), but Im still failing my own test cases. Any advice? Current output: 1801 (150@$5): 1801 0055 30 @ $5: 0055 leaver - 8 @ $10: 8 ATS-55) - 45/$2: 55 End goal: 1801 (150@$5): 150 0055 30 @ $5: 30 leaver - 8 @ $10: 8 ATS-55) - 45/$2: 45 My code import re def getSlots(title): x=title.split('@') if len(x)&lt;2: #this means @ wasnt used as the delimeter x=title.split('/') if len(x)&lt;2: x=title.split(' ') if len(x)&lt;2: return "unsolvable"; m = re.search('\d+', x[0]) return m.group(0); testlist=['1801 (150@$5)','0055 30 @ $5','leaver - 8 @ $10','ATS-55) - 45/$2'] for t in testlist: print(t+': '+getSlots(t))
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/88356125
has answer: http://stackoverflow.com/a/50673237
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50678337
downvote count: 1
has title: Get last numbers in string separated by an unknown delimiter
type: Question
score: -1
accepted answer: http://stackoverflow.com/a/50673237
has comment: http://stackoverflow.com/comment/88355971
answer count: 3
upvote count: 0
possible better answer: http://stackoverflow.com/a/50673183
has answer: http://stackoverflow.com/a/50673183
favorite count: 0

http://stackoverflow.com/a/50560629
score: 1
has comment: http://stackoverflow.com/comment/88160963
has comment: http://stackoverflow.com/comment/88133850
upvote count: 1
type: AcceptedAnswer
has body: I believe need: df['Code_new'] = df['Code'].where(df['Code'].isin(['AA','BB'])).ffill() df'Numx','Numy' = df'Numx','Numy'.mask(df['Code_new'].duplicated()) mask = df['Code_new'] == 'BB' df.loc[mask, ['Numx','Numy']] = df.loc[mask, ['Numx','Numy']].ffill() print (df) Code Numx Numy Code_new 0 AA 30.2 1.9 AA 1 NaN NaN AA 2 NaN NaN AA 3 BB 35.6 2.2 BB 4 35.6 2.2 BB 5 35.6 2.2 BB 6 35.6 2.2 BB 7 CC 35.6 2.2 BB 8 35.6 2.2 BB 9 DD 35.6 2.2 BB Or: df = df.replace('nan', np.nan) df['Code_new'] = df['Code'].where(df['Code'].isin(['AA','BB'])).ffill() m1 = df['Code_new'].duplicated() &amp; (df['Code_new'] == 'AA') df'Numx','Numy' = df'Numx','Numy'.mask(m1) m2 = df['Code_new'] == 'BB' df.loc[m2, ['Numx','Numy']] = df.loc[m2, ['Numx','Numy']].ffill() print (df) Code Numx Numy Code_new 0 AA 30.2 1.9 AA 1 NaN NaN AA 2 NaN NaN AA 3 BB 35.6 2.2 BB 4 40.2 2.5 BB 5 45.5 3.1 BB 6 45.5 3.1 BB 7 CC 45.5 3.1 BB 8 45.5 3.1 BB 9 DD 42.2 5.4 BB
has comment: http://stackoverflow.com/comment/88133884
has comment: http://stackoverflow.com/comment/88164554
type: Answer
accepted answer of: http://stackoverflow.com/q/50560399
has comment: http://stackoverflow.com/comment/88162817
answers question: http://stackoverflow.com/q/50560399
has comment: http://stackoverflow.com/comment/88164260
downvote count: 0

http://stackoverflow.com/q/50688353
has body: I'm having trouble understanding how to write this datatype to a csv file. I'm using requests in Python 2.7 and this is coming back as &lt;type 'unicode'&gt;. This is just a snippet of the data: "sizeOfApplication":0,"totalFailedFolders":0,"totalFailedFiles":0,"isVisible":true,"localizedStatus":"Running","isAged":false,"totalNumOfFiles":0,"jobId":955329,"sizeOfMediaOnDisk":0,"status":"Running","lastUpdateTime":1528140228,"percentSavings":0,"localizedOperationName":"Auxiliary Copy","statusColor":"greenspan","backupLevel":0,"jobElapsedTime":1732834,"jobStartTime":1526389208,"currentPhaseName":"Auxi"sizeOfApplication":179325630,"backupSetName":"Databases","totalFailedFolders":0,"totalFailedFiles":0,"isVisible":true,"localizedStatus":"Running","isAged":false,"totalNumOfFiles":54,"jobId":971203,"sizeOfMediaOnDisk":27870043,"status":"Running","lastUpdateTime":1527914335,"percentSavings":84.4584,"localizedOperationName":"Backup","statusColor":"greenspan","backupLevel":1,"jobElapsedTime":241877,"jobStartTime":1527897616,"currentPhaseName":"Backup","jobType":"Backup","backupLevelName":"Full" When I try to set this as a literal_eval, I get a Value Error: malformed string and when I looked that up, I'm thinking its because there's decimal data in the output and that ast doesn't support decimal. cvData = ast.literal_eval(str(r.text)) I've tried the following does not work either: with open('mycsvfile.csv', 'wb') as f: w = csv.DictWriter(f, r.text.keys()) w.writeheader() w = csv.DictWriter(writerow(r.text)) Clearly, this is an issue between the chair and the keyboard and I apologize in advance because my python skills are quite lacking. Is there a way to either get this to output correctly or to remove/convert the decimals (assuming that's the issue)?
type: Question
has comment: http://stackoverflow.com/comment/88386536
has comment: http://stackoverflow.com/comment/88386688
has comment: http://stackoverflow.com/comment/88386531
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/88386577
has comment: http://stackoverflow.com/comment/88386628
has title: Issues writing unicode data to csv
tagged with: unicode
has comment: http://stackoverflow.com/comment/88386798
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/88386630
answer count: 0

http://stackoverflow.com/a/50685919
accepted answer of: http://stackoverflow.com/q/50657352
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You have to set a new QTextCharFormat to the QTextCursor of the QTextEdit: import sys from PyQt4 import QtGui, QtCore class Window(QtGui.QMainWindow): def __init__(self): super(Window,self).__init__() self.textEdit = QtGui.QTextEdit() self.setCentralWidget(self.textEdit) self.textEdit.setReadOnly(True) toolbar = QtGui.QToolBar() self.addToolBar(QtCore.Qt.RightToolBarArea, toolbar) action = toolbar.addAction("Press Me") action.triggered.connect(self.change_color) self.textEdit.append("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ut metus diam. Donec vulputate porta libero, et hendrerit sapien sollicitudin ut. Aenean molestie sapien sit amet turpis tristique laoreet quis sed lectus. Ut sed ante arcu. Mauris vel finibus augue. Cras non malesuada dolor. Duis vel molestie ante. Pellentesque quis justo neque. Curabitur blandit auctor viverra. Vestibulum eu feugiat eros. Pellentesque at nisl ex. Morbi ornare tellus magna. Donec vel urna ac mi bibendum gravida. Integer quis interdum mauris. Aenean a metus eu felis volutpat fermentum in vitae massa.") def change_color(self): cursor = self.textEdit.textCursor() if cursor.hasSelection(): fmt = QtGui.QTextCharFormat() fmt.setBackground(QtCore.Qt.green) cursor.setCharFormat(fmt) if __name__=='__main__': import sys app = QtGui.QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec())
has comment: http://stackoverflow.com/comment/88409014
answers question: http://stackoverflow.com/q/50657352
upvote count: 1
score: 1

http://stackoverflow.com/q/50627827
has answer: http://stackoverflow.com/a/51342126
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51342126
tagged with: python
type: AnsweredQuestion
has title: inaccurate plotly cufflinks plot
tagged with: plotly
score: 1
upvote count: 1
has body: I am trying to create plots using cufflinks but they seems to be inaccurate, or to better put it, the y axis doesnt seem to be in order. the data i am using : time pos_slot crane_gkey C1 319 85 days 09:29:11 320 91 days 00:55:00 329 100 days 21:15:00 330 47 days 02:00:00 331 0 days 11:25:00 333 9 days 13:35:00 334 3 days 01:15:00 335 0 days 00:10:00 336 0 days 05:00:00 337 0 days 05:00:00 338 2 days 21:10:00 339 0 days 12:15:00 345 9 days 22:50:00 353 1 days 12:17:28 362 1 days 08:05:00 363 0 days 15:50:00 369 1 days 08:05:00 406 9 days 20:10:00 407 12 days 22:05:00 408 7 days 14:15:00 this goes on for multiple values of pos_slot This is a groupme that i created out of a bigger table. i use the following to create a plot df1_bct_pos_ctimes3 = df1_bct_pos_ctimes.unstack(level = -2) df1_bct_pos_ctimes3.iplot(kind = 'scatter') and i get the following plot And as u can see from the data, the plor does not look accurate at all and the y axis seems to be messed up now if i run the cufflinks on the table without unstacking it and look at C1 for pos_slot i get: code : df1_bct_pos_ctimes.iplot(kind = 'scatter') and this seems to accurately depict the values in the table. Also as a side question, how do i customize the axis labels to be more easily understandable? Thank you. EDIT : seems like changing time to total seconds fixed the issue. i would still like to know why this issue happened. Thank you.
tagged with: plot
type: Question

http://stackoverflow.com/comment/88136001
type: Comment
comment on: http://stackoverflow.com/a/50562800
score: 0
type: AnswerComment
has text: It wasn't clear if you wanted to keep this values in the same row of the new dataframe or in different rows, I presumed the latter

http://stackoverflow.com/a/50599205
downvote count: 0
has body: You have two questions. One at a time. Your first question is answered with groupby, shift, and cumsum: df.groupby('id').Col_1.apply(lambda x: x.shift().cumsum()) 0 NaN 1 0.0 2 1.0 3 2.0 4 2.0 5 NaN 6 0.0 Name: Col_1, dtype: float64 Or, if you prefer cleaner output, df.groupby('id').Col_1.apply(lambda x: x.shift().cumsum()).fillna(0).astype(int) 0 0 1 0 2 1 3 2 4 2 5 0 6 0 Name: Col_1, dtype: int64 Your second, also similar, using groupby, shift, cummax and ffill: df.Col_2.where(df.Col_1.eq(1)).groupby(df.id).apply( lambda x: x.shift().cummax().ffill() ) 0 NaN 1 NaN 2 24.0 3 32.0 4 32.0 5 NaN 6 NaN Name: Col_2, dtype: float64 In both cases, the essential ingredient is a groupby followed by a subsequent shift call. Note that these answers are difficult to solve sans apply because there are multiple operations to be carried out on sub-groups. Consider taking the lambda out by defining a custom function. You'll save a few cycles on larger data.
score: 4
answers question: http://stackoverflow.com/q/50598984
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50598984
type: Answer
upvote count: 4

http://stackoverflow.com/a/50700051
has body: I suggest using PDAL and developing a pipeline to implement your workflow. You can easily install PDAL via Conda. With PDAL you can crop to retain points within a 2D or 3D radius of a specified point (using distance and point options respectively). PDAL also has ground filters like SMRF and PMF. I imagine the basic pipeline you are going for is something like this, though you may need to adapt it to your data or set some advanced options. { "pipeline":[ { "type":"filters.crop", "point":"POINT (0 0)", "distance":20.0 }, { "type":"filters.smrf" } ] } Once you've installed PDAL and figured out what your processing pipeline needs to look like, you can execute it within Python too, the end result being a Numpy array. UPDATE The suggested usage of the SMRF filter classifies points, but does not extract them. You'll either need to use a PDAL or Python to extract ground returns by checking pointwise Classification values, where a value of 2 indicates a ground return. UPDATE The previously stated example, shown in Python, as discussed in the comments. import pdal json = """{ "pipeline":[ "/path/to/input.laz", { "type":"filters.crop", "point":"POINT (0 0)", "distance":20.0 }, { "type":"filters.smrf" }, "/path/to/output.laz" ] }""" pipeline = pdal.Pipeline(json) pipeline.validate() pipeline.execute()
has comment: http://stackoverflow.com/comment/88748293
has comment: http://stackoverflow.com/comment/88659220
downvote count: 0
has comment: http://stackoverflow.com/comment/89746918
upvote count: 2
has comment: http://stackoverflow.com/comment/88641293
type: Answer
has comment: http://stackoverflow.com/comment/88802898
score: 2
has comment: http://stackoverflow.com/comment/88529717
has comment: http://stackoverflow.com/comment/88479773
has comment: http://stackoverflow.com/comment/89755010
has comment: http://stackoverflow.com/comment/88701528
has comment: http://stackoverflow.com/comment/89060742
has comment: http://stackoverflow.com/comment/88701174
has comment: http://stackoverflow.com/comment/89059802
has comment: http://stackoverflow.com/comment/88966146
answers question: http://stackoverflow.com/q/50690970
has comment: http://stackoverflow.com/comment/88588424

http://stackoverflow.com/a/50590129
score: 7
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88189836
type: Answer
has body: That happens because pygame.Rects can only have integers as their coordinates, and if you add or subtract a floating point number the result gets truncated afterwards. For example if the rect.x is 10 and you add 1.5 to rect.x the new value is 11.5 which is then converted to 11. If you subtract 1.5 from 10 you get 8.5 and after truncating it 8. So in the first case you move 1 px to the right and in the second you move 2 px to the left. The solution is to store the actual position as a separate variable or attribute, add the speed to it and then assign this value to the rect. pos_x += speed rect.x = pos_x I usually use vectors to store the position and the velocity. import pygame as pg from pygame.math import Vector2 class Player(pg.sprite.Sprite): def __init__(self, pos, *groups): super().__init__(*groups) self.image = pg.Surface((30, 50)) self.image.fill(pg.Color('dodgerblue1')) self.rect = self.image.get_rect(center=pos) self.vel = Vector2(0, 0) self.pos = Vector2(pos) def update(self): self.pos += self.vel self.rect.center = self.pos
accepted answer of: http://stackoverflow.com/q/50589701
upvote count: 7
answers question: http://stackoverflow.com/q/50589701

http://stackoverflow.com/q/50651232
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/88316350
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/88314707
has title: JSONDecodeError Django
linked to: http://stackoverflow.com/q/14966989
answer count: 1
has answer: http://stackoverflow.com/a/50652196
tagged with: python
linked to: http://stackoverflow.com/q/18612248
favorite count: 0
type: UnansweredQuestion
tagged with: django
has body: I have an API that is sending me a POST request (JSON) for testing. I was doing a lot with the JSON, but all of a sudden it stopped working and giving me a JSONDecodeError. I tried all sorts of things, like using request.POST but nothing worked correctly like I said this was working at one point. Any assistance is appreciated. Test that gives the error: In the Windows Command prompt, running: curl -X POST http://127.0.0.1:8000/webhook/webhook_receiver/ -d '{"foo": "bar"}' Error: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) View: def webhook_receiver(request, *args, **kwargs): if request.method == 'POST': # Get the incoming JSON Data data = request.body.decode('utf-8') received_json_data = json.loads(data) return HttpResponse(received_json_data) else: return HttpResponse("not Post")

http://stackoverflow.com/a/50669224
answers question: http://stackoverflow.com/q/50668783
has body: gzip only supports compressing a single file or stream. In your case, the extracted stream is a tar object, so you'd use Python's tarfile library to manipulate the extracted contents. This library actually knows how to cope with .tar.gz so you don't need to explicitly extract the gzip yourself.
accepted answer of: http://stackoverflow.com/q/50668783
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/88348318
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/50568020
has comment: http://stackoverflow.com/comment/89691302
answers question: http://stackoverflow.com/q/50560582
has body: Session management isn't used in odoo. You can get some third party APPS
score: 0
type: Answer

http://stackoverflow.com/comment/88382343
has text: It's a little silly that XY questions like this one get marked as duplicates. Even before the edits, you could see that the problem of the OP was not how strings are compared.. Anyways, abernert's comments above are the (best IMHO) answer to the question.
comment on: http://stackoverflow.com/q/50686078
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/63932305
answers question: http://stackoverflow.com/q/50686388
type: Answer
has comment: http://stackoverflow.com/comment/113053382
has body: Open CMD and go to the folder of your discord bot eg: cd C:\Users\max\Desktop\DiscordBot Next type this in CMD: pip install discord.py That should work
score: 0

http://stackoverflow.com/comment/88178441
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50584450
has text: @Praveen - Added to answer also :) Thank you.
type: AnswerComment

http://stackoverflow.com/comment/88377708
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50674558
has text: @PrratekRamchandani fixed :)

ngrok
tag name: ngrok
tags question: http://stackoverflow.com/q/50588658
type: Tag

http://stackoverflow.com/q/50640962
has answer: http://stackoverflow.com/a/50641209
has comment: http://stackoverflow.com/comment/88316296
tagged with: angular5
type: UnansweredQuestion
has title: Kubernetes Connection Between two services?
has body: I have two services auth and frontend. How do I make a connection between the two? auth.yml apiVersion: apps/v1 kind: Deployment metadata: name: auth spec: replicas: 1 selector: matchLabels: app: auth template: metadata: labels: app: auth tier: backend track: dev spec: containers: - name: auth image: auth:1 ports: - name: auth containerPort: 8000 ---------------------------------------------- apiVersion: v1 kind: Service metadata: name: auth spec: selector: app: auth tier: backend ports: - protocol: TCP port: 3000 targetPort: auth type: LoadBalancer The above service works fine with the external IP and the port. fe.yml apiVersion: apps/v1 kind: Deployment metadata: name: fe spec: replicas: 1 selector: matchLabels: app: fe template: metadata: labels: app: fe tier: frontend track: dev spec: containers: - image: fe:1 name: nginx ports: - name: fe containerPort: 80 ------------------------------------------------ apiVersion: v1 kind: Service metadata: name: fe spec: selector: app: fe tier: frontend ports: - protocol: TCP port: 80 targetPort: 80 type: LoadBalancer I am able to access both the services individually with the external IP. I want both the services to interact with each other. I have tried using name-based calling service in the frontend like - http://auth:3000. It does not seem to work.
has comment: http://stackoverflow.com/comment/88292214
has comment: http://stackoverflow.com/comment/88291912
has comment: http://stackoverflow.com/comment/88292391
tagged with: docker
type: Question
score: 0
answer count: 1
tagged with: kubernetes
tagged with: python

http://stackoverflow.com/comment/115975978
comment on: http://stackoverflow.com/a/52237389
type: Comment
has text: BOOM! Well done sir give that man a cookie!
score: 3
type: AnswerComment

http://stackoverflow.com/q/50660820
has answer: http://stackoverflow.com/a/50660886
tagged with: datetime
tagged with: python
score: 2
type: AnsweredQuestion
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/50660960
downvote count: 0
tagged with: dataframe
has title: Transforming dates in chronological order using pandas dataframe
tagged with: pandas-groupby
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50660886
favorite count: 0
has body: I need help with comparing dates in different rows and in different columns and making sure that they follow a chronological order. First, I group data based on Id and group columns. Next, each date value is supposed to occur in the future. The first group [1111 + A ] contains an error because the dates don't follow a chronological order : 1/1/2016 &gt; 2/20/2016 &gt; **2/19/2016** &gt; 4/25/2016 &gt; **4/1/2016** &gt; 5/1/2016 Current result id start end group 0 1111 01/01/2016 02/20/2016 A 1 1111 02/19/2016 04/25/2016 A 2 1111 04/01/2016 05/01/2016 A 3 2345 05/01/2016 05/28/2016 B 4 2345 05/29/2016 06/28/2016 B 5 1234 08/01/2016 09/16/2016 F 6 9882 01/01/2016 08/29/2016 D 7 9992 03/01/2016 03/15/2016 C 8 9992 03/16/2016 08/03/2016 C 9 9992 05/16/2016 09/16/2016 C 10 9992 09/17/2016 10/16/2016 C 11 9992 10/17/2016 12/13/2016 C The answer should be: 1/1/2016 &gt; 2/20/2016 &gt; **2/21/2016** &gt; 4/25/2016 &gt; **4/26/2016** &gt; 5/1/2016 Desired output id start end group 0 1111 01/01/2016 02/20/2016 A 1 1111 02/21/2016 04/25/2016 A 2 1111 04/26/2018 05/01/2016 A 3 2345 05/01/2016 05/28/2016 B 4 2345 05/29/2016 06/28/2016 B 5 1234 08/01/2016 09/16/2016 F 6 9882 01/01/2016 08/29/2016 C 7 9992 03/01/2016 03/15/2016 C 8 9992 03/16/2016 08/03/2016 C 9 9992 08/04/2016 09/16/2016 C 10 9992 09/17/2016 10/16/2016 C 11 9992 10/17/2016 12/13/2016 C Any help will be greatly appreciated.
has answer: http://stackoverflow.com/a/50660960
upvote count: 2

http://stackoverflow.com/comment/88227233
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50606524
score: 0
has text: @PM2Ring Oops, missed that. Thanks!

http://stackoverflow.com/comment/118475860
score: 0
type: Comment
has text: I am still getting this on Spark 3.0.1, and it's independent of Correlation.corr. I just commented on that existing ticket with the traceback and a little more info. I'll post back if I come up with more info or another workaround.
type: AnswerComment
comment on: http://stackoverflow.com/a/56105513

http://stackoverflow.com/q/50615723
tagged with: python
possible better answer: http://stackoverflow.com/a/50628491
upvote count: 2
linked to: http://stackoverflow.com/q/7359828
score: 0
answer count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/50615903
has title: Creating function: (f, n) which return f(f(f( .... x... ))) n times
duplicate of: http://stackoverflow.com/q/7359828
tagged with: recursion
has body: I am having trouble creating a higher order function in python that applies a function f, n times to generate a new function h, as its return value. def compile(f, n) # h is a function, f applied n times ... return h new = compile(lambda x: 2*x, 3) new(4) == 32 # new(4) == 2(2(2(4)))
type: AnsweredQuestion
tagged with: function
accepted answer: http://stackoverflow.com/a/50615903
has comment: http://stackoverflow.com/comment/88241350
favorite count: 0
tagged with: function-composition
has comment: http://stackoverflow.com/comment/88241743
type: Question
has answer: http://stackoverflow.com/a/50628491

http://stackoverflow.com/comment/88307485
comment on: http://stackoverflow.com/q/50625363
type: Comment
type: QuestionComment
has text: It is not strange at all that running a program with `sudo` would solve your permission problems, that's kind of the whole point of `sudo` and the root user.
score: 2

http://stackoverflow.com/q/50599584
has comment: http://stackoverflow.com/comment/88208748
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88208821
has title: Python : get the next working time slot
type: Question
score: 0
has comment: http://stackoverflow.com/comment/88209758
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
tagged with: time
tagged with: datetime
tagged with: python
has body: Handling a staff planning (Python 2.7), I have for a given person a list of working days (and times) in isoWeek. With a given date I'm trying to determine when will be the next date the staff person will be available. working_days = { 1: { 'start': datetime.time(8, 0), 'end': datetime.time(17, 15) }, 2: { 'start': datetime.time(7, 45), 'end': datetime.time(17, 0) }, 3: { 'start': datetime.time(8, 0), 'end': datetime.time(16, 45) }, 4: { 'start': datetime.time(10, 0), 'end': datetime.time(15, 30) }, 5: { 'start': datetime.time(8, 30), 'end': datetime.time(17, 15) } } searched_date = datetime.datetime(2018, 6, 13, 20, 57, 00) // Wednesday searched_date_week_day = searched_date.isoweekday() expected result : datetime.datetime(2018, 6, 14, 10, 00, 00) // Thursday at 10 I would have liked to just use the weekdays to achieve this result but I have my doubts on it. What I wrote is tricked on the simplest example (my searched time is greater than the end working time of the staff) next_working_day = next((x for x in working_days if x &gt;= searched_date_week_day), None) gives: 3 , Wednesday Considering there will me more tricky cases (let's imagine my searched date is on a Sunday, isoweek 7, it doesn't work), is my only way out is to transform my working_days in some datetime.datetime list? Fiddle
has comment: http://stackoverflow.com/comment/88209077
has answer: http://stackoverflow.com/a/50600517
accepted answer: http://stackoverflow.com/a/50600517

http://stackoverflow.com/a/50667954
has comment: http://stackoverflow.com/comment/88349793
has comment: http://stackoverflow.com/comment/88349253
score: 1
has comment: http://stackoverflow.com/comment/88349629
has body: df['datum'].replace(df['datum'][0:2],' ') will replace the first two rows with whitespace, not the first two letters in each row. You want to work with df.datum.str Option 1 (If all your months are three letter abbreviations) string slicing df.datum.str[-8:] 0 jun 2018 1 jun 2018 2 maj 2018 Name: datum, dtype: object Option 2 str.replace with .*\s(\w+\s\w+)$ df.datum.str.replace(r'.*\s(\w+\s\w+)$', r'\1') 0 jun 2018 1 jun 2018 2 maj 2018 Name: datum, dtype: object
downvote count: 0
has comment: http://stackoverflow.com/comment/88345984
type: Answer
has comment: http://stackoverflow.com/comment/88345963
upvote count: 1
answers question: http://stackoverflow.com/q/50667928

http://stackoverflow.com/comment/88363665
score: 0
has text: Thank you, but this is not exactly what I want. At every row I'm looking at "1" and randomly select one, other 1 are made into 0. So in result dataframe for every row should be only one "1". I assume that at least one "1" exists in every row.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50676729

http://stackoverflow.com/comment/88385775
comment on: http://stackoverflow.com/q/50687892
score: 0
has text: I have a full sentence. I should divide it into words, then divide the words into letters and only THEN I should loop over the letters.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88395638
has text: I'm under the impression that everything that happens after the error line is irrelevant for a question here, because it isn't even executed, @tdelaney. Of course, for the real program they may be relevant but the reason to *demand* a MCVE is to put focus on the problem at hand.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50692572

http://stackoverflow.com/comment/88227342
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50608703
has text: @coldspeed I have plenty of vote, you will have my support man :-)
score: 1

http://stackoverflow.com/q/50559933
upvote count: 1
tagged with: python
score: 1
type: Question
has title: python runserver performing system checks stays indefinitely
has body: I am using Python2.7.12 and when i try to open web server with run server command, I stacked at performing system checks command. What can be the problem? How can I pass this and open the web server? run server performing system checks stays indefinitely
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88130610
answer count: 0
has comment: http://stackoverflow.com/comment/88133235
type: UnansweredQuestion

http://stackoverflow.com/a/50655248
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/136444541
type: Answer
score: 6
upvote count: 6
has body: Now I don't see the point why you would want this. However, as I could think of a workaround I might as well post it. import pandas as pd cols = pd.read_excel('text.xlsx', header=None,nrows=1).values[0] # read first row df = pd.read_excel('text.xlsx', header=None, skiprows=1) # skip 1 row df.columns = cols print(df) Returns: col1 col1 0 1 1 1 2 2 2 3 3
accepted answer of: http://stackoverflow.com/q/50653962
has comment: http://stackoverflow.com/comment/123709422
has comment: http://stackoverflow.com/comment/131049566
answers question: http://stackoverflow.com/q/50653962

http://stackoverflow.com/comment/88315944
has text: See if [this](https://stackoverflow.com/questions/39838367/pandas-groupby-return-average-but-exclude-nan) is of any help.
comment on: http://stackoverflow.com/q/50652569
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88136089
comment on: http://stackoverflow.com/a/50562710
has text: @JahnabKumarDeka - you get `datetime`s, but if need only dates use `df['date'] = pd.to_datetime(df['date'].astype(str), errors='coerce').dt.date`
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/60515993
downvote count: 1
score: 191
has comment: http://stackoverflow.com/comment/116230716
has comment: http://stackoverflow.com/comment/112160798
upvote count: 192
has body: I found that my dfs both had the same type column (str) but switching from join to merge solved the issue.
type: Answer
has comment: http://stackoverflow.com/comment/120908430
has comment: http://stackoverflow.com/comment/111299998
answers question: http://stackoverflow.com/q/50649853
has comment: http://stackoverflow.com/comment/110082835

http://stackoverflow.com/q/50606448
has comment: http://stackoverflow.com/comment/88284730
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: machine-learning
downvote count: 1
tagged with: random-forest
type: Question
score: 0
has title: predict in a loop using random forest with sklearn and pickle
has comment: http://stackoverflow.com/comment/88260267
tagged with: runtime
has comment: http://stackoverflow.com/comment/88261698
favorite count: 0
has comment: http://stackoverflow.com/comment/88258010
has comment: http://stackoverflow.com/comment/88284411
has comment: http://stackoverflow.com/comment/88287939
tagged with: pickle
tagged with: python
has body: I'm using sci-kit learn on Python3.6 and I have some runtime problems for predicting in a loop with a random forest loaded from Pickle. When I'm predicting from a random forest with 1 estimator (tree) the runtime is about 0.002 sec per sample. However, when I increase the number of estimators (>1) the runtime grows to 0.1 seconds per sample whatever the number of trees. here is my code for saving the model : clf = RandomForestClassifier(n_estimators=1, #or &gt; 1 n_jobs=-1, random_state=2, max_depth=15, min_samples_leaf=1, verbose=0, max_features='auto' ) clf.fit(X_train, y_train) with open('classifier.pkl', 'wb') as fid: cPickle.dump(clf, fid) and here is my code for loading the model and predict in a loop: with open('classifier.pkl', 'rb') as fid: clf = cPickle.load(fid) for s in samples: #my feature extraction method pred = clf.predict(feature) #feature is a 1D np array containing features computed for the sample s I don't understand why the runtime isn't proportional to the number of trees and why it increases so fast. Is it a bug or am I using pickle in the wrong way? Please, can you help me? CB

http://stackoverflow.com/a/50543070
has comment: http://stackoverflow.com/comment/88097297
score: 1
upvote count: 1
has body: &gt;&gt;&gt; s = "A&gt;B&gt;C" &gt;&gt;&gt; lst = s.split("&gt;") &gt;&gt;&gt; result = zip(range(1, len(lst)+1), lst) &gt;&gt;&gt; print result [(1, 'A'), (2, 'B'), (3, 'C')]
has comment: http://stackoverflow.com/comment/88097320
answers question: http://stackoverflow.com/q/50543045
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88097404

http://stackoverflow.com/q/50572875
has comment: http://stackoverflow.com/comment/88155640
has comment: http://stackoverflow.com/comment/88155427
has comment: http://stackoverflow.com/comment/88155936
has answer: http://stackoverflow.com/a/50609520
accepted answer: http://stackoverflow.com/a/50609520
type: Question
tagged with: python-multiprocessing
has comment: http://stackoverflow.com/comment/88155442
has comment: http://stackoverflow.com/comment/88155661
has comment: http://stackoverflow.com/comment/88155616
upvote count: 2
answer count: 1
downvote count: 0
has title: python pool.map_async doesn't wait for .wait()
favorite count: 0
tagged with: python-3.x
has body: I'm trying to run a fat function which worked pretty well with pool.apply_async Now, I'm trying out the pool.map_async function (with 2 arguments passed with the functools.partial method) and the program finishes immediately without any error or exceptions... files = list_files(mypath) # list of files to process csv_rows = None result = mp.Queue() #result queue from multiprocessing module pool = mp.Pool(4) t = pool.map_async( partial(process_file, result), files) t.wait() # it doesn't wait HERE ... program exits immediately - no errors Any clues on what I might be missing?
tagged with: python
type: AnsweredQuestion
score: 2

http://stackoverflow.com/a/50698336
answers question: http://stackoverflow.com/q/50690452
score: 0
type: AcceptedAnswer
type: Answer
has body: Python list does not support indexing via a list of indexers. There are a couple of solutions to overcome this. Where you know keys exist You can use itemgetter and sequence unpacking: from operator import itemgetter A = {1: -3, 2: -5, 3: 4, 5: 12, -34: 23, 64: 32} res = min(itemgetter(*[2, 3, 5])(A)) # -5 Where keys may not exist You can use a range object to specify a range of keys. A list or set would work too. Here we feed a generator expression to min: res = min(v for k, v in A.items() if k in range(2, 6)) # -5
accepted answer of: http://stackoverflow.com/q/50690452

http://stackoverflow.com/q/50685524
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50686072
accepted answer: http://stackoverflow.com/a/50686072
score: -1
type: Question
tagged with: removing-whitespace
has comment: http://stackoverflow.com/comment/88381496
upvote count: 0
tagged with: string
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88381555
has title: Putting integers in tabular form without whitespace in Python
tagged with: python
has body: Sorry that I ask this here, because this seems really elementary and is most likely asked before. However, I have been searching and trying for hours and I couldn't find anything that helped me out. I want to write a program that asks for an upper bound and returns a table with pairs of numbers (m,n) such that the sum of of divisors of n (excluding n) equals m, and vice versa. Now I wrote the following bound = int(input('upper bound = ')) l = len(str(bound)) for x in range(1,l): print(' ', end='') print('m', end=' ') for y in range(1,l): print(' ', end='') print('n', end='') for i in range(1,bound): for j in range (1, bound): if j == i: break som_i = 0 som_j = 0 for k in range(1,i): if i % k == 0: som_i += k for l in range(1,j): if j % l == 0: som_j += l if som_i == j and som_j == i: print('{:{prec}d}'.format(j, prec = l).rstrip(''), end="") print('{:{prec}d}'.format(i, prec = l+2).lstrip(''), end="") The problem is that I want the pair to be displayed in tabular form side to side and with the right indentation, depending on the length of the number. Whatever I tried (I read so many treads with similar questions already) Python keeps adding a whitespace. Can anyone help me out on this? I am really new to Python and I cannot figure this out myself. If relevant, I am using version 3.6. EDIT: For example, when I run the program I get: upper bound = 300 m n 220 284 while I would like to get upper bound = 300 m n 220 284 And similar for larger inputs. EDIT2 My question is not a duplicate, since i already tried adding end="" which did not work.
downvote count: 1
linked to: http://stackoverflow.com/q/12102749
has comment: http://stackoverflow.com/comment/88381150

http://stackoverflow.com/comment/88205641
type: QuestionComment
has text: iterate the file two lines at a time. One approach could be a function that yields two lines at a time. It is then simple to check for the None value and discard some lines. To iterate two lines at a time look at the functions `iter`, `next` and the `StopIteration` exception.
comment on: http://stackoverflow.com/q/50597860
score: 0
type: Comment

http://stackoverflow.com/q/50584778
downvote count: 0
score: 1
favorite count: 0
tagged with: exception
tagged with: python
has title: Python tornado tornado.iostream.StreamClosedError
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50600748
has body: I have a python tornado websocket handler which works just fine. However, sporadically when tab is closed with websocket connection it throws exceptions which I can not catch. That occurs only with Firefox so I suspect that maybe it is some internal bug. Exception does not break execution of code but I still want to be able to catch all exceptions. Exceptions: ERROR:asyncio:Future exception was never retrieved future: Traceback (most recent call last): File "C:\Users\user\Anaconda3\lib\site-packages\tornado\websocket.py", line 808, in wrapper yield fut File "C:\Users\user\Anaconda3\lib\site-packages\tornado\gen.py", line 1099, in run value = future.result() tornado.iostream.StreamClosedError: Stream is closed During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\user\Anaconda3\lib\site-packages\tornado\gen.py", line 1107, in run yielded = self.gen.throw(*exc_info) File "C:\Users\user\Anaconda3\lib\site-packages\tornado\websocket.py", line 810, in wrapper raise WebSocketClosedError() tornado.websocket.WebSocketClosedError An here is the code for the on_message function: async def on_message(self, message): print(message) while True: try: #print('ws_connections: ', self.ws_connection, self.ws_connection.stream.socket) _fut = self.write_message(self.users[self].request_data()) except tornado.iostream.StreamClosedError as e: print('StreamClosedError:', e) break except tornado.websocket.WebSocketClosedError as e: print('WebSocketClosedError:', e) break except KeyError as e: print('KeyError:', e) break await gen.sleep(1)
upvote count: 1
type: Question
linked to: http://stackoverflow.com/q/37001733
tagged with: tornado
accepted answer: http://stackoverflow.com/a/50600748
answer count: 1

http://stackoverflow.com/q/50695819
accepted answer: http://stackoverflow.com/a/50696135
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50695968
has comment: http://stackoverflow.com/comment/88400938
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/88400906
has answer: http://stackoverflow.com/a/50696064
downvote count: 1
has body: Goal : i want only alphabets to be printed in a string #Input #====== string = ' 529Wind3@. ' #Neededoutput #============ 'Wind' I tried coding for this using the below code import re string=re.sub('[^a-z]+[^A-Z]',' ',string) print(string) The output i'm getting is ind But this code only applies for lowercase Can you please tell me how to write code for both upper and lowercase
favorite count: 0
has answer: http://stackoverflow.com/a/50695931
possible better answer: http://stackoverflow.com/a/50696064
has comment: http://stackoverflow.com/comment/88401758
has comment: http://stackoverflow.com/comment/88400867
answer count: 5
has comment: http://stackoverflow.com/comment/88400988
tagged with: python
tagged with: python-3.x
has title: Print only alphabetics in a string using Regular Expression
has answer: http://stackoverflow.com/a/50695991
has answer: http://stackoverflow.com/a/50696135

http://stackoverflow.com/q/50570455
downvote count: 1
has body: i'm trying to send keys in a textarea but it give me the error AttributeError: 'NoneType' object has no attribute 'send_keys' my code is barra_commenti= driver.find_element_by_xpath("//*[@id='react-root']/section/main/section/div[1]/div[1]/div/article[1]/div[2]/section[3]/form").click() time.sleep(2) barra_commenti.send_keys("ciao") The textarea is this it's the instagram comment bar, i don't understand why it dosn't go I tried too with selenium chrome extension for see if it doesn't goo on it too but it works so it's only in the program that gives the error
score: -1
type: Question
upvote count: 0
answer count: 1
has title: Selenium Textarea error
favorite count: 0
tagged with: python
tagged with: bots
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50570640
tagged with: selenium

heap-memory
tag name: heap-memory
tags question: http://stackoverflow.com/q/50607748
type: Tag

http://stackoverflow.com/q/50646412
answer count: 1
has comment: http://stackoverflow.com/comment/88332226
downvote count: 0
has comment: http://stackoverflow.com/comment/88314853
has comment: http://stackoverflow.com/comment/88304776
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/88303527
has comment: http://stackoverflow.com/comment/88335887
tagged with: python
tagged with: defunct
has comment: http://stackoverflow.com/comment/88331221
favorite count: 0
has comment: http://stackoverflow.com/comment/88380463
tagged with: subprocess
has comment: http://stackoverflow.com/comment/88314576
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88390755
has title: subprocess becomes defunct, `communicate()` hangs
has answer: http://stackoverflow.com/a/50690498
score: 3
has body: In python 2.7 on Ubuntu 14.04, I launch a process like this: bag_process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) for i in range(5): print "Countdown: {}".format(5 - i - 1) time.sleep(1) print "Sending SIGINT to PID {}".format(bag_process.pid) bag_process.send_signal(signal.SIGINT) (bag_out, bag_err) = bag_process.communicate() The program hangs on the communicate() line. When I open another terminal, I run ps -ef | grep ### to find the pid of the subprocess, and I see it's &lt;defunct&gt;. Why is the child program becoming defunct, and the parent program hanging on communicate()? Provided that the child truly exits after receiving SIGINT, how can I make the parent program reliably handle that without hanging?
upvote count: 3
has comment: http://stackoverflow.com/comment/88314599
type: Question

http://stackoverflow.com/a/50666399
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50666277
has body: y[:] makes a copy of y, for example: &gt;&gt;&gt; id(y) 140532682743688 &gt;&gt;&gt; id(y[:]) 140532673103944 so the net effect of g(y[:]).extend(g(y)) is to rotate the list once for the copy and once on the original list. The return value of g() when performed on the copy is not bound to a variable so the result is lost, and the net effect is that only 1 rotation is performed on the original list.
has comment: http://stackoverflow.com/comment/88342658
has comment: http://stackoverflow.com/comment/88342815
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88342730

ubuntu-16.04
tags question: http://stackoverflow.com/q/50602112
tag name: ubuntu-16.04
tags question: http://stackoverflow.com/q/50685218
type: Tag
tags question: http://stackoverflow.com/q/50576702
tags question: http://stackoverflow.com/q/50625363

http://stackoverflow.com/a/50677028
answers question: http://stackoverflow.com/q/50676937
accepted answer of: http://stackoverflow.com/q/50676937
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: Getting in href itself is easy with BeautifulSoup once you've got the link itself: href = name['href'] Then you can use regex with the re module: import re match = re.search(r'document.frmMain.PhysicianID.value=\d*;', href).group() value = re.search(r'\d+', match).group() print(value) #prints 1234567 Putting it all together with your code: import re for i in soup.select('.data'): name = i.find('a', attrs = {'title': 'For more information, click here.'}) match = re.search(r'document.frmMain.PhysicianID.value=\d*;', href).group() value = re.search(r'\d+', match).group() print(value) #prints 1234567
type: AcceptedAnswer

http://stackoverflow.com/q/50541926
has body: args = parser.parse_args() find = args.data_variable cmd = commands.getoutput("cat /cc/ddd '"+find+"' |grep -A 3 node | tail -n +2") r = tuple(cldb.split('\n')) print r i get the out put in tuples but it has /t please help how to remove it.
tagged with: python-2.7
has answer: http://stackoverflow.com/a/50542032
score: -1
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python
has title: greping with os command assigning it in tupe want to remove /t
has comment: http://stackoverflow.com/comment/88095094
answer count: 1
downvote count: 1
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88095030

http://stackoverflow.com/q/50604718
has answer: http://stackoverflow.com/a/50605420
has body: from flask import Flask app = Flask(__name__) @app.route("/") def function(): return "Hello Work" print('here') if __name__ == "__main__": app.run(debug=True) The print works, but the server does not start.
accepted answer: http://stackoverflow.com/a/51181703
tagged with: python
answer count: 4
type: AnsweredQuestion
score: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50618401
downvote count: 1
has title: UnsupportedOperation: not writable
type: Question
has answer: http://stackoverflow.com/a/53236407
tagged with: flask
has answer: http://stackoverflow.com/a/51181703
possible better answer: http://stackoverflow.com/a/50605420
favorite count: 0

http://stackoverflow.com/q/50684086
has comment: http://stackoverflow.com/comment/88377912
accepted answer: http://stackoverflow.com/a/50684183
tagged with: python
type: AnsweredQuestion
has title: Count purchases after occurrence of event in python dataframe
type: Question
has body: In the below dataframe I want to count the number of purchases after a promo has been done for each product. So for banana, the promo is done on 1-5-2018 and I want to receive the total number of purchases after it (8 times). How do I best do that efficiently in python? Date product Purchase Promo 0 01-01-2018 banana 1 0 1 01-02-2018 apple 2 0 2 01-03-2018 apple 3 0 3 01-04-2018 banana 4 0 4 01-05-2018 banana 1 1 5 01-06-2018 banana 3 0 6 01-07-2018 apple 1 0 7 01-08-2018 banana 4 0 8 01-09-2018 banana 1 0
tagged with: dataframe
has answer: http://stackoverflow.com/a/50684183
has comment: http://stackoverflow.com/comment/88377870
score: 0
tagged with: pandas-groupby
tagged with: pandas
answer count: 1

http://stackoverflow.com/q/50553820
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/58393520
tagged with: django
has body: I am new in Django and having a hard time figuring out how to print what an object have inside. I mean type and value of the variable with its members inside. Just like Laravel's dd(object) function. Laravel's dd() is a handy tool for debugging the application. I have searched for it. But found nothing useful. I have tried pprint(), simplejson, print(type(object) and {% debug %}. But none of them could provide the required information about an object. Here is a sample output from Laravel's dd() function. In this Image, I am printing the request object of Laravel. as you can see its showing complete information about an object. I mean name of class it belongs to, its member variables. also with its class name and value. and it keeps digging deep inside the object and prints all the information. But I am not able to find a similar tool in Django. That's hard to believe that Django doesn't have such a useful tool. Therefore I would like to know about any third party package that can do the trick. I am using Django version 2.0.5. and trying to print django.contrib.messages Also, I want the output to be displayed in the browser, not in the console. In a well readable way that's why I am asking for a Django package that can take in the object and render a well-formed presentation of object architecture.
tagged with: python
has answer: http://stackoverflow.com/a/66417645
has title: Laravel's dd() equivalent in django
has comment: http://stackoverflow.com/comment/88118776
has comment: http://stackoverflow.com/comment/88118693
type: Question
linked to: http://stackoverflow.com/q/2675028
has answer: http://stackoverflow.com/a/50553986
answer count: 6
has answer: http://stackoverflow.com/a/78244002
score: 20
linked to: http://stackoverflow.com/q/192109
upvote count: 21
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/61134618
has answer: http://stackoverflow.com/a/74592691

http://stackoverflow.com/a/70512116
downvote count: 0
has body: If you're using pytest with a test that inherits unittest.TestCase, there's a simple way of repeating it by using the parameterized Python library: from unittest import TestCase from parameterized import parameterized class RepeatTests(TestCase): @parameterized.expand([[]] * 5) def test_repeat_this_test_with_parameterized(self): print("Hello!") self.assertTrue(True) Output: Hello! Hello! Hello! Hello! Hello!
upvote count: 2
has comment: http://stackoverflow.com/comment/124643872
answers question: http://stackoverflow.com/q/50691692
type: Answer
score: 2

http://stackoverflow.com/comment/88234562
type: Comment
type: QuestionComment
has text: @AdamSmith - Fair enough. I only suggested a `tuple` or `class` because in the question he wants to keep the integers as integers, a `tuple` or `class` will allow that. The way it's set up now, if you forget and place quotes around the integer, nothing will warn until you use that integer for calculations, at least with a class you can have error checking when you create an object.
comment on: http://stackoverflow.com/q/50612208
score: 0

http://stackoverflow.com/q/50544197
type: AnsweredQuestion
type: Question
tagged with: keras
has answer: http://stackoverflow.com/a/50544276
score: 0
has title: Expected activation_1 to have 3 dimensions, but got array with shape (12 6984, 67)
accepted answer: http://stackoverflow.com/a/50544276
answer count: 1
has body: Writing a model to try using LSTM to generate realistic text based on examples. Here's the gist of the code # ... path = 'lyrics.txt' with io.open(path, encoding='utf-8') as f: text = f.read().lower() print('corpus length:', len(text)) chars = sorted(list(set(text))) print('total chars:', len(chars)) char_indices = dict((c, i) for i, c in enumerate(chars)) indices_char = dict((i, c) for i, c in enumerate(chars)) # cut the text in semi-redundant sequences of maxlen characters maxlen = 140 step = 3 sentences = [] next_chars = [] for i in range(0, len(text) - maxlen, step): sentences.append(text[i: i + maxlen]) next_chars.append(text[i + maxlen]) print('nb sequences:', len(sentences)) print('Vectorization...') x = np.zeros((len(sentences), maxlen, len(chars)), dtype=np.bool) y = np.zeros((len(sentences), len(chars)), dtype=np.bool) for i, sentence in enumerate(sentences): for t, char in enumerate(sentence): x[i, t, char_indices[char]] = 1 y[i, char_indices[next_chars[i]]] = 1 # build the model: a single LSTM print('Build model...') model = Sequential() model.add(LSTM(128, dropout_W=0.5, return_sequences=True, input_shape=(maxlen, len(chars)))) model.add(LSTM(128, dropout_W=0.5, return_sequences=True)) model.add(LSTM(128, dropout_W=0.5, return_sequences=True)) model.add(Dense(len(chars))) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam') edited it to try and see the result with stacking multiple LSTM, in return getting this error Using TensorFlow backend. corpus length: 381090 total chars: 67 nb sequences: 126984 Vectorization... Build model... char_lstm.py:55: UserWarning: Update your `LSTM` call to the Keras 2 API: `LSTM(128, return_sequences=True, drop out=0.5, input_shape=(140, 67))` model.add(LSTM(128, dropout_W=0.5, return_sequences=True, input_shape=(maxlen, len(chars)))) char_lstm.py:56: UserWarning: Update your `LSTM` call to the Keras 2 API: `LSTM(128, return_sequences=True, drop out=0.5)` model.add(LSTM(128, dro…
tagged with: python

http://stackoverflow.com/comment/88152022
has text: @JeruLuke I'm also working now some tests based on your code - the start you gave me is great.
comment on: http://stackoverflow.com/a/50551682
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/comment/88234237
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50612085
has text: Could you add the actual code, and not just the results?
score: 1

http://stackoverflow.com/q/50657449
tagged with: deep-learning
answer count: 1
downvote count: 0
tagged with: python
favorite count: 0
score: 4
has body: I have an input image, as numpy array of shape [H, W, C] where H - height, W - width and C - channels. I want to convert it into [B, C, H, W] where B - batch size, which should be equal to 1 every time, and changing the place for C. _image = np.array(_image) h, w, c = _image.shape image = torch.from_numpy(_image).unsqueeze_(0).view(1, c, h, w) So, will this preserve the image properly i.e without displacing the original image pixel values?
has answer: http://stackoverflow.com/a/50657805
has title: Convert image to proper dimension PyTorch
tagged with: pytorch
type: AnsweredQuestion
tagged with: image-processing
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/50657805
tagged with: numpy

http://stackoverflow.com/q/50570312
type: Question
tagged with: bash
answer count: 1
accepted answer: http://stackoverflow.com/a/50571280
score: 0
has comment: http://stackoverflow.com/comment/88153566
has comment: http://stackoverflow.com/comment/88150511
tagged with: python
has comment: http://stackoverflow.com/comment/88191407
tagged with: installation
has comment: http://stackoverflow.com/comment/88233339
tagged with: package
tagged with: pip
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50571280
has title: pip doesn't install anything and tells me to upgrade pip
has body: So whenever I try to install anything pip throws this error: DEVICE_NAME:~ MY_NAME$ sudo pip install pyautogui Password: The directory '/Users/daankoning/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/daankoning/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Collecting pyautogui Downloading https://files.pythonhosted.org/packages/2e/83/89b5adbc37d1bbf7b486a2c1c00e8037e6f801e8c053c4897bb82d9510c6/PyAutoGUI-0.9.36.tar.gz (46kB) 100% |████████████████████████████████| 51kB 1.3MB/s Collecting pymsgbox (from pyautogui) Downloading https://files.pythonhosted.org/packages/b6/65/86379ede1db26c40e7972d7a41c69cdf12cc6a0f143749aabf67ab8a41a1/PyMsgBox-1.0.6.zip Collecting PyTweening&gt;=1.0.1 (from pyautogui) Downloading https://files.pythonhosted.org/packages/b9/f8/c32a58d6e4dff8aa5c27e907194d69f3b57e525c2e4af96f39c6e9c854d2/PyTweening-1.0.3.zip Collecting Pillow (from pyautogui) Downloading https://files.pythonhosted.org/packages/df/aa/a25f211a4686f363d8ca5a1752c43a8f42459e70af13e20713d3e636f0af/Pillow-5.1.0-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (3.6MB) 100% |████████████████████████████████| 3.6MB 3.5MB/s Collecting pyscreeze (from pyautogui) Downloading https://files.pythonhosted.org/packages/9e/ec/e625b7c4f496977eafc441cd1f71becc8436a4ff0714263b885d269d866a/PyScreeze-0.1.14.tar.gz matplotlib 1.3.1 requires nose, which is not installed. matplotlib 1.3.1 requires tornado, which is not installed. matplotlib 1.3.1 has requirement numpy&gt;=1.5, but you'll have numpy 1.8.0rc1 which is incompatible. Installing collected packages: pymsg…

http://stackoverflow.com/a/50646093
type: Answer
upvote count: 1
has body: As you already found out the data is put into the page via JS. However, you can still get that data, because the entire data over the comapany is always loaded with the page. You can access this data via requests + BeautifulSoup + json (+ re): import json import re import requests from bs4 import BeautifulSoup webpage = "https://www.zippia.com/amazon-com-careers-487/" page = requests.get(webpage) soup = BeautifulSoup(page.content, 'lxml') for script in soup.find_all('script', {'type': 'text/javascript'}): if 'getCompanyInfo' in script.text: match = re.search("{[^\n]*}", script.text) data = json.loads(match.group()) print(data["companyDiversity"]["languages"]) json.dump(data, open("test.json", "w"), indent=2) # Only if you want the data put in a readable format to a file (like if you want to find the path to an entry)
downvote count: 0
answers question: http://stackoverflow.com/q/50645645
score: 1

http://stackoverflow.com/a/59217760
downvote count: 0
has body: I'm assuming your signature field follows this pattern: AAA 123 letters followed by a space followed by numbers (int). Item.objects.extra(select={ 's1': 'cast(split_part(signature, \' \', 2) as int)', 's2': 'split_part(signature, \' \', 1)' }).order_by('s2', 's1')
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50689359

http://stackoverflow.com/q/50665615
has answer: http://stackoverflow.com/a/50679050
has title: tkinter Scrolled Frame Buttons Resize with Frame
type: Question
linked to: http://stackoverflow.com/q/29319445
has body: I have created (with help) a Frame class with scrollbars on it. Seems to work well but I would like the buttons to size themselves to the size of the frame. Right now if you look they are all bunched up to the left side. I have looked through lots of examples and this seems common. Included below is some easy run code so you can see the issue. Attached below is a picture of the issue. Thank you. from tkinter import * class ScrolledFrame(Frame): def __init__(self, top, *args, **kwargs): Frame.__init__(self, top, *args, **kwargs) hscrollbar = Scrollbar(self, orient=HORIZONTAL) hscrollbar.grid(row=1, column=0, sticky=E+W) vscrollbar = Scrollbar(self, orient=VERTICAL) vscrollbar.grid(row=0, column=1, sticky=N+S) self.canvas = Canvas(self, xscrollcommand=hscrollbar.set, yscrollcommand=vscrollbar.set) self.canvas.grid(row=0, column=0, sticky=N+S+E+W) hscrollbar.config(command = self.canvas.xview) vscrollbar.config(command = self.canvas.yview) # Make the canvas expandable self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) # Create the canvas contents self.frame = Frame(self.canvas) self.frame.rowconfigure(1, weight=1) self.frame.columnconfigure(1, weight=1) self.canvas.create_window(0, 0, window=self.frame, anchor=N+W) self.canvas.config(scrollregion=self.canvas.bbox('all')) self.frame.bind('&lt;Configure&gt;', self.frame_changed) def frame_changed(self, event): self.frame.update_idletasks() self.canvas.config(scrollregion=self.canvas.bbox('all')) root = Tk() frame = ScrolledFrame(root) frame.grid(row=0, column=0, sticky=N+E+W+S) root.rowconfigure(0, weight=1) root.columnconfigure(0, weight=1) for i in range(20): button = Button(frame.frame, text='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx %d' % i) button.pack(fill=BOTH, side=TOP, expand=True) root.mainloop()
score: 0
accepted answer: http://stackoverflow.com/a/50679050
answer count: 1
tagged with: positioning
tagged with: python
type: AnsweredQuestion
tagged with: tkinter

http://stackoverflow.com/comment/88367802
comment on: http://stackoverflow.com/q/50677932
score: 0
has text: i'm not sure i understand your problem. do you want to get all direction changes?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50570524
has body: Say I have a function that takes a value and a arbitrary number of functions, let's call the function for chain_call. Without types a simple naive implementation would be: def chain_call(input_value, *args): for function in args: input_value = function(input_value) return input_value As you imagine, input_value could be anything really but it's always the same as the first and only required argument of the first Callable in *args: List[Callable]. From here and forward the Callable´s first and only required argument is the same type as the previous items return-type. So far I've managed to define a quite generic type but it's too loose. def chain_call(input_value: Any, *args: List[Callable[Any], Any]) -&gt; Any: ... What I'd really like is something like T = TypeVar('T') def chain_call(input_value: T, *args: List[Callable[T, ...], tr]) -&gt; tr: ... Where T for Callable n+1 is tr of Callable n and the final return-type is tr of Callable n_max. I'm not sure how to express this with the type system and would love any guidance.
tagged with: type-hinting
tagged with: higher-kinded-types
has answer: http://stackoverflow.com/a/64607153
upvote count: 5
has comment: http://stackoverflow.com/comment/88153292
accepted answer: http://stackoverflow.com/a/64607153
type: AnsweredQuestion
tagged with: types
downvote count: 0
favorite count: 0
tagged with: python-3.x
has title: Chained references in python type annotations
type: Question
answer count: 2
score: 5
tagged with: python
possible better answer: http://stackoverflow.com/a/50634026
has answer: http://stackoverflow.com/a/50634026

http://stackoverflow.com/comment/88293431
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50641312
has text: @Rakesh I forgot to add the extractTags function also. It's updated now in the post.

http://stackoverflow.com/q/50592625
answer count: 2
has answer: http://stackoverflow.com/a/50592685
tagged with: pandas
upvote count: 0
favorite count: 0
has title: How get a column's mean based in another column vale
type: UnansweredQuestion
tagged with: python
has body: I have a dataframe like this: Random number Location Month Value xxxxxxx USA September 5 xxxxxxx Canada September 4 xxxxxxx Canada September 4 xxxxxxx Canada July 9 xxxxxxx Italy February 6 . . . . . . . . . . . . xxxxxxx USA January 10 How can I get a value's mean in Canada? In my case is 200 Locations , I can't do it one by one. Had another way to get the mean. Is posible do a dict with the mean? Tks.
has comment: http://stackoverflow.com/comment/88194699
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50592661
score: -1
has comment: http://stackoverflow.com/comment/88194853

http://stackoverflow.com/a/50717031
downvote count: 0
has body: If you are open to using a 3rd party library, you can use pandas: import pandas as pd # read csv file df = pd.read_csv('file_in.csv') # perform groupby res = df.groupby('Cluster')'Latitude', 'Longitude'.mean().reset_index() print(res) # Cluster Latitude Longitude # 0 214 22.289210 19.812105 # 1 422 22.332293 19.752901 # 2 500 22.296393 19.624689 # write to csv res.to_csv('file_out.csv', index=False)
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50684104
type: Answer
answers question: http://stackoverflow.com/q/50684104

http://stackoverflow.com/comment/88185482
type: QuestionComment
comment on: http://stackoverflow.com/q/50587540
has text: Apparently, feed_dict is less efficient than using a buffer in this way because of how python/tensorflow fetches data. I don't know the full details - which you can read about here: https://www.tensorflow.org/performance/performance_guide But I can see this making sense. Firstly, I can see my python script utilizing less of the cpu/gpu as its RAM utilization increases - utilization eventually drops by more than half. Secondly, I tried posting a "simple" version, but in a situation where you are feeding a lot of mostly static data, it might be better to use some buffer, like the queue.
score: 1
type: Comment

http://stackoverflow.com/q/50591396
has title: Visually show hierarchy in data and filter out a path based on search criteria in Python
type: Question
has body: I have data as below in excel and I want show the data in graphical form showing layers of hierarchy. Also, when a search criteria like a child is searched then need to show only the path that leads to that node from top. I am new to python and I am trying to learn visualizing hierarchy data using Python. I also checked Python Library NetworKx for this. Can somebody please guide me right direction. Data: child parent 1 2010 1000 7 2100 1000 5 2110 1000 3 3000 2110 2 3011 2010 4 3033 2100 0 3102 2010 6 3111 2110 Output:
answer count: 1
accepted answer: http://stackoverflow.com/a/50591830
tagged with: python
tagged with: python-3.x
score: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50591830

http://stackoverflow.com/a/69296734
has body: If you use virtual environment, check(command : pip freeze) if whitenoise is installed. If yes, you can add below details to your settings.py to work. MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # ... ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), # '/var/www/static/', ] Verify/ Update your static setttings as stated above. Next, make sure DEBUG=True and run, the collectstatic command. To see if any errors, run makemigrations and migrate command. You should be good
accepted answer of: http://stackoverflow.com/q/50552846
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50552846
score: 0
type: Answer

http://stackoverflow.com/a/50605749
upvote count: 1
score: 1
downvote count: 0
has body: The reason you cant update your label is because you haven't stored it in any variable. The grid, pack and place functions of the Label object and of all other widgets returns None, therefore when you call: letter = Label(play, text = dashes, font = ("Arial",20)).grid(row = 2, column = i+1,padx = 10, pady =10) your label cannot be accessed by variable letter. To fix this you should split it like so: letter = Label(play, text = dashes, font = ("Arial",20)) letter.grid(row = 2, column = i+1,padx = 10, pady =10) To update text of that label, you can call .configure(text = 'new text') on it. # letter = Label(play, text = dashes, font = ("Arial",20)).grid(row = 2, column = i+1,padx = 10, pady =10) # letter.configure(text = dashes) As for your second issue, i think you confused while loop and if statement in the function enterLetter. It's called once per click and you only need to check one time if player has ran out of guesses. if guesses != 0: ... elif guesses == 0: ....
type: Answer
answers question: http://stackoverflow.com/q/50605101

http://stackoverflow.com/a/66819617
score: 0
has comment: http://stackoverflow.com/comment/118120875
has comment: http://stackoverflow.com/comment/118497550
type: Answer
has body: This is a ban command I use and it works perfectly fine for me. You have full permission to use the whole thing if you'd like. async def ban(self, ctx, member:discord.Member, *, reason=None): guild = ctx.guild author = ctx.message.author if author.guild_permissions.administrator == False: embed4=discord.Embed(color=discord.Colour.red(), timestamp=datetime.datetime.utcnow(), title="Missing Permissions!", description="You don't have the required permissions to use this command!") message1 = await ctx.send(embed=embed4) sleeper=5 await asyncio.sleep(sleeper) await message1.delete() return if member.guild_permissions.administrator and member != None: embed=discord.Embed(color=discord.Colour.red(), title="Administrator", description="This user is an administrator and is not allowed to be banned.") message2 = await ctx.send(embed=embed) sleeper=5 await asyncio.sleep(sleeper) await message2.delete() return if reason == None: embed1=discord.Embed(color=discord.Colour.red(), title="Reason Required!", description="You must enter a reason to ban this member.") message3 = ctx.send(embed=embed1) sleeper=5 await asyncio.sleep(sleeper) await message3.delete() return else: guild = ctx.guild await member.ban() embed2=discord.Embed(color=discord.Colour.green(), timestamp=datetime.datetime.utcnow(), title="Member Banned", description=f"Banned: {member.mention}\n Moderator: **{author}** \n Reason: **{reason}**") embed3=discord.Embed(color=discord.Colour.green(), timestamp=datetime.datetime.utcnow(), title=f"You've been banned from **{guild}**!", description=f"Target: {member.mention}\nModerator: **{author.mention}** \n Reason: **{reason}**") message4 = await ctx.send(embed=embed2) message5 = await ctx.send("✔ User has been notified.") sleeper=5 await asyncio.sleep(sleeper) await message4.delete() await message5.delete() await member.send(embed=embed3)
answers question: http://stackoverflow.com/q/50569780

http://stackoverflow.com/comment/88404306
has text: I am using Windows 10
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50697174

setuptools
tags question: http://stackoverflow.com/q/50667413
tags question: http://stackoverflow.com/q/50685024
tags question: http://stackoverflow.com/q/50585246
tag name: setuptools
tags question: http://stackoverflow.com/q/50606484
tags question: http://stackoverflow.com/q/50678754
type: Tag
tags question: http://stackoverflow.com/q/50631966

http://stackoverflow.com/a/50543479
score: 0
has comment: http://stackoverflow.com/comment/88105004
has body: I think none of the other suggested solutions works if the largest number appears multiple times in nums. This does: def dominantIndex(self, nums): s = sorted(nums) if s[-1] &gt;= 2 * s[-2]: return nums.index(s[-1]) else: return -1 In addition, you might want to check if nums has more than one element.
has comment: http://stackoverflow.com/comment/88133521
has comment: http://stackoverflow.com/comment/88146032
has comment: http://stackoverflow.com/comment/88111895
type: Answer
answers question: http://stackoverflow.com/q/50543265

http://stackoverflow.com/q/50671321
type: Question
accepted answer: http://stackoverflow.com/a/50671836
score: 0
tagged with: abstract-syntax-tree
answer count: 1
tagged with: python
has body: Let's say the name of the module is available in form of a string rather than module object. How do I locate its source code location and load the abstract syntax tree (if the source code is present)?
has answer: http://stackoverflow.com/a/50671836
has title: How to load abstract syntax tree of a python module by its name?
type: AnsweredQuestion

http://stackoverflow.com/comment/88291071
comment on: http://stackoverflow.com/a/50639339
type: Comment
has text: [ [('Material', 'Wood'), ('Base', 'Red Gold'), ('Color', 'Red'), ('year', '2020')], [('Material', 'Wood'), ('Base', 'Red Gold'), ('Color', 'Blue'), ('year', '2010')], [('Material', 'Wood'), ('Base', 'Red Gold'), ('Color', 'Blue'), ('year', '2020')] ] ???
score: 0
type: AnswerComment

http://stackoverflow.com/q/50676965
linked to: http://stackoverflow.com/q/22934996
tagged with: pytables
has body: I'm using pandas HDFStore to store data in hfd5 files. Typically, data is appended one sample at a time, rather than by long batches. I noticed the files are growing pretty fast and I can reduce them substantially with ptrepack. Here's an example with a small file. The file generated by my application (using zlib and complevel 9) is 6.7 MB big. / (RootGroup) '' /test (Group) '' /test/table (Table(1042,), shuffle, zlib(1)) '' description := { "index": Int64Col(shape=(), dflt=0, pos=0), "values_block_0": Float64Col(shape=(2,), dflt=0.0, pos=1), "values_block_1": Int64Col(shape=(1,), dflt=0, pos=2)} byteorder := 'little' chunkshape := (2048,) autoindex := True colindexes := { "index": Index(6, medium, shuffle, zlib(1)).is_csi=False} If I ptrepack it with no option, it gets dramatically smaller (71K): / (RootGroup) '' /test (Group) '' /test/table (Table(1042,)) '' description := { "index": Int64Col(shape=(), dflt=0, pos=0), "values_block_0": Float64Col(shape=(2,), dflt=0.0, pos=1), "values_block_1": Int64Col(shape=(1,), dflt=0, pos=2)} byteorder := 'little' chunkshape := (2048,) When using --complevel=1 or --complevel=9, I get a 19K file. / (RootGroup) '' /test (Group) '' /test/table (Table(1042,), shuffle, zlib(1)) '' description := { "index": Int64Col(shape=(), dflt=0, pos=0), "values_block_0": Float64Col(shape=(2,), dflt=0.0, pos=1), "values_block_1": Int64Col(shape=(1,), dflt=0, pos=2)} byteorder := 'little' chunkshape := (2048,) / (RootGroup) '' /test (Group) '' /test/table (Table(1042,), shuffle, zlib(9)) '' description := { "index": Int64Col(shape=(), dflt=0, pos=0), "values_block_0": Float64Col(shape=(2,), dflt=0.0, pos=1), "values_block_1": Int64Col(shape=(1,), dflt=0, pos=2)} byteorder := 'little' chunkshape := (2048,) These are small files, but my point is that I could downsize the whole 35GB database to a few hundreds MB just by repacking it. There has to be something wrong in the way it is written. I know about the "hdf5 does not reclaim space" warning. The…
has comment: http://stackoverflow.com/comment/89548133
tagged with: pandas
score: 2
answer count: 0
downvote count: 0
tagged with: hdfstore
favorite count: 0
type: Question
upvote count: 2
has title: hdf5 files growing huge while only appending
tagged with: python
tagged with: hdf5
has comment: http://stackoverflow.com/comment/89555888
type: UnansweredQuestion

http://stackoverflow.com/q/50614498
tagged with: python
has comment: http://stackoverflow.com/comment/88254892
tagged with: tkinter
has body: I have created a bunch of OVALS. And have defined a variable (w_oval) to be used in a FOR. Itemconfigure does not accept this variable. Something about immutable variables? How do I define a variable for the itemconfigure? I know I'm missing some philosophy here. b1_oval = bottom_frame.create_oval( 25,180,65,205, fill='') b2_oval = bottom_frame.create_oval( 25,180,65,205, fill='') #... more bn_oval i_oval = 0 w_oval = '' ovalLONG = [-90,-75,-60,-45,-30,-15,0,15,30,45,60,75,90] for j in ovalLONG: i_oval = i_oval + 1 w_oval = str('b'+str(i_oval)+'_oval') # Not flying Wilbur if i == j: bottom_frame.itemconfigure(w_oval, fill='goldenrod3')
type: Question
has comment: http://stackoverflow.com/comment/88257447
has title: Tkinte: loop through image objects and set itemconfigure
has comment: http://stackoverflow.com/comment/88239383
score: 0
answer count: 1
duplicate of: http://stackoverflow.com/q/1373164
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50627023
linked to: http://stackoverflow.com/q/1373164

http://stackoverflow.com/a/50576528
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88162223
downvote count: 0
type: Answer
has body: You'll need to determine whether all columns of a row have zeros or not. Given a boolean mask, use DataFrame.all(axis=1) to do that. df[df[mylist].eq(0).all(1)] a b c d 2 0 0 3 4 4 0 0 0 0 Note that if you wanted to find rows with zeros in every column, remove the subsetting step: df[df.eq(0).all(1)] a b c d 4 0 0 0 0
accepted answer of: http://stackoverflow.com/q/50576470
answers question: http://stackoverflow.com/q/50576470
upvote count: 10
score: 10

http://stackoverflow.com/comment/88342058
type: Comment
comment on: http://stackoverflow.com/a/50641813
has text: after removing I am getting an output but a wrong one
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88274939
has text: Instagram requires registration to access anything whatsoever, so I cannot give a concrete example.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50632242

http://stackoverflow.com/comment/88112425
has text: @SamanthaLeo use rb when reading files(or opening them). This will most probably resolve the error
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50543024
type: Comment

http://stackoverflow.com/comment/88237664
type: Comment
score: 1
has text: @CDNthe2nd I see it. I'm working on a big edit on the answer.
type: AnswerComment
comment on: http://stackoverflow.com/a/50613637

http://stackoverflow.com/comment/88329829
score: 1
comment on: http://stackoverflow.com/q/50659796
has text: Use `text_clf = Pipeline([ ('tfidf', TfidfTransformer()), ('clf', MultinomialNB(alpha=.01)) ])` and it should work as expected.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88245685
type: QuestionComment
has text: I'll copy-paste the result I'm getting. Yes I am still getting -1
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50617915

http://stackoverflow.com/comment/88267913
has text: You've got it; `type.__call__()` calls `__new__()` first, then calls `__init__()` if `__new__()` returned an instance of the class. See https://docs.python.org/3/reference/datamodel.html#object.__new__
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50628941
type: Comment

http://stackoverflow.com/a/50594962
has comment: http://stackoverflow.com/comment/88269409
upvote count: 3
answers question: http://stackoverflow.com/q/50594852
accepted answer of: http://stackoverflow.com/q/50594852
score: 3
has comment: http://stackoverflow.com/comment/88269834
has comment: http://stackoverflow.com/comment/88269483
type: AcceptedAnswer
downvote count: 0
has body: IIUC df['New']=df.b.loc[df.k==1]# get all value b when k equal to 1 df.New=df.groupby('a').New.apply(lambda x : x.ffill().shift()) # fillna by froward method , then we need shift. df.b-df['New']# yield Out[260]: 0 NaN 1 NaN 2 1.0 3 2.0 4 3.0 5 1.0 6 NaN 7 NaN 8 1.0 9 2.0 10 1.0 dtype: float64
type: Answer

http://stackoverflow.com/a/50574998
has comment: http://stackoverflow.com/comment/88195015
downvote count: 0
has comment: http://stackoverflow.com/comment/88196554
has comment: http://stackoverflow.com/comment/88196143
has comment: http://stackoverflow.com/comment/88196477
upvote count: 2
has comment: http://stackoverflow.com/comment/88196402
answers question: http://stackoverflow.com/q/50573260
has body: I assume you're after something like this: The official documentation explains how to do everything, which is much more than you need right now. You need the label widget, the entry widget, the button widget and the packer geometry manager. A good tutorial for you might be ZetCode, and this answer is based partly on his code: #### Save this as dual_input.py #### #! /usr/bin/env python # -*- coding: utf-8 -*- from tkinter import Tk, Text, TOP, BOTH, X, N, LEFT, RIGHT from tkinter.ttk import Frame, Label, Entry, Button # Good habit to put your GUI in a class to make it self-contained class SimpleDialog(Frame): def __init__(self): super().__init__() # self allow the variable to be used anywhere in the class self.output1 = "" self.output2 = "" self.initUI() def initUI(self): self.master.title("Simple Dialog") self.pack(fill=BOTH, expand=True) frame1 = Frame(self) frame1.pack(fill=X) lbl1 = Label(frame1, text="Input 1", width=6) lbl1.pack(side=LEFT, padx=5, pady=10) self.entry1 = Entry(frame1, textvariable=self.output1) self.entry1.pack(fill=X, padx=5, expand=True) frame2 = Frame(self) frame2.pack(fill=X) lbl2 = Label(frame2, text="Input 2", width=6) lbl2.pack(side=LEFT, padx=5, pady=10) self.entry2 = Entry(frame2) self.entry2.pack(fill=X, padx=5, expand=True) frame3 = Frame(self) frame3.pack(fill=X) # Command tells the form what to do when the button is clicked btn = Button(frame3, text="Submit", command=self.onSubmit) btn.pack(padx=5, pady=10) def onSubmit(self): self.output1 = self.entry1.get() self.output2 = self.entry2.get() self.quit() def main(): # This part triggers the dialog root = Tk() root.geometry("250x150+300+300") app = SimpleDialog() root.mainloop() # Here we can act on the form components or # better yet, copy the output to a new variable user_input = (app.output1, app.output2) print(app.output1) # Get rid of the error message if the user clicks the # close icon instead of the submit button # Any component of the dialog will no longer be available # past…
type: Answer
score: 2

http://stackoverflow.com/comment/88201980
type: Comment
comment on: http://stackoverflow.com/a/50596189
has text: @three_pineapples partial does not create a function, it only extends the arguments that you can see in the source code shown in the docs. Where did you get that partial create a new method?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88326343
score: 0
type: Comment
has text: @Verbal_Kint Just inherit from it. Sorry, I'm using very confusing names, that's my bad.
type: QuestionComment
comment on: http://stackoverflow.com/q/50657695

http://stackoverflow.com/q/50613391
tagged with: selenium
type: Question
tagged with: python-2.7
has body: Is there a way to get the outgoing AJAX request URL using Selenium? For example, when I click a button, it generates a AJAX request to get some data. How can I use Python to determine that GET request URL?
upvote count: 1
has comment: http://stackoverflow.com/comment/88236830
has comment: http://stackoverflow.com/comment/88236705
downvote count: 0
has comment: http://stackoverflow.com/comment/88244240
favorite count: 0
tagged with: python
tagged with: selenium-webdriver
answer count: 0
has title: How to get AJAX URL with Selenium (Python)?
type: UnansweredQuestion
score: 1

http://stackoverflow.com/q/50646640
answer count: 3
tagged with: pandas
favorite count: 0
type: UnansweredQuestion
tagged with: datetime
tagged with: python
has body: Basically I am trying to delete rows of a pandas dataframe where values in a certain column are not instances of datetime. I have tried: df = df[df[‘date’] == isinstance(datetime)] I know isinstance takes two arguments (I am missing the value to be checked) but I’m not sure what to put there.
score: 2
downvote count: 0
has title: Deleting rows of pandas dataframe based on instance type
linked to: http://stackoverflow.com/q/46999146
type: Question
has answer: http://stackoverflow.com/a/50647126
has answer: http://stackoverflow.com/a/50646741
has answer: http://stackoverflow.com/a/50647143
upvote count: 2

http://stackoverflow.com/q/50561076
has comment: http://stackoverflow.com/comment/88132676
downvote count: 0
possible better answer: http://stackoverflow.com/a/50561171
has comment: http://stackoverflow.com/comment/88132781
has comment: http://stackoverflow.com/comment/88132708
has answer: http://stackoverflow.com/a/50561171
has body: I have a list of dict, list dict = [ {'children': [], 'folder': 'test2', 'parent': 'None'}, {'children': [{'children': [], 'folder': 'arun2', 'parent': 'arun2'}], 'folder': 'arun2', 'parent': 'None'}, {'children': [], 'folder': 'important', 'parent': 'None'}, {'children': [], 'folder': 'arun', 'parent': 'None'}, {'children': [], 'folder': 'hoi', 'parent': 'None'}, {'children': [], 'folder': 'drafts', 'parent': 'None'}, {'children': [], 'folder': 'Trash', 'parent': 'None'}, {'children': [], 'folder': 'sent', 'parent': 'None'}, {'children': [], 'folder': 'spam', 'parent': 'None'}, {'children': [], 'folder': 'reference', 'parent': 'None'}, {'children': [], 'folder': 'test3', 'parent': 'None'}, {'children': [], 'folder': 'test1', 'parent': 'None'}, {'children': [], 'folder': 'INBOX', 'parent': 'None'} ] Now i want to remove dict from list_dict that has all the values in the remove_key_list remove_key_list = ['INBOX','sent','Trash'] For example i want remove {'children': [], 'folder': 'INBOX', 'parent': 'None'} from list dict and return the list dict I'm new to python how to use del , lamda functions here.
accepted answer: http://stackoverflow.com/a/50561177
favorite count: 0
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88132722
type: Question
has comment: http://stackoverflow.com/comment/88132680
has comment: http://stackoverflow.com/comment/88132596
has comment: http://stackoverflow.com/comment/88132690
score: 4
has title: Remove dict from list of matching values
upvote count: 4
has answer: http://stackoverflow.com/a/50561177
answer count: 2

http://stackoverflow.com/q/50555355
answer count: 1
downvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50555806
has title: How can I exclude the list of web-pages from google-search results?
upvote count: 0
tagged with: google-custom-search
has body: "minus" sign doesn't fit because the list consists of ~2000 entries. I'm just beginner in python, so, please explain as to 5-year old, if possible Thank you much in advance!
type: Question
tagged with: google-sheets
tagged with: google-search
score: -1

http://stackoverflow.com/q/50610089
tagged with: beautifulsoup
type: Question
has answer: http://stackoverflow.com/a/50612661
has comment: http://stackoverflow.com/comment/88229890
tagged with: python
answer count: 1
has title: Wait for result to load in Python Data Scraping
upvote count: 1
has comment: http://stackoverflow.com/comment/88231715
type: UnansweredQuestion
has body: I am coding a data scaper but I don't know what to do for Python wait to the request that I made to load. I am pulling a table from this link: http://www.ans.gov.br/perfil-do-setor/dados-e-indicadores-do-setor/sala-de-situacao Go to Caderno 2.0 Select the first value at the droplist Run anything The big question here is: when I run the query at the website, the website takes a while to get the output, so I need to figure out how to get Python into standby till the result comes out (see picture below) Image execution message Can someone help me with that? Please. Thanks so much!
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/a/50636437
answers question: http://stackoverflow.com/q/50636424
type: Answer
score: 3
upvote count: 3
has body: Use map by dict created with zip: L1 = ['excellent', 'good', 'average', 'bad', 'very bad'] L2 = ['EX', 'G', 'Avg', 'B', 'VB'] df['col'] = df['col'].map(dict(zip(L1, L2))) Detail: print (dict(zip(L1, L2))) {'excellent': 'EX', 'good': 'G', 'average': 'Avg', 'bad': 'B', 'very bad': 'VB'}
accepted answer of: http://stackoverflow.com/q/50636424
has comment: http://stackoverflow.com/comment/88282972
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50651996
has title: keras fine-tuning a pre-trained model does not change weights when using multi_gpu_model and layers.trainable = True
tagged with: tensorflow
type: Question
tagged with: keras
has comment: http://stackoverflow.com/comment/88821889
has comment: http://stackoverflow.com/comment/88314981
answer count: 0
type: UnansweredQuestion
has body: I'm loading the VGG16 pretrained model, adding a couple of dense layers and fine tuning the last 5 layers of the base VGG16. I'm training my model on mutliple gpus. I saved the model before and after training. The weights are the same inspite of having layers.trainable = True. Please help! Heres the code from keras import applications from keras import Model &lt;import other relevant Keras layers, etc.&gt; model = applications.VGG16(weights = "imagenet", include_top = False, input_shape = (224,224,3)) model.save('./before_training') for layer in model.layers: layer.trainable = False for layer in model.layers[-5:]: layer.trainable = True x = model.output x = Flatten()(x) x = Dense(1024, activation = "relu")(x) x = Dropout(0.5)(x) x = Dense(1024, activation = "relu")(x) predictions = Dense(2, activation = "softmax")(x) model_final = Model(input = model.input, output = predictions) from keras.utils import multi_gpu_model parallel_model = multi_gpu_model(model_final, gpus = 4) parallel_model.compile(loss = "categorical_crossentropy" ..... ) datagen = ImageDataGenerator(....) early = EarlyStopping(...) train_generator = datagen.flow_from_directory(train_data_dir,...) validation_generator = datagen.flow_from_directory(test_data_dir,...) parallel_model.fit_generator(train_generator, validation_data = valiudation_generator,...) model_final.save('./after_training) Weights in before_training and after_training models are the same!!! Which is not what I expected!
tagged with: python
tagged with: multi-gpu
has comment: http://stackoverflow.com/comment/88810905
score: 0

http://stackoverflow.com/comment/88392766
score: 1
comment on: http://stackoverflow.com/a/50689688
type: AnswerComment
has text: @user2675516 Please don't take offense at the somewhat flippant "reinventing the wheel" . The numpy-version is reusing the matrix-matrix-multiplication, one of the best optimized algorithms that is out there, - what a beauty! At the beginning it was not clear to me, that this is basically what the calculation was about...
type: Comment

http://stackoverflow.com/a/50633767
has comment: http://stackoverflow.com/comment/88293542
type: Answer
has comment: http://stackoverflow.com/comment/88542960
has body: You need to append new urls to a list as you find them, and continually iterate through the list of urls extracting the content you are looking for. from urllib.request import urlopen as Req from bs4 import BeautifulSoup as souce start_url='https://www.ebay.de/sch/i.html?_fosrp=1&amp;_from=R40&amp;_nkw=iphone&amp;_in_kw=1&amp;_ex_kw=&amp;_sacat=0&amp;_mPrRngCbx=1&amp;_udlo=600&amp;_udhi=4.800&amp;LH_BIN=1&amp;LH_ItemCondition=4&amp;_ftrt=901&amp;_ftrv=1&amp;_sabdlo=&amp;_sabdhi=&amp;_samilow=&amp;_samihi=&amp;_sadis=10&amp;_fpos=&amp;LH_SubLocation=1&amp;_sargn=-1%26saslc%3D0&amp;_fsradio2=%26LH_LocatedIn%3D1&amp;_salic=77&amp;_saact=77&amp;LH_SALE_CURRENCY=0&amp;_sop=2&amp;_dmd=1&amp;_ipg=200' page_urls =[start_url] for purl in page_urls: Client=Req(purl) page_html=Client.read() Client.close() page_soup=souce(page_html, "html.parser") containers_listings = page_soup.findAll("li",{"class":"sresult lvresult clearfix li"}) container_next=page_soup.find("td",{"class":"pagn-next"}) next_url=container_next.a["href"] #this is where you would add your new link if next_url not in page_urls: page_urls.append(next_url) filename="scrape_ebay.csv" f=open(filename,"w") headers="item_title,item_link,item_price\n" f.write(headers) for container in containers_listings: item_title=container.h3.text.strip() item_link=container.h3.a["href"].strip() item_price=container.span.text.strip() f.write(item_title + "," + item_link + "," + item_price.replace(",",".") + "\n") f.close()
answers question: http://stackoverflow.com/q/50633442
score: 0

http://stackoverflow.com/a/50569035
score: 1
type: AcceptedAnswer
upvote count: 1
has body: Check out this link here with a working example of Hough Circles. https://www.pyimagesearch.com/2014/07/21/detecting-circles-images-using-opencv-hough-circles/ I'm not familiar with them myself, but I did take a Computer Vision class a few semesters ago and found this site very helpful in general. In the article, he provides some code with comments. It seems like circles is a list of all the circles detected in the image. It appears that a circle is an object containing the coordinates of the circle center along with the radius. # detect circles in the image circles = cv2.HoughCircles(gray, cv2.cv.CV_HOUGH_GRADIENT, 1.2, 100) # ensure at least some circles were found if circles is not None: # convert the (x, y) coordinates and radius of the circles to integers circles = np.round(circles[0, :]).astype("int") # loop over the (x, y) coordinates and radius of the circles for (x, y, r) in circles: # draw the circle in the output image, then draw a rectangle # corresponding to the center of the circle cv2.circle(output, (x, y), r, (0, 255, 0), 4) cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1) # show the output image cv2.imshow("output", np.hstack([image, output])) cv2.waitKey(0) About your code, for more details about the value of i, try printing i as well as getting the type, and that should give you a hint. print i print type(i)
accepted answer of: http://stackoverflow.com/q/50568668
type: Answer
answers question: http://stackoverflow.com/q/50568668
downvote count: 0

http://stackoverflow.com/q/50579783
possible better answer: http://stackoverflow.com/a/59640371
tagged with: plotly-dash
has answer: http://stackoverflow.com/a/50580439
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/50580439
favorite count: 0
upvote count: 2
tagged with: python
type: AnsweredQuestion
score: 2
has title: Plotly Dash - how to set automated colors rather than having blue for everything
has body: I'm looking to get help in creating a bar chart in Dash (plotly) and having more than one color for all bars,at the moment they are all blue. e.g. pv = pd.pivot_table(df, index=['customer_name2'], columns=['FY'], values=['amount'], aggfunc=sum, fill_value=0) pv2 = pv.reindex(pv['amount'].sort_values(by='FY17', ascending=True).index).head(x_bottom) trace1 = go.Bar(x=pv2.index, y=pv2[('amount','FY17')], name='Revenue') graphs.append(html.Div(dcc.Graph( id='chart_id_6', figure={ 'data': [trace1], 'layout': { 'title': 'Bottom ' + str(x_bottom) + ' Customers' } })))
has answer: http://stackoverflow.com/a/59640371
tagged with: plotly
type: Question

http://stackoverflow.com/comment/88242204
comment on: http://stackoverflow.com/q/50616048
has text: Possible duplicate of [Obtaining more than 20 results with Google Places API](https://stackoverflow.com/questions/6965847/obtaining-more-than-20-results-with-google-places-api)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50673552
type: AcceptedAnswer
downvote count: 0
has body: You could use the following expression: world_wide='([^/]+) # world_wide=' # capture anything not a / into group 1 In Python this is: import re value = "world_wide='test1/one/two', " \ "stage_test='ALPHA', world_wide='test2/one/two', " \ "stage_test='GAMMA', world_wide='test3/one/two', " \ "stage_test='GAMMA', world_wide='test4/one/two', " \ "stage_test='ALPHA', world_wide='test5/one/two', " \ "stage_test='GAMMA', world_wide='test6/one/two', " \ "stage_test='GAMMA" rx = re.compile(r'''world_wide='([^/]+)''') parts = rx.findall(value) print(parts) This yields a list containing ['test1', 'test2', 'test3', 'test4', 'test5', 'test6'] See a demo on regex101.com.
type: Answer
accepted answer of: http://stackoverflow.com/q/50673360
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50673360

http://stackoverflow.com/a/50676474
has body: I thought I had this problem, hence the upvote. But I simply wasnt waiting long enough. Leave the eval running for the at least couple of hours or longer alongside the train job.
accepted answer of: http://stackoverflow.com/q/50642500
answers question: http://stackoverflow.com/q/50642500
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/88181756
type: QuestionComment
has text: https://eli.thegreenplace.net/2012/01/30/the-bytesstr-dichotomy-in-python-3 Might give you a good crash course on the difference between bytes and strings.
score: 1
comment on: http://stackoverflow.com/q/50586045
type: Comment

http://stackoverflow.com/comment/93748507
comment on: http://stackoverflow.com/q/50688468
has text: It was pandas version, try to downgrade and see if it works
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50679560
has answer: http://stackoverflow.com/a/50679609
accepted answer: http://stackoverflow.com/a/50679609
upvote count: 0
answer count: 1
favorite count: 0
has title: Pyyaml, accessing dictionary in Python
tagged with: python
downvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88368564
has body: I have some yaml I'm trying to access keys in python. --- nodes: - AAAA: AAAA BBBB: BBBB CCCC: CCCC DDDD: AAAA: AAAA BBBB: AAAA CCCC: CCCC - AAAA: AAAA BBBB: BBBB CCCC: CCCC DDDD: AAAA: AAAA BBBB: AAAA CCCC: CCCC I'm trying to access using the following python format. import yaml filepath = "report.yml" audit = yaml.load(open(filepath)) audit['nodes']['DDDD'].items() but I get the following error. print audit['nodes']['DDDD'].items() TypeError: list indices must be integers, not str Whats i'm expetcting to see is a list of key/values returned under DDDD Obviously, I'm mixing up lists and dicts, but I don't quite see how... is it the yaml, python or my understanding of how pyyaml nests dicts in dicts?
score: -2
tagged with: pyyaml
type: Question

http://stackoverflow.com/a/50597403
answers question: http://stackoverflow.com/q/50567229
score: 0
type: AcceptedAnswer
has body: I managed to get it working using round_amount = 1*1*1000000000 data[i].index = pd.DatetimeIndex(((data[i].index.asi8/(round_amount)).round()*round_amount).astype(np.int64)) Which rounds the DatetimeIndex to the nearest second.
type: Answer
accepted answer of: http://stackoverflow.com/q/50567229

http://stackoverflow.com/a/50704295
downvote count: 1
type: Answer
score: 1
answers question: http://stackoverflow.com/q/50591068
has body: Get the frames per second from the video or default to 25 as a reasonable guess, then step through the paused video, using the frames per second as your jump forward each time. import vlc import time instance = vlc.Instance('--no-xlib --quiet') player = instance.media_player_new() media = instance.media_new("./bebop.sdp"") player.set_media(media) player.play() mfps = int(1000 / (player.get_fps() or 25)) player.set_time(30000) # start at 30 seconds player.pause() t = player.get_time() for iter in range(30): t += mfps player.set_time(t) if player.get_state() == 3: player.pause() time.sleep(0.5) Here, I start at the 30 second mark and then advance just 30 times. You will probably want to keep advancing until player.get_state() == 6 indicating that the video has finished. [state 3 = playing]
upvote count: 2

http://stackoverflow.com/q/50691608
accepted answer: http://stackoverflow.com/a/50691855
score: 0
has comment: http://stackoverflow.com/comment/88392919
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/50691843
has answer: http://stackoverflow.com/a/50691855
has answer: http://stackoverflow.com/a/50691843
has body: I'm begginer in django. I have a problem with error: No Part matches the given query. views.py: from description.models import Part from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.shortcuts import render_to_response, get_object_or_404 def PartyNumView(request, pk=None, page_number = 1): all_parties = Part.objects.all() current_page = Paginator(all_parties, 10) try: context = current_page.page(page_number) except PageNotAnInteger: context = current_page.page(1) except EmptyPage: context = current_page.page(current_page.num_pages) onePart = get_object_or_404(Part, pk = pk) return render_to_response('part_list.html', {'PartyNum': context, 'onePart': onePart}) urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^parties/(\d+)/$', PartyNumView), url(r'^parties', PartyNumView), url(r'parties/(?P<pk>[\d]+)$', PartyNumView, name='onePart'), url(r'^main/', TemplateView.as_view(template_name='main.html')), #static html url(r'^measures/', TemplateView.as_view(template_name='IcDesc.html')), #static html ] And a little bit of part_list.html: {% for object in PartyNum %} {{ forloop.counter }} {{ object.Party_number }} {{ object.Film }} {{ object.Thick }} {{ object.Critical_temperature }} {{ object.R_s }} {% endfor %} In Models.py I have a class Part(models.Model) Help me please find a mistake.
has title: No Part matches the given query
tagged with: django
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/88268527
score: 0
type: Comment
type: QuestionComment
has text: Yeah now it works, must have done something wrong. But I thought the `?` after the `(\'\w+)` makes it non-capturing?
comment on: http://stackoverflow.com/q/50629057

http://stackoverflow.com/comment/88178224
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50584368
has text: Fast solution worked, but I will yet try to load `keras` modules inside function `create_model`

http://stackoverflow.com/a/50592369
accepted answer of: http://stackoverflow.com/q/50592008
has body: TextFields, CharFields, are typically only used to store, well text. Yes there are some special subclasses to store for example JSON objects and IP addresses, but typically this is only a good idea if you do not have to filter on the subparts of these objects, or do not have to treat these as individual subelements. JSON fields are not bad, especially since they introduce a certain dynamic that is hard to represent in a (relational) database, but one should use them with care in a relational database. Here you basically have two entities: Absent and an AbsentDate, and ther is a one-to-many relation between an Absent and AbsentDate. We can model this with a ForeignKey: class Absent(models.Model): # ... pass class AbsentDate(models.Model): absent = models.ForeignKey(Absent) date = models.DateField() class Meta: ordering = ['date'] So that means we have constructed something that looks like: +--------+ 1 N +------------+ | Absent |-------| AbsentDate | +--------+ +------------+ | date | +------------+ We can then for a certain Absent instance, query the set of related AbsentDates with: our_absent_instance.absentdate_set.all() So we can use this in a template like: {% for attend in attends %} &lt;td&gt; {% for attenddate in attend.absentdate_set.all %} {{ attends.attenddate.date }} {% endfor %} &lt;/td&gt; {% endfor %}
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50592008
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/50601116
type: Question
has comment: http://stackoverflow.com/comment/88211630
accepted answer: http://stackoverflow.com/a/50601461
has body: So I have been playing around with Multiprocessing and I was thinking to upgrade my knowledge where I can read the first sentence from the text file for process 1 then the second sentence for process 2 etc... txt file: helloworld@world.com helloworld2@world.com helloworld3@world.com helloworld4@world.com helloworld5@world.com and this is how the code is looking: def info(thread): global prod prod = int(thread) + 1 runit() def runit(): log("Profile-" + str(prod) + Fore.GREEN + ' - ' + email) #From here I can then use the email for each worker basically. Or thats the plan atleast. Theplan is that every worker will have its own email that can be used in here. sys.exit() def main(): user_input = 0 while True: try: user_input = int(input(Fore.WHITE + 'How many tasks do you wanna run? [NUMBERS] \n' + Fore.RESET)) except ValueError: print(Fore.RED + "Stop being stupid" + Fore.RESET) continue else: with open('email.txt') as f: content = f.readlines() content = [x.strip('\n') for x in content] try: for i, email in enumerate(content): print(email) except ValueError as e: print(e) HowManyThread = user_input i = 0 jobs = [] for i in range(HowManyThread): p = multiprocessing.Process(target=info, args=(str(i),)) jobs.append(p) time.sleep(.5) p.start() for p in jobs: p.join() sys.exit() Log is just a log message basically, Nothing special Fore.COLOR &lt;-- Colorama However, I have completely no idea what I should do to actually make each process take each email row. So basically.... Process-1 to take helloworld@world.com Process-2 to take helloworld2@world.com Process-3 to take helloworld3@world.com Process-4 to take helloworld4@world.com Process-5 to take helloworld5@world.com What are the suggestions on how I can do this? I'm completely off and have absolutely no idea on how to move forward. Update from multiprocessing import pool, Process, Queue from tqdm import tqdm with open('email.txt') as f: content = f.readlines() global email_list email_list = [x.strip('\n') for x in cont…
has answer: http://stackoverflow.com/a/50603735
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/50603735
has comment: http://stackoverflow.com/comment/88211852
has answer: http://stackoverflow.com/a/50601461
tagged with: python
tagged with: multiprocess
has comment: http://stackoverflow.com/comment/88212271
tagged with: text
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88211956
has title: Python - Multirprocessing, give each processor an email from a text file

http://stackoverflow.com/q/50658442
downvote count: 0
has comment: http://stackoverflow.com/comment/88327180
has body: I am trying to make a subplot from a few png files. However, it appears that the frame sizes of the photos were also included the resulting output. I appreciate if anybody could tell me why and how to resolve the issues? thanks import matplotlib.image as mpimg import matplotlib.pyplot as plt img1 = mpimg.imread('plot/test1.png') img2 = mpimg.imread('plot/test2.png') plt.figure(1) plt.subplot(121) plt.imshow(img1) plt.subplot(122) plt.imshow(img2) plt.show()
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88327068
tagged with: python
has comment: http://stackoverflow.com/comment/88327387
linked to: http://stackoverflow.com/q/2176424
answer count: 0
score: 1
tagged with: matplotlib
upvote count: 1
linked to: http://stackoverflow.com/q/25862026
has title: Subplot multiple images without framesize
duplicate of: http://stackoverflow.com/q/2176424
type: Question
has comment: http://stackoverflow.com/comment/88326969
has comment: http://stackoverflow.com/comment/88327535
tagged with: subplot
duplicate of: http://stackoverflow.com/q/25862026

http://stackoverflow.com/comment/88223705
comment on: http://stackoverflow.com/a/50607012
has text: but OP stated that "f this string 'newick' is going to appear, then it would be in the first 10 characters of the string", not necessarily at the start...
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/comment/104616358
has text: Yes, and I think the answer on how to use those tools to achieve the solution to the problem in this question is what both @n2o and myself are searching for
type: AnswerComment
comment on: http://stackoverflow.com/a/59199034
score: 0
type: Comment

http://stackoverflow.com/comment/88208095
has text: Ok , Got it. I will look for the alternative option . However the answers provided below seems to reasonable. I will edit as per my need keeping your suggestion in mind as well.
score: 0
comment on: http://stackoverflow.com/q/50599312
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88157850
score: 0
type: Comment
has text: @hpaulj: you could attempt an answer if you will :)
comment on: http://stackoverflow.com/a/50572805
type: AnswerComment

http://stackoverflow.com/comment/88418879
type: AnswerComment
type: Comment
has text: I have marked it as solved. One last thing if you could drop some knowledge - how does k = matches[0] work? i see that its different from removing all occurrences in your second code. This has worked exactly as it should.
score: 0
comment on: http://stackoverflow.com/a/50691641

http://stackoverflow.com/comment/88353570
type: QuestionComment
comment on: http://stackoverflow.com/q/50671283
has text: Amazon Product Review ,Coursera Classification Assignment . I even did the same coding as of the helpdesk but still got this error
score: 0
type: Comment

http://stackoverflow.com/comment/88199180
comment on: http://stackoverflow.com/q/50582132
score: 0
type: Comment
type: QuestionComment
has text: yes, I can use cluster slots to see my cluster info

http://stackoverflow.com/comment/106471524
score: 1
comment on: http://stackoverflow.com/a/50668285
type: AnswerComment
has text: @wwii oops. Am I correct in assuming you are on windows?
type: Comment

http://stackoverflow.com/a/50594396
accepted answer of: http://stackoverflow.com/q/50591694
answers question: http://stackoverflow.com/q/50591694
type: AcceptedAnswer
has body: You'll want to use cv2.normalize() to scale the image before displaying. You can set the min/max of the image and it will scale the image appropriately (by moving the min of the image to alpha and max of the image to beta). Supposing your img is already a uint16: img_scaled = cv2.normalize(img, dst=None, alpha=0, beta=65535, norm_type=cv2.NORM_MINMAX) And then you can view as normal. By default, cv2.normalize() will result in an image the same type as your input image, so if you want an unsigned 16-bit result, your input should be uint16. Again, note that this linearly stretches your image range---if your image never actually hit 0 and say the lowest value was 100, after you normalize, that lowest value will be whatever you set alpha to. If you don't want that, as one of the comments suggests, you can simply multiply your image by 16, since it's currently only going up to 4095. With * 16, it will go up to 65535.
type: Answer
score: 11
upvote count: 11
downvote count: 0

http://stackoverflow.com/a/67548565
has body: Creating a directory .venv in the project then try to initiate with pipenv install <some package> did not work for me at the first in my mac, it was always creating virtual environment somewhere else. Though later I figure it out the reason. The hack is, first cd to the project folder cd /Home/.../MyProject then create a empty Pipfile touch Pipfile the create a directory mkdir .venv should work. Now you can run pipenv install and .venv folder will be used. Now the elaboration is given form the source code. When the pipenv try to create create a virtual env it looks to the directory dot_venv = os.path.join(self.project_directory, ".venv") (taken from source code) and thats how the self.project_directory looks like: @property def project_directory(self): # type: () -> str return os.path.abspath(os.path.join(self.pipfile_location, os.pardir)) So that function looks for the pipfile location to create the path it will create the virtual environment. So if you create the empty Pipfile before hand it is confirmed that it will find that file and then find the .venv directory and create the path all together.
type: Answer
answers question: http://stackoverflow.com/q/50598220
upvote count: 0
score: -1
downvote count: 1

http://stackoverflow.com/q/50638315
type: UnansweredQuestion
score: 1
upvote count: 1
tagged with: scipy
has answer: http://stackoverflow.com/a/50638538
type: Question
has body: scipy.minimize does not seem to adhere to constraints. Here is a simple example where the constraint is for preventing a negative argument in the logarithm, but the minimize function does not adhere : import math from scipy.optimize import minimize def obj(x,b): print "obj x",x return math.log(x-b) def constr(x,b): print "constr x",x return x-b x=3.1 b=3 a=minimize(obj,x,args=(b),constraints={'type': 'ineq', 'fun':constr,'args':[b]}) the output is: constr x [ 3.1] obj x [ 3.1] constr x [ 3.1] obj x [ 3.1] obj x [ 3.10000001] constr x [ 3.1] constr x [ 3.10000001] obj x [ 3.] Traceback (most recent call last): File "scipy_minimize_constraints.py", line 19, in a=minimize(obj,x,args=(b),constraints={'type': 'ineq', 'fun':constr,'args':[b]}) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/optimize/_minimize.py", line 495, in minimize constraints, callback=callback, **options) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/optimize/slsqp.py", line 378, in _minimize_slsqp fx = func(x) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/optimize/optimize.py", line 292, in function_wrapper return function(*(wrapper_args + args)) File "scipy_minimize_constraints.py", line 9, in obj return math.log(x-b) ValueError: math domain error python2.7 Scipy version 1.0.0 Am I doing something wrong?
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50641827
has title: scipy.minimize does not seem to adhere to constraints
favorite count: 0
tagged with: python
tagged with: mathematical-optimization

http://stackoverflow.com/q/50644652
linked to: http://stackoverflow.com/q/14693701
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/14693701
tagged with: python
tagged with: regex
has body: I'm trying to remove \x1b(B\x1b[m in a string, but whenever I try using strip("\x1b(B\x1b[m") it doesn't seem to work. Is there a way to ask for that literal string instead of using the expression it is.
has comment: http://stackoverflow.com/comment/88299640
has comment: http://stackoverflow.com/comment/88299689
answer count: 0
type: Question
score: 0
has title: Find a a special ascii in string

http://stackoverflow.com/a/56583204
type: Answer
has body: Made a few modifications based on Gord Thompson's answer. This will auto-calculate the chunksize and keep it to the lowest nearest integer value which fits in the 2100 parameters limit : import math df_num_of_cols=len(df.columns) chunknum=math.floor(2100/df_num_of_cols) df.to_sql('MY_TABLE',con=engine,schema='myschema',chunksize=chunknum,if_exists='append',method='multi',index=False )
upvote count: 2
downvote count: 1
answers question: http://stackoverflow.com/q/50689082
score: 1
has comment: http://stackoverflow.com/comment/110031393

http://stackoverflow.com/q/50616632
has answer: http://stackoverflow.com/a/50617268
answer count: 1
tagged with: postgresql
tagged with: python-2.7
tagged with: sql
has body: I have run a query which inner join two temp table in postgresql using python to find a radio parameter different. Also I have csv file which increased the table name and column name. I use pandas to read the csv and query the postgreqsql several times and insert the result to a cell call comparsion.cccheck_table_cell. This is my code: from ftplib import FTP import os import csv import psycopg2 import time from datetime import datetime, timedelta import pandas as pd today=datetime.strftime(datetime.now(), '%Y-%m-%d') yesterday=datetime.strftime(datetime.now() - timedelta(2), '%Y- %m-%d') i=0 abc=[] conn = psycopg2.connect( host="xxx", database="parameter", user="xxx", password="xxx", port="xxx" ) abc =pd.read_csv( 'xxxx/create_comp/164/cell_table.csv', header=None, index_col=False ) table="insert into comparsion.cccheck_table_cell SELECT a.date as date,a.ne_name as ne_name,a.local_cell_id,'"+abc.iloc[i,1]+"' as parameter,a." + abc.iloc[i,1] + " as today_parameter,\ b." + abc.iloc[i,1] + " as yesterday_parameter FROM (select * from radio_parameter." + abc.iloc[i,0] + " \ where date='" + today + "')a INNER JOIN (select * from radio_parameter." + abc.iloc[i,0] + " where date='" + yesterday + "')b ON a.ne_name = b.ne_name and a.local_cell_id=b.local_cell_id WHERE a." + abc.iloc[i,1] + " != b." + abc.iloc[i,1] + ";" print(table) cursor = conn.cursor() cursor.execute(table) cursor.close() conn.commit() conn.close() print('done_1') For troubleshoot, I have print the query when execute one times. But I find the query no responds and no error found if I inner join two temp table. Is anyone have these experience when execute the query which no respond but no error? Is the problem related to server or database loading problem?(my database is about 24GB)
has comment: http://stackoverflow.com/comment/88243961
tagged with: python
has title: INNER JOIN two temp table no respond in postgresql usibn python
score: 0
type: UnansweredQuestion
type: Question

http://stackoverflow.com/comment/88348523
comment on: http://stackoverflow.com/q/50656643
has text: It fails at: os.system('cd D:\\Program\\Steam\Steam.exe')
score: 0
type: QuestionComment
type: Comment

web-crawler
tags question: http://stackoverflow.com/q/50692065
tags question: http://stackoverflow.com/q/50695027
tags question: http://stackoverflow.com/q/50545113
tag name: web-crawler
type: Tag
tags question: http://stackoverflow.com/q/50602900
tags question: http://stackoverflow.com/q/50613071
tags question: http://stackoverflow.com/q/50636524

http://stackoverflow.com/comment/88307520
score: 0
has text: Please provide more code. There are several things I need to address here. I can almost guarantee your `def GETFTP(self):` is not a good idea and 100% `def FTPSUBMIT(self):` is not doing what you think it is.
comment on: http://stackoverflow.com/q/50648208
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50606261
has body: Given that data is time variable, a line plot suits it the best. Honestly I'd do some pre-elaboration on dataset if I were you, this thing you need can be done very simple; create a Timestamp array separately and some array for each machine. However I don't know how much you are restricted to keep in the data as it is. import matplotlib.pylab as plt import pandas as pd efficiency = [{'weights': '21', 'sets': '5', 'time': '1', 'machine': 'a'}, {'weights': '93', 'sets': '25', 'time': '2', 'machine': 'a'}, {'weights': '53', 'sets': '5', 'time': '1', 'machine': 'b'}, {'weights': '61', 'sets': '25', 'time': '2', 'machine': 'b'}, {'weights': '66', 'sets': '5', 'time': '1', 'machine': 'c'}, {'weights': '90', 'sets': '25', 'time': '2', 'machine': 'c'}, {'weights': '79', 'sets': '5', 'time': '1', 'machine': 'd'}, {'weights': '100', 'sets': '25', 'time': '1', 'machine': 'd'}] class Efficiency: plt.rcParams['figure.figsize'] = (16,6) def __init__(self, data): self.data = data self.machines = [] self.Timestamp = [] for i in data: setattr(self, 'machine_'+i['machine'], dict(efficiency=[])) if not i['machine'] in self.machines: self.machines.append(i['machine']) if not i['time'] in self.Timestamp: self.Timestamp.append(i['time']) def readData(self): for i in self.data: getattr(self, 'machine_' + i['machine'])['efficiency'].append(float(i['weights'])) def plotData(self): eff_dict = {} for i in self.machines: eff_dict['machine ' + i] = getattr(self, 'machine_' + i)['efficiency'] self.df = pd.DataFrame(eff_dict, index= self.Timestamp) self.df.plot() plt.grid() plt.xticks(fontsize=12, rotation=90) plt.tick_params(axis='both', which='major', labelsize=18) plt.legend(fontsize=12) plt.tight_layout() plt.show() print(self.df) test = Efficiency(efficiency) test.readData() test.plotData() this is from your exact code; If data can be defined like the following: import matplotlib.pylab as plt import pandas as pd import numpy as np import datetime efficiency2 = [{'weights': np.random.uniform(…
type: Answer
answers question: http://stackoverflow.com/q/50604349
accepted answer of: http://stackoverflow.com/q/50604349
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88143670
type: QuestionComment
has text: Btw you are using a dictionary and not list.
comment on: http://stackoverflow.com/q/50566728
score: 0
type: Comment

http://stackoverflow.com/a/50605017
score: 0
has body: convert the Date column to timestamp type, if not already done &amp; set it as index df.Date = pd.to_datetime(df.Date) df = df.set_index('Date') group the data using the other dimensions, and for each group, apply a rolling sum on value. DataFrame.rolling can create temporal windows, and defaults to using the index for windowing. specify 62D for the window size as you have done in your attempt. df['RQ'] = df.groupby(list(df.columns[:-1].values)).Value.apply(lambda x: x.rolling('62D').sum()) This outputs (with the sample data): Brand Indication Geo Type Value RQ Date 2016-04-01 1 A National Value 10 10.0 2016-05-01 1 A National Value 20 30.0 2016-06-01 1 A National Value 30 60.0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50601382
accepted answer of: http://stackoverflow.com/q/50601382

http://stackoverflow.com/q/50675135
answer count: 1
tagged with: user-interface
favorite count: 0
tagged with: tkinter
has body: I want to load multiple images from a folder and do something(crop) with each image and after closing i want the next image to be loaded for cropping and so on......but at present my code only loads one image and after working on it closes as it supposed to but the next image doesn't load onto the canvas. I think the problem is in 'load_image' function or the calling to that function. from Tkinter import * from PIL import Image, ImageTk import os array = [] tuplee = () count = 0 d = 0 f = 1 FileDir = "" #Load all files from directory File = os.listdir('frames/') #print(File) if __name__ == "__main__": root = Tk() #setting up a tkinter frame and canvas frame = Frame(root, bd=2, relief = SUNKEN) frame.grid_rowconfigure(0, weight=1) frame.grid_columnconfigure(0, weight=1) canvas = Canvas(frame, bd=1, width=950, height=600) canvas.grid(row=0, column=0, sticky=N+S+E+W) frame.pack(fill=BOTH,expand=1) FileDir = 'C:/Users/cvcrb/Desktop/NumberPlate/frames/' + File[0] img = ImageTk.PhotoImage(Image.open(FileDir)) canvas.create_image(0,0,image=img,anchor="nw") canvas.config(scrollregion=canvas.bbox(ALL)) def load_image(): FileDir = 'C:/Users/cvcrb/Desktop/NumberPlate/frames/' + File[f] img = ImageTk.PhotoImage(Image.open(FileDir)) canvas.create_image(0,0,image=img,anchor="nw") canvas.config(scrollregion=canvas.bbox(ALL)) #root.update_idletasks() #root.after(100,load_image) #function to be called when mouse is clicked def printcoords(event): global count global d global FileDir global f for i in range(1): array.append(event.x) array.append(event.y) tuplee = tuple(array) print (tuplee) count += 1 if count == 2: print ("Cropping...") crop(FileDir, tuplee, 'cropped%d.jpg' % d) d += 1 print ("Cropped") count = 0 canvas.destroy() #canvas closes after 2 clicks load_image() #should load the next image #mouseclick event canvas.bind("&lt;Button 1&gt;",printcoords) #function to crop a certain area using coordinates def crop(image_path, coords, saved_location): image_obj = Image.open(imag…
tagged with: python
type: AnsweredQuestion
tagged with: python-imaging-library
downvote count: 0
score: 1
type: Question
tagged with: canvas
has title: Load multiple images one after another in a canvas with tkinter
has answer: http://stackoverflow.com/a/50691633
accepted answer: http://stackoverflow.com/a/50691633
upvote count: 1

http://stackoverflow.com/q/50543820
has answer: http://stackoverflow.com/a/59602468
linked to: http://stackoverflow.com/q/7498595
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/77080894
type: Question
score: 5
has answer: http://stackoverflow.com/a/50544576
accepted answer: http://stackoverflow.com/a/50544576
has body: I'm using argparse with several subparsers. I want my program to take options for verbosity anywhere in the args, including the subparser. from argparse import ArgumentParser p = ArgumentParser() p.add_argument('--verbose', '-v', action='count') sub = p.add_subparsers() a = sub.add_parser('a') print(p.parse_args()) By default, options for the main parser will throw an error if used for subparsers: $ python tmp.py -v a Namespace(verbose=1) $ python tmp.py a -v usage: tmp.py [-h] [--verbose] {a} ... tmp.py: error: unrecognized arguments: -v I looked into parent parsers, from this answer. from argparse import ArgumentParser parent = ArgumentParser(add_help=False) parent.add_argument('--verbose', '-v', action='count') main = ArgumentParser(parents=[parent]) sub = main.add_subparsers() a = sub.add_parser('a', parents=[parent]) print(main.parse_args()) For some reason though, none of the shared flags work on the main parser. $ python tmp2.py a -vvv Namespace(verbose=3) $ python tmp2.py -vvv a Namespace(verbose=None) Note that the main parser definitely has the appropriate arguments, because when I change it to main = ArgumentParser() I get error: unrecognized arguments: -v. What am I missing here?
has comment: http://stackoverflow.com/comment/88100431
has comment: http://stackoverflow.com/comment/88099964
favorite count: 0
answer count: 3
tagged with: argparse
tagged with: python
has answer: http://stackoverflow.com/a/77080894
tagged with: python-3.x
upvote count: 5
has comment: http://stackoverflow.com/comment/88100284
has title: Argparse: options for subparsers override main if both share parent
has comment: http://stackoverflow.com/comment/88099980

http://stackoverflow.com/comment/88356361
comment on: http://stackoverflow.com/q/50673092
score: 0
type: QuestionComment
has text: @JohnCarter Thank you.
type: Comment

http://stackoverflow.com/a/50615819
score: 1
answers question: http://stackoverflow.com/q/50615643
upvote count: 1
downvote count: 0
type: Answer
has body: let f be a function used to filter the data frame where i is a value from col_1 def f(i): return (df.col_2 == 1) \ &amp; (df.col_1 &lt;= i + 10) \ &amp; (df.col_1 &gt; i) df['col_3'] = df.apply(lambda x: ((df.id==x.id) &amp; f(x.col_1)).any(), axis=1).astype(int) prouduces output: id col_1 col_2 col_3 0 1 1.2 0 0 1 1 7.2 0 1 2 1 12.1 1 1 3 1 15.2 0 1 4 1 16.3 1 0 5 1 21.1 0 0 6 1 22.2 0 0 7 2 3.0 0 1 8 2 5.0 1 0

http://stackoverflow.com/comment/88225309
score: 0
type: AnswerComment
has text: This is indeed faster, but I was hoping to avoid allocating (num_partition x num_samples) temporary storage. Do you think there's a more memory-efficient method that is still faster than the loop, or is the best we can do without API support?
type: Comment
comment on: http://stackoverflow.com/a/50606957

http://stackoverflow.com/a/50586599
has body: Why it does not work The following code you wrote will not work. good = [[1, 2, 3], [2, 3, 1]] good_dups = [] for x in good: x = sorted(x) if good.count(x) &gt; 1: good_dups.append(x) print(good_dups) # [] You are counting how many sorted copy of you list are in good, but if the original sublists are not sorted, list.count will not find them. Solution What you might want to do is use sorted tuples as key to compare the sublists and keep track of them in a dict or a defaultdict. from collections import defaultdict good = [[1, 2, 3], [2, 3, 1], [2, 3, 4]] good_dups = defaultdict(list) for x in good: good_dups[tuple(sorted(x))].append(x) print(dict(good_dups)) # {(1, 2, 3): [[1, 2, 3], [2, 3, 1]], (2, 3, 4): [[2, 3, 4]]} The duplicates are the entries which list has length two or more.
score: 1
accepted answer of: http://stackoverflow.com/q/50586283
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/50586283

http://stackoverflow.com/q/50656196
linked to: http://stackoverflow.com/q/31213086
accepted answer: http://stackoverflow.com/a/50656248
has title: Unsupported operand types for &: 'str' and 'bytes' in python
upvote count: 0
answer count: 1
tagged with: string
score: -6
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88322423
has comment: http://stackoverflow.com/comment/88322394
has comment: http://stackoverflow.com/comment/88322405
tagged with: python
has body: if(msg.topic == "abc" &amp; msg.payload == b'1'): print("Loop entered") TypeEror: unsupported operand types for &amp;: 'str' and 'bytes'
downvote count: 6
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50656248
linked to: http://stackoverflow.com/q/2485466
type: Question
duplicate of: http://stackoverflow.com/q/2485466

http://stackoverflow.com/q/50584057
answer count: 2
has answer: http://stackoverflow.com/a/50584170
has body: After running this code, I got an error: pygame.error: video system not initialized My code: import sys import pygame def run_game(): # Initialize game and create a screen object. pygame.init() screen = pygame.display.set_mode((1200, 800)) pygame.display.set_caption("Alien Invasion") # Start the main loop for the game. while True: # Watch for keyboard and mouse events. for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # Make the most recently drawn screen visible. pygame.display.flip() run_game() Can anyone help me and explain what this error means and how to rectify it?
tagged with: python
tagged with: pygame
favorite count: 0
type: UnansweredQuestion
downvote count: 1
has title: pygame.error: video system not initialized python code error
type: Question
score: 1
has comment: http://stackoverflow.com/comment/88177325
has answer: http://stackoverflow.com/a/50584128
upvote count: 2

http://stackoverflow.com/comment/88346892
type: Comment
comment on: http://stackoverflow.com/a/50668496
has text: Did, No difference @Zimdero
type: AnswerComment
score: 0

http://stackoverflow.com/q/50695027
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
has title: grabbing the content inside the html content using Python
type: Question
has answer: http://stackoverflow.com/a/50703287
has body: The Chinese website here mainly describes the information of one company. Since there are many pages containing similar contents, I decided to learn data crawler in Python. Basic code import requests from bs4 import BeautifulSoup page = requests.get('http://182.148.109.184/enterprise- info!getCompanyInfo.action?companyid=1000356') soup = BeautifulSoup(page.text, 'html.parser') source_content = soup.find(class_='rightSide').find(class_='content register').find(class_='formestyle') The information I want to collect The figure was captured in Chrome inspect element page. Maybe Chinese is not friendly here, I created an example here for better illustration. &lt;th&gt; the variable name &lt;/th&gt; =&gt; For example, "company name", "company location" &lt;td&gt; the target data I want to save &lt;/td&gt; My question Based on my basic code, the source_content contain no information inside . The output file was shown like this: Comparing fig1, 2, we can see that the information of longitude, latitude has gone. How to get those data with Python? Any advice would be appreciated
tagged with: web-crawler
tagged with: python-2.7
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50703287
favorite count: 0
tagged with: beautifulsoup

http://stackoverflow.com/a/50575557
upvote count: 1
has body: Here is code I came up with. It uses a dict to look up the value for each id in df1. Map can then be used to look up the value for each id in df2, creating a series that is then added to df2['value'] to produce the desired result. df1_lookup = dict(df1.set_index('id')['value'].items()) df2['value'] += df2['id'].map(lambda x: df1_lookup.get(x, 0))
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50575247

http://stackoverflow.com/a/50630390
type: Answer
downvote count: 0
upvote count: 55
has comment: http://stackoverflow.com/comment/88270923
has comment: http://stackoverflow.com/comment/137766611
has comment: http://stackoverflow.com/comment/132724130
has comment: http://stackoverflow.com/comment/132696523
accepted answer of: http://stackoverflow.com/q/50630045
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/132685495
has body: You simply need to encode the array in the same format as the image, and then use tobytes() if you want it in the same format. &gt;&gt;&gt; import cv2 &gt;&gt;&gt; with open('image.png', 'rb') as image_file: ... content1 = image_file.read() ... &gt;&gt;&gt; image = cv2.imread('image.png') &gt;&gt;&gt; success, encoded_image = cv2.imencode('.png', image) &gt;&gt;&gt; content2 = encoded_image.tobytes() &gt;&gt;&gt; content1 == content2 True
answers question: http://stackoverflow.com/q/50630045
has comment: http://stackoverflow.com/comment/132709079
has comment: http://stackoverflow.com/comment/88271170
score: 55

http://stackoverflow.com/q/50687376
score: 0
tagged with: pandas
tagged with: datetime
linked to: http://stackoverflow.com/q/37840812
tagged with: python
has title: Iterating through datetime64 columns in pandas dataframe
answer count: 0
type: UnansweredQuestion
has body: I have a dataframe of the ending time and the next starting time for various car rides. These columns represent how long the given car was parked at its parking spot before being driven again. My goal is to create new column(s) in the dataframe that include each hour of the day in which that car was parked. Example of the dataframe is as such: End Time Next start time 0 2018-01-02 11:23:54.591 2018-01-03 08:22:06.408 1 2018-01-03 08:51:57.027 2018-01-04 15:07:54.105 2 2018-01-05 01:08:00.000 2018-01-05 17:58:43.829 3 2018-01-05 18:10:20.337 2018-01-05 19:02:00.906 4 2018-01-05 19:12:06.385 2018-01-05 19:41:21.319 I have already run code to find the difference in the two columns in hours: df['time_parked'] = df['Next start time'] - df['End Time'] df['time_parked'] = df['time_parked'] / np.timedelta(1, 'h') The question now is how do I calculate which day of the week and hour of the day these cars were parked? The ideal end output would be new columns for each day of the week, and another set of columns ranging from 0-23 representing the hour of the day, and for each observation a 0 or 1 in the day of the week column and hour of the day columns representing if that car was parked at that given time or not. Does anyone know the best way to do this in python?
duplicate of: http://stackoverflow.com/q/37840812
type: Question
has comment: http://stackoverflow.com/comment/88384547
has comment: http://stackoverflow.com/comment/88413122

http://stackoverflow.com/comment/88265830
type: AnswerComment
has text: Thanks so far. That way I gonna figure out the max value, but how to get the companies name?!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50602377

http://stackoverflow.com/q/50602043
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88214051
score: 3
tagged with: conv-neural-network
type: Question
tagged with: numpy
answer count: 1
tagged with: keras
upvote count: 3
has body: I am trying to build an image classifier but im running in to the error as mentioned in the title of this post. Below is the code im working on. How do i convert my numpy array that is of shape (8020,) to the shape as required by the function fit()? I tried to print the input shape: train_img_array.shape[1:] but it gives an empty shape: () import numpy as np img_train.shape img_valid.shape img_train.head(5) img_valid.head(5) (8020, 4) (2006, 4) ID index class data 8030 11596 11596 0 [[[255, 255, 255, 0], [255, 255, 255, 0], [255... 2152 11149 11149 0 [[[255, 255, 255, 0], [255, 255, 255, 0], [255... 550 10015 10015 0 [[[255, 255, 255, 0], [255, 255, 255, 0], [255... 1740 9035 9035 0 [[[255, 255, 255, 0], [255, 255, 255, 0], [255... 9549 8218 8218 1 [[[255, 255, 255, 0], [255, 255, 255, 0], [255... ID index class data 3312 5481 5481 0 [[[255, 255, 255, 0], [255, 255, 255, 0], [255... 9079 10002 10002 0 [[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], ... 6129 11358 11358 0 [[[255, 255, 255, 0], [255, 255, 255, 0], [255... 1147 2613 2613 1 [[[255, 255, 255, 0], [255, 255, 255, 0], [255... 7105 5442 5442 1 [[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], ... img_train.dtypes ID int64 index int64 class int64 data object dtype: object train_img_array = np.array([]) train_id_array = np.array([]) train_lab_array = np.array([]) train_id_array = img_train['ID'].values train_lab_array = img_train['class'].values train_img_array =img_train['data'].values train_img_array.shape train_lab_array.shape train_id_array.shape (8020,) (8020,) (8020,) # Importing the Keras libraries and other packages #matplotlib inline from __future__ import print_function import keras from keras.models import Sequential from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense from keras.layers import Dropout Using Theano backend. WARNING (theano.tensor.blas): Using NumPy C-API based implementation for BLAS functions. classifier = S…
has comment: http://stackoverflow.com/comment/88213636
has comment: http://stackoverflow.com/comment/88213899
has comment: http://stackoverflow.com/comment/88214153
has comment: http://stackoverflow.com/comment/88213689
favorite count: 0
has title: ValueError: Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (8020, 1)
downvote count: 0
has answer: http://stackoverflow.com/a/50603089
has comment: http://stackoverflow.com/comment/88213868

http://stackoverflow.com/comment/88211045
score: 2
has text: @Chris_Rands Only when you run through one of the new iterators. For example, if you use `a, b, c = tee(itr, 3)` then if you do `i = next(a); del i` you will have `i` stored in memory until **both** `next(b)` and `next(c)` are executed. Worst case scenario, if you do `la = list(a)` then you will have `len(la)` elements in memory until both `b` and `c` are iterated forward.
comment on: http://stackoverflow.com/q/50599850
type: Comment
type: QuestionComment

http://stackoverflow.com/a/55607308
type: Answer
has body: There are several issues that I will explain them one by one, also I have added the correct code for your example. staged_predict(X) method shall NOT be used As staged_predict(X) outputs the predicted class instead of predicted probabilities, it is not correct to use that. One can (where the context accept) use staged_decision_function(X) method and pass the computed decisions at each stage to the model.loss_ attribute. But in this example, it does not work (the loss based on staged decision increases while the loss decreases). You should use staged_predict_proba(X) with cross entropy loss you should use staged_predict_proba(X) you also need to define a function that calculate the cross entropy loss at each stage. I have provided the code below. Note that I set the verbosity to 2, and then you can see that the sklearn training loss at each stage is the same as our loss (as a sanity check that our approach works correctly). Why you have big jumps I think the reason is that GBC becomes very confident and then predict a label is 1 (as an example) with probability one, while it is not correct (for example the label is 2). This creates big jumps (as cross entropy goes to infinity). In such a scenario you should change your GBC parameters. The code and the Plot are given below The code is: import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import fetch_covtype from sklearn.model_selection import train_test_split from sklearn.ensemble import GradientBoostingClassifier def _cross_entropy_like_loss(model, input_data, targets, num_estimators): loss = np.zeros((num_estimators, 1)) for index, predict in enumerate(model.staged_predict_proba(input_data)): loss[index, :] = -np.sum(np.log([predict[sample_num, class_num-1] for sample_num, class_num in enumerate(targets)])) print(f'ce loss {index}:{loss[index, :]}') return loss covtype = fetch_covtype() X = covtype.data Y = covtype.target n_estimators = 10 X_train, X_val, Y_train, Y_val = train_test_split(X, Y, …
score: 0
answers question: http://stackoverflow.com/q/50545339

http://stackoverflow.com/comment/88167287
type: AnswerComment
has text: Better do Nx=Len(x), Ny=len(y). Than its dynamic and you will be not supposed to change something if the datafile changes
type: Comment
comment on: http://stackoverflow.com/a/50579079
score: 0

http://stackoverflow.com/comment/88129970
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50559590
type: Comment
has text: @Alex - I agree with you, but I think `df.groupby("id")[cols].transform(fmap)` return `DataFrame`

http://stackoverflow.com/q/50641585
has title: Understanding statsmodels linear regression
has body: I am trying to fit a linear regression model implemented in statsmodels library. I have a doubt regarding the fit() method. Let's say I have data sample of size 15 and I broke it down into 3 parts and fit the model. Does call to each fit() will fit the model properly or will it overwrite previous values. import numpy as np import statsmodels.api as sm # First call X = [377, 295, 457, 495, 9] # independent variable y = [23, 79, 16, 41, 40] # dependent variable X = sm.add_constant(X) ols = sm.OLS(y,X).fit() #print(ols.summary()) # Second call X = [243, 493, 106, 227, 334] y = [3, 5, 1, 62, 92] X = sm.add_constant(X) ols = sm.OLS(y,X).fit() #print(ols.summary()) # Third call X = [412, 332, 429, 96, 336] y = [30, 1, 99, 4, 33] X = sm.add_constant(X) ols = sm.OLS(y,X).fit() #print(ols.summary()) scores = [9, 219, 200, 134, 499] scores = sm.add_constant(scores) print(ols.predict(scores))
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50644360
accepted answer: http://stackoverflow.com/a/50644360
tagged with: python
type: AnsweredQuestion
tagged with: linear-regression
score: 1
upvote count: 1
type: Question
tagged with: statsmodels

noise
tags question: http://stackoverflow.com/q/50683540
type: Tag
tag name: noise

http://stackoverflow.com/q/50597714
has answer: http://stackoverflow.com/a/50600165
score: 2
has comment: http://stackoverflow.com/comment/88243254
has comment: http://stackoverflow.com/comment/88219265
tagged with: awk
has comment: http://stackoverflow.com/comment/88204939
favorite count: 0
has body: Suppose I have a huge text file like below: 19990231 blabla sssssssssssss hhhhhhhhhhhhhh ggggggggggggggg 20090812 blbclg hhhhhhhhhhhhhh ggggggggggggggg hhhhhhhhhhhhhhh 20010221 fgghgg sssssssssssss hhhhhhhhhhhhhhh ggggggggggggggg &lt;etc&gt; How can I randomly remove 100 blocks that start with numeric characters and end with a blank line? Eg: 20090812 blbclg hhhhhhhhhhhhhh ggggggggggggggg hhhhhhhhhhhhhhh &lt;blank line&gt;
has answer: http://stackoverflow.com/a/50605513
tagged with: linux
type: Question
has comment: http://stackoverflow.com/comment/88204599
tagged with: python
has comment: http://stackoverflow.com/comment/88204709
has comment: http://stackoverflow.com/comment/88204794
downvote count: 2
answer count: 3
has answer: http://stackoverflow.com/a/50608505
has title: How to randomly remove 100 blocks from a text file
has comment: http://stackoverflow.com/comment/88205446
has comment: http://stackoverflow.com/comment/88241182
has comment: http://stackoverflow.com/comment/88205268
has comment: http://stackoverflow.com/comment/88204826
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88204823
upvote count: 4

http://stackoverflow.com/a/50651388
answers question: http://stackoverflow.com/q/50651364
type: Answer
accepted answer of: http://stackoverflow.com/q/50651364
downvote count: 0
has comment: http://stackoverflow.com/comment/88313939
score: 3
has body: The difference is not int the type of the object, but in what your code does to it. There is a big difference between these two: self.tricks = trick and: self.tricks.append(trick) The first one self.tricks = trick assigns a value to attribute tricks of self. The second one self.tricks.append(trick) retrieves self.tricks and calls a method on it (which here modifies its values). The problem, in your case, is that there is no tricks defined on self instance, so self.tricks.append gets the tricks attribute of the class and modifies it, but self.tricks = ... creates a new attribute on self instead. The fact that one of them is a string and the other is a list is not really relevant. It would be the same if both were lists. Note that they could not both be strings because strings are immutable and thus have no append method How to fix it? This is wrong: def add_trick(self, trick): self.tricks = trick If tricks is a class attribute, add_trick should be a class method: @classmethod def add_trick(cls, trick): cls.tricks = trick If there are reasons for add_trick to be an instance method, then simply do this: def add_trick(self, trick): DogStr.tricks = trick
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/88202084
comment on: http://stackoverflow.com/q/50596456
score: 1
has text: Can you try using `cart = browser.find_element_by_name('commit')`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50555855
answer count: 2
downvote count: 0
favorite count: 0
tagged with: google-scholar
tagged with: beautifulsoup
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/50555971
type: UnansweredQuestion
has title: Parsing Google Scholar results with Python and BeautifulSoup
score: 6
has body: Given a typical keyword search in Google Scholar (see screenshot), I want to get a dictionary containing the title and url of each publication appearing on the page (eg. results = {'title': 'Cytosolic calcium regulates ion channels in the plasma membrane of Vicia faba guard cells', 'url': 'https://www.nature.com/articles/338427a0'}. To retrieve the results page from Google Scholar, I am using the following code: from urllib import FancyURLopener, quote_plus from bs4 import BeautifulSoup class AppURLOpener(FancyURLopener): version = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36' openurl = AppURLOpener().open query = "Vicia faba" url = 'https://scholar.google.com/scholar?q=' + quote_plus(query) + '&amp;ie=UTF-8&amp;oe=UTF-8&amp;hl=en&amp;btnG=Search' #print url content = openurl(url).read() page = BeautifulSoup(content, 'lxml') print page This code correctly returns the results page, in (very ugly) HTML format. However, I have not been been able to progress beyond this point, as I could not figure out how to use BeautifulSoup (to which I am not too much familiarized) to parse the results page and retrieve the data. Notice that the issue is with the parsing of and extracting of data from the results page, not with Google Scholar itself, since the results page is correctly retrieved by the above code. Could anyone please give a few hints? Thanks in advance!
type: Question
has answer: http://stackoverflow.com/a/67553457

http://stackoverflow.com/a/50695206
score: 1
answers question: http://stackoverflow.com/q/50694011
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50694011
downvote count: 0
has body: To better understanding you can just to debug your send_to_api function. But in short: *args is used to send a non-keyworded variable length argument list to the function def send_to_api(param1, param2, *args): print(param1, param2, args) If you call then your function and pass after param1, param2 any numbers of positional arguments you can access them inside function in args tuple. So in your question example your dict is inside args variable. send_to_api(1,2, {"a":1, "b":2}) ... 1 2 ({'a': 1, 'b': 2},) And you can access it as args[0], so your code might looks like: def send_to_api(user_id, event_type, *args): event_args = {"user_id": user_id, "event_type": event_type, "event_properties": args[0]} But probably its better if you can change signature to smth like that: def send_to_api(user_id, event_type, event_properties, *args): event_args = {"user_id": user_id, "event_type": event_type, "event_properties": event_properties} As for me it much more cleaner ;) If you need to handle any numbers of positional arguments - use *args in function definition, then you can access them in args tuple inside function. If you need to handle any numbers of keyworded arguments - use **kwargs in function definition, then inside function you can access them in kwargs dictionary. so for example: def send_to_api(arg1, *args, **kwargs): print(arg1, args, kwargs) you can then call function with: send_to_api(1, 2 , key1=1, key2=2) it will print: 1 (2,) {'key1': 1, 'key2': 2} so you can see that args is a tuple (2,); kwargs is a dictionary {'key1': 1, 'key2': 2} Also you can pass kwargs to the function as a dictionary with unpack operator: send_to_api(1, 2, **{'key1': 1, 'key2': 2}) it will print the same: 1 (2,) {'a': 1, 'b': 2} So dictionary {'key1': 1, 'key2': 2} was unpacked with ** operator to key1=1, key2=2 keyword arguments and available inside your function in kwargs dict. There no magic, just try to play in python interactive console.
type: Answer
upvote count: 1

http://stackoverflow.com/a/50670142
downvote count: 0
has body: Your setup.py contains the following line: path = pkg_resources.resource_filename('pycda', 'models/tinynet.h5') Based on the traceback I get when trying to install your package, this call makes pkg_resources try to import your package, but your package imports numpy. Because numpy can't be installed unless pip knows it's a dependency, and because it can't know it's a dependency without running setup.py, and because setup.py can't run without first making the above pkg_resources call, we end up in the situation that numpy is required before we can know it's required; hence, an error. The solution is to delete the above line, which should be easy, as the path variable isn't even used!
accepted answer of: http://stackoverflow.com/q/50669306
type: Answer
answers question: http://stackoverflow.com/q/50669306
score: 4
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/q/50598405
has body: Currently I have a working xgboost XGBClassifier Model trained perfectly with good accuracy. I have stored the model state (instance of the model) for new prediction on new python file by loading the state. I am unable to load the labelencoder from the loaded model state to encode the new data. If I am making use of new LabelEncoder() than my all data are encoded to 0 so I want to make use of the trained data labelEncoder value. How I can achieve it? My source code is: from flask import Flask, request from sklearn.externals import joblib app=Flask(__name__) import pandas as pd @app.route('/', methods=['POST']) def hello(): model=joblib.load("Saved_Model.sav") print(model) //model is loaded successfully data=pd.read_json(request.data) print(data) col=data.columns //data also came perfectly encoder=model.__le__ for i in range(0,len(TrainCols)): data[col[i]]=encoder.fit_transform(data[col[i]]) prediction=model.predict(data.values) Please help me to resolve my problem and also how can I get the list of parameters from the Model State?
has comment: http://stackoverflow.com/comment/88208634
downvote count: 0
score: 1
tagged with: scikit-learn
tagged with: xgboost
tagged with: flask
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Use Saved xgboost Sklearn XGBClassifier Model State for prediction of new data
answer count: 0
tagged with: machine-learning
upvote count: 1
type: Question

http://stackoverflow.com/q/50600998
has comment: http://stackoverflow.com/comment/88211537
downvote count: 1
linked to: http://stackoverflow.com/q/7129285
type: Question
has comment: http://stackoverflow.com/comment/88212960
has comment: http://stackoverflow.com/comment/88211884
score: 0
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/88211483
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88211749
has comment: http://stackoverflow.com/comment/88211690
accepted answer: http://stackoverflow.com/a/50601706
tagged with: python
has body: I am trying to get a value from a closure in an other module. When I press the button in the GUI the file dialog creates a string with the path of the file (so this step works). The string should then be accessible in the main.py. This step doesn't work, in the main it's always None. This is what I have in file main.py: import mat_import import GUI filename1 = GUI.gui() print(filename1) This is what I have in the GUI.py from tkinter import * from tkinter import filedialog from PIL import ImageTk, Image import os import math import sys def gui(): mainpage = Tk() def choose_file1(): filename1 = filedialog.askopenfilename() lbl_read_file1_path = Label() lbl_read_file1_path.configure(text = filename1) lbl_read_file1_path.grid(column=1, row=5, sticky="W", columnspan=3) return filename1 def returnfile1(): return choose_file1() button_read_file1 = Button(mainpage, text="Durchsuchen...", command = returnfile1) button_read_file1.config(height = 1, width = 15) button_read_file1.grid(column=0, row=5, sticky="W") mainloop() What do I have to change to "print" the string with the filename from function choose_file1 (defined inside the function gui) in file main.py?
has comment: http://stackoverflow.com/comment/88211239
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1261875
tagged with: tkinter
has comment: http://stackoverflow.com/comment/88211409
has comment: http://stackoverflow.com/comment/88211244
has title: Return value from closure and use it in an other module
has answer: http://stackoverflow.com/a/50601706

http://stackoverflow.com/q/50562688
accepted answer: http://stackoverflow.com/a/50562779
has comment: http://stackoverflow.com/comment/88135836
has answer: http://stackoverflow.com/a/50562779
has answer: http://stackoverflow.com/a/50562759
tagged with: python
has comment: http://stackoverflow.com/comment/88135849
tagged with: dictionary
has body: I am creating a sort of a database and I need to change a key in a dictionary. {'lastExecution': '1-1-1970', 'wachtwoord': 'wachtwoord', 'name': {'laatsteUpdate': '1-1-1970', 'puntenAantal': '0'}} How can I change the key that is now called name and still keep the data assigned to it? PS, I am using python(3.7.0b4)
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50562760
type: Question
has comment: http://stackoverflow.com/comment/88135891
tagged with: database
possible better answer: http://stackoverflow.com/a/50562759
duplicate of: http://stackoverflow.com/q/16475384
has title: Python dictionary key change
score: 0
answer count: 3
linked to: http://stackoverflow.com/q/16475384

http://stackoverflow.com/q/50606929
tagged with: headless
has title: How to initiate Chrome Canary in headless mode through Selenium and Python
has answer: http://stackoverflow.com/a/50608556
accepted answer: http://stackoverflow.com/a/50608556
has answer: http://stackoverflow.com/a/50607514
answer count: 2
has comment: http://stackoverflow.com/comment/88224556
downvote count: 0
tagged with: chrome-canary
favorite count: 0
has comment: http://stackoverflow.com/comment/88223456
tagged with: python
type: AnsweredQuestion
tagged with: selenium-chromedriver
possible better answer: http://stackoverflow.com/a/50607514
score: 1
has comment: http://stackoverflow.com/comment/88223936
has body: from selenium import webdriver options = webdriver.ChromeOptions() options.binary_location = 'C:\Users\mpmccurdy\Desktop\Google Chrome Canary.lnk' options.add_argument('headless') options.add_argument('window-size=1200x600') driver = webdriver.Chrome(chrome_options=options) driver.get("https://www.python.org")
tagged with: selenium
upvote count: 1
type: Question

http://stackoverflow.com/comment/88312818
type: Comment
has text: Thank you. That helps! What if I want to check the entire alist for the "boy" not just the sublist[0]? Please advise.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50634316

http://stackoverflow.com/a/50604002
downvote count: 0
has body: Without having tried it myself: you need to change cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=prediction,logits=y) ) to cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction) ) The TF documentation states: "Backpropagation will happen only into logits. To calculate a cross entropy loss that allows backpropagation into both logits and labels, see tf.nn.softmax_cross_entropy_with_logits_v2."
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50601927
score: 1

http://stackoverflow.com/a/50645097
answers question: http://stackoverflow.com/q/50645034
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50645034
type: AcceptedAnswer
type: Answer
score: 3
downvote count: 0
has body: You can create a dictionary from the string's contents with re: import re s = 'DATE: 7/25/2017 DATE OPENED: 7/25/2017 RETURN DATE: 7/26/2017 NUMBER: 201707250008754 RATE: 10.00' results = re.findall('[a-zA-Z\s]+(?=:)|[\d/\.]+', s) d = dict([re.sub('^\s+', '', results[i]), results[i+1]] for i in range(0, len(results), 2)) for i in ['DATE', 'RETURN DATE', 'NUMBER']: print(d[i]) Output: 7/25/2017 7/26/2017 201707250008754

http://stackoverflow.com/comment/88316017
type: Comment
comment on: http://stackoverflow.com/a/50652620
score: 0
type: AnswerComment
has text: @Geek here's a [sample implementation](https://stackoverflow.com/questions/4159331/python-speed-up-an-a-star-pathfinding-algorithm) of A* in Python. I'd prefer A* here since you have a pretty clear metric function (in general reducing the number of overlapping numbers per step will be better)

http://stackoverflow.com/q/50601585
has answer: http://stackoverflow.com/a/50601681
type: AnsweredQuestion
score: 3
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/50601812
has title: Multiple conditions np.extract
has answer: http://stackoverflow.com/a/50601812
type: Question
has comment: http://stackoverflow.com/comment/88212345
tagged with: python
accepted answer: http://stackoverflow.com/a/50601681
linked to: http://stackoverflow.com/q/22646463
upvote count: 3
answer count: 2
has body: I have an array and want ot extract all entries which are in a specific range x = np.array([1,2,3,4]) condition = x&lt;=4 and x&gt;1 x_sel = np.extract(condition,x) But this does not work. I'm getting ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() If I'm doing the same without the and and checking for example only one condition x = np.array([1,2,3,4]) condition = x&lt;=4 x_sel = np.extract(condition,x) everything works... Of courese I could just apply the procedure twice with one condition, but isn't there a solution to do this in one line? Many thanks in advance
tagged with: numpy

recurrent-neural-network
tags question: http://stackoverflow.com/q/50608080
tags question: http://stackoverflow.com/q/50626224
tags question: http://stackoverflow.com/q/50631867
tags question: http://stackoverflow.com/q/50623737
tags question: http://stackoverflow.com/q/50635729
tags question: http://stackoverflow.com/q/50615323
tags question: http://stackoverflow.com/q/50612686
type: Tag
tags question: http://stackoverflow.com/q/50626630
tags question: http://stackoverflow.com/q/50609697
tags question: http://stackoverflow.com/q/50600624
tags question: http://stackoverflow.com/q/50644981
tag name: recurrent-neural-network

http://stackoverflow.com/comment/90584079
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50674733
has text: @Raj Great,you could mark answer for others' reference.Thank you!

http://stackoverflow.com/q/50629892
has title: How to not write a line if it is of differing length in Python
type: AnsweredQuestion
has body: I'm trying to combine CSV files and there is some evidence of corruption that I would like to remove. some of the lines are not the same length as the others and if that is the case I do not want to write them to the master file. This is the code I am using to accomplish that for line in rest: if len(line.split(",")) == good_line_length or line == "\n": processed_file_write.write(line) else: pass Where good line length is the len(csv_header.split(",")) I am trying this and it spits out a newline instead of passing over the line and not writing anything. If i replace the pass with processed_file_write.write("DUMMY") then it writes "DUMMY" instead of the newline. I don't know how to make python just skip writing the line.
tagged with: file
type: Question
accepted answer: http://stackoverflow.com/a/50684602
has comment: http://stackoverflow.com/comment/88269871
has comment: http://stackoverflow.com/comment/88269905
score: 0
has comment: http://stackoverflow.com/comment/88270059
has comment: http://stackoverflow.com/comment/88270038
answer count: 1
has comment: http://stackoverflow.com/comment/88270144
tagged with: http://stackoverflow.com/tag/csv
tagged with: io
has answer: http://stackoverflow.com/a/50684602
tagged with: python

http://stackoverflow.com/comment/88568666
type: AnswerComment
comment on: http://stackoverflow.com/a/50638192
type: Comment
has text: @TJE - Hard question, For me help code a lot and answering in StackOveflow. Also I think in docs are nice tutorials, especially [modern-pandas](http://pandas.pydata.org/pandas-docs/stable/tutorials.html#modern-pandas)
score: 1

http://stackoverflow.com/comment/88138858
has text: I see it but it isn't helping much.
type: QuestionComment
comment on: http://stackoverflow.com/q/50563370
score: 0
type: Comment

http://stackoverflow.com/a/50609771
accepted answer of: http://stackoverflow.com/q/50609551
has body: Using diff with cumsum create subgruop within each employee_id, then we do groupby size with max to find the max s=df.groupby('employee_id').time_off_date.apply(lambda x : x.diff().dt.days.ne(1).cumsum()) df['New']=s df.groupby(['employee_id','New']).size().max(level=0) Out[423]: employee_id 1 3 2 4 dtype: int64
score: 5
type: AcceptedAnswer
downvote count: 0
upvote count: 5
has comment: http://stackoverflow.com/comment/88229440
type: Answer
answers question: http://stackoverflow.com/q/50609551
has comment: http://stackoverflow.com/comment/88230295

http://stackoverflow.com/q/50592182
tagged with: python
type: UnansweredQuestion
tagged with: python-requests
has comment: http://stackoverflow.com/comment/88193736
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/50609246
has answer: http://stackoverflow.com/a/50592282
has title: API not accepting my JSON data from Python
has comment: http://stackoverflow.com/comment/88193787
type: Question
score: 0
answer count: 2
has body: I'm new to Python and dealing with JSON. I'm trying to grab an array of strings from my database and give them to an API. I don't know why I'm getting the missing data error. Can you guys take a look? ########################################### rpt_cursor = rpt_conn.cursor() sql="""SELECT `ContactID` AS 'ContactId' FROM `BWG_reports`.`bounce_log_dummy`;""" rpt_cursor.execute(sql) row_headers=[x[0] for x in rpt_cursor.description] #this will extract row headers row_values= rpt_cursor.fetchall() json_data=[] for result in row_values: json_data.append(dict(zip(row_headers,result))) results_to_load = json.dumps(json_data) print(results_to_load) # Prints: [{"ContactId": 9}, {"ContactId": 274556}] headers = { 'Content-Type': 'application/json', 'Accept': 'application/json', } targetlist = '302' # This is for their PUT to "add multiple contacts to lists". api_request_url = 'https://api2.xyz.com/api/list/' + str(targetlist) +'/contactid/Api_Key/' + bwg_apikey print(api_request_url) #Prints https://api2.xyz.com/api/list/302/contactid/Api_Key/##### response = requests.put(api_request_url, headers=headers, data=results_to_load) print(response) #Prints &lt;Response [200]&gt; print(response.content) #Prints b'{"status":"error","Message":"ContactId is Required."}' rpt_conn.commit() rpt_cursor.close() ########################################################### Edit for Clarity: I'm passing it this [{"ContactId": 9}, {"ContactId": 274556}] and I'm getting this response body b'{"status":"error","Message":"ContactId is Required."}' The API doc gives this as the from to follow for the request body. [ { "ContactId": "string" } ] When I manually put this data in there test thing I get what I want. [ { "ContactId": "9" }, { "ContactId": "274556" } ] Maybe there is something wrong with json.dumps vs json.load? Am I not creating a dict, but rather a string that looks like a dict? EDIT I FIGURED IT OUT!: This was dumb. I needed to define results_to_load = [] as a dict before I loaded it at …
has comment: http://stackoverflow.com/comment/88194839
has comment: http://stackoverflow.com/comment/88194119

http://stackoverflow.com/q/50615191
tagged with: python
tagged with: dictionary
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/50615251
accepted answer: http://stackoverflow.com/a/50615251
type: Question
has comment: http://stackoverflow.com/comment/88241024
score: 0
has body: I have a data sets in a xml format and would like to store this in a Python dictionary/List and how I can iterate back. Please note the url tags will vary based on application. Much appreciated Head 20 ur1-l ::: url-n
has title: Best idea to create this XML structure in python Dictionary
has comment: http://stackoverflow.com/comment/88240385
answer count: 1
has comment: http://stackoverflow.com/comment/88240303

http://stackoverflow.com/q/50634189
tagged with: sorting
tagged with: ubuntu
has title: sort numerically then alphnumerically on the same column
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/50634782
tagged with: shell
has answer: http://stackoverflow.com/a/50634834
has comment: http://stackoverflow.com/comment/88278550
has comment: http://stackoverflow.com/comment/88278977
tagged with: python
has body: I have very large data which I want to sort on column 1: numerically and then alphanumerically then on column 2: numerically. So, my final output would be something like this: 1 11 1 13 1 15 2 3 2 5 chr2 6 chr2 15 chr15 3 chr15 9 I am using sort on unix. But, I either keep getting chr2 on the top or on the bottom with any sort I try. Here are some of the sort I tried: which fail to give me the desired output: sort -V -k1,1n -k2n final_merged.txt &gt; merged-sort.txt sort -k1,1n -k2n final_merged.txt &gt; merged-sort.txt sort -k1,1h -k2n final_merged.txt &gt; merged-sort.txt sort -k1,1 -k2n final_merged.txt &gt; merged-sort.txt Post edit: Any way to fix this issue without overloading the memory while using sort or other unix utilities python Thanks,
has comment: http://stackoverflow.com/comment/88278840
tagged with: unix
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50634782
linked to: http://stackoverflow.com/q/19366517
has comment: http://stackoverflow.com/comment/88278498
possible better answer: http://stackoverflow.com/a/50634551
type: Question
has answer: http://stackoverflow.com/a/50634551

http://stackoverflow.com/q/50546339
tagged with: git-bash
has body: I'm using Anaconda for my virtualenvs in win 10. I'm using git-bash .I've been reading about pipenv recently and decided to give it a try. I installed pipenv on my base conda python which is a version of python 2.7 using : pip install pipenv I can easily create a python environment using conda create --name py3 python=3.6 but I tried: $ pipenv install --three which gave: Warning: Python 3 was not found on your system… You can specify specific versions of Python with: $ pipenv --python path\to\python ....\miniconda2\lib\site-packages\pipenv\_compat.py:86: ResourceWarning: Implicitly cleaning up &lt;TemporaryDirectory 'c:\\users\\......\\appdata\\local\\temp\\pipenv-4_fzvq-requi rements'&gt; warnings.warn(warn_message, ResourceWarning) Is it possible to use the 2 packages together?
tagged with: anaconda
has comment: http://stackoverflow.com/comment/88103544
has comment: http://stackoverflow.com/comment/88103385
score: 40
has title: Pipenv with Conda?
type: Question
upvote count: 40
tagged with: pipenv
downvote count: 0
answer count: 3
has answer: http://stackoverflow.com/a/51002659
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/69872518
has answer: http://stackoverflow.com/a/57128480
tagged with: python

http://stackoverflow.com/comment/88329724
type: AnswerComment
has text: it didn't give me any error when i tried. The file was not a valid jpeg file. Now looking at your example i think i did something wrong on the decoding part. I will try again and come back with more info.
comment on: http://stackoverflow.com/a/50659763
type: Comment
score: 0

http://stackoverflow.com/q/50566293
type: Question
has title: Include more columns with get_dummies()
score: 1
answer count: 2
tagged with: pandas
downvote count: 0
has body: I have the following lists: vocab = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] list1 = ['a', 'b', 'c', 'd', 'e'] list2 = ['f', 'g', 'h', 'i', 'j'] With the following code, I would like to get an encoding that creates a one-hot-encoding for list 1, but includes all the items from vocab. import pandas as pd encoding1 = pd.get_dummies(data= list1, columns= vocab) encoding2 = pd.get_dummies(data= list2, columns= vocab) I want the output: encoding1 = a b c d e f g h i j 1 1 0 0 0 0 0 0 0 0 0 2 0 1 0 0 0 0 0 0 0 0 3 0 0 1 0 0 0 0 0 0 0 4 0 0 0 1 0 0 0 0 0 0 5 0 0 0 0 1 0 0 0 0 0 encoding2 = a b c d e f g h i j 1 0 0 0 0 0 1 0 0 0 0 2 0 0 0 0 0 0 1 0 0 0 3 0 0 0 0 0 0 0 1 0 0 4 0 0 0 0 0 0 0 0 1 0 5 0 0 0 0 0 0 0 0 0 1 However, I get the output: encoding1 = a b c d e 1 1 0 0 0 0 2 0 1 0 0 0 3 0 0 1 0 0 4 0 0 0 1 0 5 0 0 0 0 1 encoding2 = f g h i j 1 1 0 0 0 0 2 0 1 0 0 0 3 0 0 1 0 0 4 0 0 0 1 0 5 0 0 0 0 1 What can I do to get the desired output?
favorite count: 0
linked to: http://stackoverflow.com/q/37425961
tagged with: one-hot-encoding
has answer: http://stackoverflow.com/a/50566675
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50567429
has comment: http://stackoverflow.com/comment/88142844
upvote count: 1

http://stackoverflow.com/comment/88380932
type: AnswerComment
score: 0
has text: Oh, someone beat me to it.
type: Comment
comment on: http://stackoverflow.com/a/50685614

http://stackoverflow.com/comment/88323386
type: AnswerComment
score: 0
type: Comment
has text: Thank you. I will try to understand how this code works. If I do not understand any part of the code, can I later knock you?
comment on: http://stackoverflow.com/a/50656638

http://stackoverflow.com/comment/88162385
comment on: http://stackoverflow.com/a/50576003
has text: I tried installing the 4.5.3 version with pip but it keep saying that that it's an invalid requirement ...
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88322468
type: QuestionComment
has text: You shouldn't remove items from a list while iterating it. Instead, build a new list with the items you want to keep.
comment on: http://stackoverflow.com/q/50656257
score: 1
type: Comment

http://stackoverflow.com/comment/88296329
comment on: http://stackoverflow.com/a/50625194
type: Comment
has text: yes, the initial seeding is just arbitrary guesses. An optimization (gradient decent or otherwise) function will repeatedly call the cross section area function while making small changes to that test vectors orientation. The easiest numerical way to do gradient decent is to just rotate a little one way, if it gets better, do it again, if it gets worse, rotate half in other direction. keep doing that until u are below a min step size (then do the other axis). There are a lot of better styles of this tho
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88168040
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50579236
has text: How is that supposed to be a countdown timer? It counts up! BTW, [`time.time`](https://stackoverflow.com/questions/41777880/functions-that-help-to-understand-jsondict-structure) is _not_ intended for use as a high precision timing function. See [time.perf_counter](https://docs.python.org/3/library/time.html#time.perf_counter).
score: 0

http://stackoverflow.com/a/50677473
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50677301
type: AcceptedAnswer
downvote count: 0
has body: You can add status as model property: class CatalogStudentsFirstYear(models.Model): catalogFirstYear = models.ForeignKey(CatalogFirstYear) student = models.ForeignKey(Students) grade = models.IntegerField(blank=True, null=True) def __str__(self): return str(self.catalogFirstYear) +' ' + str(self.student) @property def status(self): return self.student.status And add this property to admin's list_display: list_display = ["student", "catalogFirstYear", "grade", "status"]
type: Answer
answers question: http://stackoverflow.com/q/50677301
score: 2

http://stackoverflow.com/q/50685298
tagged with: python
type: AnsweredQuestion
has title: Django - Call command line with arguments from view
has answer: http://stackoverflow.com/a/50685404
type: Question
has comment: http://stackoverflow.com/comment/88380472
tagged with: django-management-command
score: 0
accepted answer: http://stackoverflow.com/a/50685404
answer count: 1
has body: I am trying to call a command that alters a database from a view. Basically, once the view is loaded, a parameter changes. If I run the command from the terminal, it works, but if I try to call it from the view I keep on getting this error. I would believe there is an error in the way I pass the dictionary as the command works fine from the terminal. It may also be because I am trying to update a model which is being shown to the user at the moment, but I have also tried passing a different ID as an argument and it raises the same error. CommandError at /sample/45/ Error: argument num: invalid int value: "{'num': 45}" Request Method: GET Request URL: http://127.0.0.1:8000/sample/45/ Django Version: 2.0 Exception Type: CommandError Exception Value: Error: argument num: invalid int value: "{'num': 45}" Exception Location: /usr/local/lib/python3.6/dist-packages/django/core/management/base.py in error, line 60 Python Executable: /usr/bin/python3 Python Version: 3.6.5 Python Path: ['/home/ander/Desktop/Proyecto/meduloblastoma/Code/MedulloblastomaProject', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages', '/home/ander/Desktop/Proyecto/meduloblastoma/Code/MedulloblastomaProject'] Server time: Mon, 4 Jun 2018 18:35:37 +0200 This is the code I have used. classify.py from django.core.management.base import BaseCommand from rpy2.robjects.packages import importr import rpy2.robjects as ro from sample.models import Sample class Command(BaseCommand): """ Management command to run the classifier """ def add_arguments(self, parser): parser.add_argument('num',type=int) help="Runs the classifier on uploaded samples" def handle(self,*Args,**Options): num=Options['num'] samples=Sample.objects.filter(id=num) print(samples) for sample in samples: if sample.classificator=="Not classified": sample.classificator="Classified" views.py @login_required def detail_sample(request, id): inst…
tagged with: django

http://stackoverflow.com/q/50576247
has body: I am trying to set up a basic e-commerce site using Django Oscar and am having difficulties. The majority of the problem has to do with the absence of examples of how to hook up meaningful (think Paypal, Stripe, Braintree) methods of payment and presence of obscure ones of which I have never heard before. Either way, I am attempting to use django-oscar-paypal and follow its documentation. The Paypal Express part seems to work in that the button shows up and something akin to check out and processing happens. However, if I choose to proceed with checkout in a regular way (with hopes of paying with a card), I am taken to the following page (the message in parentheses is mine) Which is a product of the following template: {% extends "checkout/checkout.html" %} {% load i18n %} {% block title %} {% trans "Payment details" %} | {{ block.super }} {% endblock %} {% block checkout_nav %} {% include 'checkout/nav.html' with step=3 %} {% endblock %} {% block checkout_title %}{% trans "Enter payment details" %}{% endblock %} {% block order_contents %}{% endblock %} {% block shipping_address %}{% endblock %} {% block shipping_method %}{% endblock %} {% block payment_method %}{% endblock %} {% block payment_details %} {% block payment_details_content %} {% trans "(*** Message from ./templates/tshirt-theme/ ***) This page needs implementing within your project. You may want to use one of Oscar's payment gateway libraries:" %} django-oscar-paypal django-oscar-datacash django-oscar-gocardless django-oscar-paymentexpress django-oscar-accounts {% trans "Continue" %} {% endblock payment_details_content %} {% endblock payment_details %} When I click "Continue", I am taken to something resembling a pre-order page on which the Payment Method is empty. When I click "Change" on it, it takes me back to the page on the screenshot. My question is how do I get credit cards to work with this setup? Is there a better way of doing this thing altogether? I am somewhat familiar with Django, but this…
has comment: http://stackoverflow.com/comment/88330732
upvote count: 5
type: Question
has comment: http://stackoverflow.com/comment/88229431
has comment: http://stackoverflow.com/comment/88189058
answer count: 2
score: 5
has comment: http://stackoverflow.com/comment/88273379
has answer: http://stackoverflow.com/a/51305952
has comment: http://stackoverflow.com/comment/88273242
has comment: http://stackoverflow.com/comment/88189008
downvote count: 0
tagged with: django-oscar
tagged with: braintree
has answer: http://stackoverflow.com/a/58976680
has title: Processing Payments Via Paypal in Django-Oscar
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/88317137
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88273794
tagged with: django
tagged with: paypal

http://stackoverflow.com/q/50658543
has answer: http://stackoverflow.com/a/50658738
accepted answer: http://stackoverflow.com/a/50658738
linked to: http://stackoverflow.com/q/2216666
has comment: http://stackoverflow.com/comment/88327250
has comment: http://stackoverflow.com/comment/88327322
has comment: http://stackoverflow.com/comment/88327382
tagged with: python
type: AnsweredQuestion
tagged with: linked-list
tagged with: algorithm
score: 1
has title: Linked List: Finding intersection of 2 linked lists by swapping their pointers after reaching the end of one of them
type: Question
has body: This question is about a particular approach on finding the intersection and NOT a general method of doing so. My approach to solving the problem at the beginning was that of kenntym's in his answer to this question. His answer is quoted below. This takes O(M+N) time and O(1) space, where M and N are the total length of the linked lists. Maybe inefficient if the common part is very long (i.e. M,N >> m,n) Traverse the two linked list to find M and N. Get back to the heads, then traverse |M − N| nodes on the longer list. Now walk in lock step and compare the nodes until you found the common ones. I have trouble understanding the 3rd solution of 160. Intersection of Two Linked Lists on Leetcode. The approach is different but I feel it might be similar to the above solution. Could anyone show me how the two could be similar? I still can't see how one gets to the intersection from this. The solution presented there is: Approach #3 (Two Pointers) [Accepted] Maintain two pointers pA and pB initialized at the head of A and B, respectively. Then let them both traverse through the lists, one node at a time. When pA reaches the end of a list, then redirect it to the head of B (yes, B, that's right.); similarly when pB reaches the end of a list, redirect it the head of A. If at any point pA meets pB, then pA/pB is the intersection node. To see why the above trick would work, consider the following two lists: A = {1,3,5,7,9,11} and B = {2,4,9,11}, which are intersected at node '9'. Since B.length (=4) &lt; A.length (=6), pB would reach the end of the merged list first, because pB traverses exactly 2 nodes less than pA does. By redirecting pB to head A, and pA to head B, we now ask pB to travel exactly 2 more nodes than pA would. So in the second iteration, they are guaranteed to reach the intersection node at the same time. If two lists have intersection, then their last nodes must be the same one. So when pA/pB reaches the end of a list, record the last element of A/B respectiv…
upvote count: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88327301
tagged with: data-structures
favorite count: 0

http://stackoverflow.com/comment/88263147
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50622990
has text: @ivan_pozdeev - pip install pandas is the entirety of it. It was fast one day, slow the next (after I decided to pip install a newer version). I install it frequently and it wasn't just a one time issue.

http://stackoverflow.com/comment/88101545
score: 0
type: Comment
type: QuestionComment
has text: I want it to look at a range of options, for example when looking for black it looks for pixels between (0, 0 ,0) and (40, 40, 40). It may be too complicated to do in python im not sure
comment on: http://stackoverflow.com/q/50545192

http://stackoverflow.com/a/50576914
type: Answer
has comment: http://stackoverflow.com/comment/116079263
score: 95
answers question: http://stackoverflow.com/q/50574293
downvote count: 0
upvote count: 95
has comment: http://stackoverflow.com/comment/88184674
has body: I think you are in the wrong folder. You probably did: cd flask_tutorial/flaskr You need to go up to the tutorial folder: cd .. You should flask run in the flask_tutorial folder rather than flask_tutorial/flaskr because you want to import flaskr from that folder, not flaskr/flaskr (which doesn't exist).

http://stackoverflow.com/comment/88261047
has text: Sorry I dont konw how to upgrade my code in this tool
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50625366

http://stackoverflow.com/q/50695255
has title: Not overwriting wrapped text in curses
has body: I am trying to write a simple sockets-based chat application in python, and am making a client with curses. The issue I have is that you may receive messages longer than the window width, and in this case the text wraps like expected, but the next message is written on the next line overwriting the previous one wrapped to that line. Here is the related code: def receive(): global recv_queue raw_data = sock.recv(1024) raw_data = json.loads(raw_data) recv_queue.append(raw_data["TMSG"] + "\n") def mainloop(stdscr): global recv_queue i = 1 stdscr.clear() curses.cbreak() stdscr.keypad(1) stdscr.scrollok(1) curses.noecho() menu_bar = stdscr.derwin(3, curses.COLS, 0, 0) log_win = stdscr.derwin(curses.LINES - 6, curses.COLS, 2, 0) ed_win = stdscr.derwin(0, curses.COLS, curses.LINES - 4, 0) sub_ed_win = ed_win.derwin(2, curses.COLS - 2, 1, 1) box = curses.textpad.Textbox(sub_ed_win, insert_mode=True) while True: log_win.border() ed_win.border() menu_bar.box() menu_bar.refresh() log_win.refresh() ed_win.refresh() sub_ed_win.refresh() t = threading.Thread() t.run = box.edit t.start() receive() try: log_win.addstr(i, 1, recv_queue.pop().encode("utf_8")) i += 1 except: pass wrapper(mainloop) The part where I start a thread for editing box can be ignored, it isn't finished yet.
tagged with: python-curses
favorite count: 0
score: 0
tagged with: python
tagged with: curses
tagged with: python-2.x
answer count: 0
type: UnansweredQuestion
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88401216
has comment: http://stackoverflow.com/comment/88834052
tagged with: python-2.7

http://stackoverflow.com/q/50644435
has title: How to use Klepto package Python
tagged with: klepto
has body: Hellow World! I have a pickle file (containing images in byte form) to open but when I open it with pickle I get this error: Traceback (most recent call last): File "test.py", line 20, in &lt;module&gt; if __name__ == "__main__": main() File "test.py", line 10, in main dump = pickle.load(file) UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128) I was told to use klepto instead. This is my try at it but when I load and try to print the data it prints "None" localdb = dir_archive('E:\localdb', {}, serialized=True, cached=True) print(localdb) d = localdb.load('K_Select all images with a construction vehicle\output.pkl') print(d) and this is the output: dir_archive('localdb', {}, cached=True) None Any advice will be greatly appreciated
tagged with: directory
favorite count: 0
type: Question
upvote count: 2
tagged with: pickle
tagged with: python
tagged with: archive
score: 2
answer count: 0
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/88311888
type: AnswerComment
has text: Also, once the objects are stored in the list, is the only way to see all the objects' info with `[print(vars(i)) for i in users]` or is there a better way?
type: Comment
comment on: http://stackoverflow.com/a/50650177
score: 0

http://stackoverflow.com/q/50663584
answer count: 1
has answer: http://stackoverflow.com/a/50678457
accepted answer: http://stackoverflow.com/a/50678457
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/7299973
type: AnsweredQuestion
has body: I am working on a hard django project and I am stuck again. I have a field in the userprofile which is called troop: class UserProfile(models.Model): scout_username = models.OneToOneField(User, on_delete=models.CASCADE) Group_Choice = Groups.Scout_Groups() troop = models.SlugField(max_length=27, choices=Group_Choice, default='None', blank=False) date_of_birth = models.DateField(default=date.today) def __str__(self): return '%s'% (self.scout_username) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) Then I have a form which fills in data which is sent to my stData model. Within the form the user can choose to add details about another user. Except they can only add details to another user who has the same troop details. forms.py from django import forms from leaders.models import stData from django.contrib.auth.models import User from accounts.models import UserProfileManager, UserProfile st_username_list=[ (None, 'Choose a user'), (user1, 'user1'), (i, 'no progress'), ] class BadgeForm(forms.ModelForm): def set_user(self, user): global st_username_list troop = user.userprofile.troop userprofile = UserProfile.objects.all() selected_st = userprofile.filter(troop=troop) for st in selected_st: username = str(st.st_username) st_username_list.append((username, username)) st_username = forms.ChoiceField(choices=st_username_list) class Meta: model = stData fields = ('st_username', 'Pioneer_Badge', 'Explorer_Badge', 'Adventurer_Badge', 'Proficiency_Badge', 'Other_Badge') Please note In the example above I used a global variable. I understand this is far from desired. I have since removed it thanks to the explanation of the proper way to do the filter (found after the line break). I'm only keeping this for education reasons for others who may find they had similar problems. I pass through the user within my views like this: user = request.user user_form…
tagged with: django-forms
type: Question
has comment: http://stackoverflow.com/comment/88366469
has comment: http://stackoverflow.com/comment/88366331
tagged with: django-models
has title: Filtering Django User Choice Field use for a form
score: 0

http://stackoverflow.com/a/50652515
has comment: http://stackoverflow.com/comment/88316261
type: Answer
has body: They do two different things. I don't think you really wanted a union. You don't want the same result twice if it shows up in both sets. What you want is an or query which is what the bitwise operator gives you. It takes both filters and makes them as if you wrote them as Program.objects.filter(Q(default=True) | Q(id__in=user.programs.values('id')))
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50651920
answers question: http://stackoverflow.com/q/50651920
score: 0

http://stackoverflow.com/comment/88176975
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50583889
has text: I'm not sure where to start though :(

http://stackoverflow.com/q/50652724
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88316211
has body: I'm using Python's concurrent.futures framework. I have used the map() function to launch concurrent tasks as such: def func(i): return i*i list = [1,2,3,4,5] async_executor = concurrent.futures.ThreadPoolExecutor(5) results = async_executor.map(func,list) I am interested only in the first n results and want to stop the executor after the first n threads are finished where n is a number less than the size of the input list. Is there any way to do this in Python? Is there another framework I should look into?
has answer: http://stackoverflow.com/a/50652901
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50652901
has comment: http://stackoverflow.com/comment/88316331
upvote count: 3
has title: Concurrent futures wait for subset of tasks
type: Question
linked to: http://stackoverflow.com/q/42782953
score: 3
tagged with: threadpool
downvote count: 0
answer count: 1
tagged with: asynchronous
tagged with: concurrent.futures

http://stackoverflow.com/comment/88112798
score: 0
has text: That makes sense. Since class members with leading underscore need to be treated as private members, it should not be used outside of the class. Thanks
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50544725

http://stackoverflow.com/a/52218972
downvote count: 0
has body: You can just remove the GroupBy and use agg directly. Like this. from pyspark.sql import functions as F mydf=mydf.filter("booking!=''").agg(F.count("patid"), F.countDistinct("patid"))
type: Answer
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/50689005

pycharm
tags question: http://stackoverflow.com/q/50644283
tags question: http://stackoverflow.com/q/50676733
tags question: http://stackoverflow.com/q/50571282
tags question: http://stackoverflow.com/q/50626663
tags question: http://stackoverflow.com/q/50562192
tags question: http://stackoverflow.com/q/50634751
tags question: http://stackoverflow.com/q/50685086
tags question: http://stackoverflow.com/q/50572392
tags question: http://stackoverflow.com/q/50697256
tags question: http://stackoverflow.com/q/50671746
tag name: pycharm
tags question: http://stackoverflow.com/q/50620954
tags question: http://stackoverflow.com/q/50575254
tags question: http://stackoverflow.com/q/50608443
tags question: http://stackoverflow.com/q/50692522
tags question: http://stackoverflow.com/q/50591619
tags question: http://stackoverflow.com/q/50609744
tags question: http://stackoverflow.com/q/50625882
tags question: http://stackoverflow.com/q/50682144
tags question: http://stackoverflow.com/q/50631306
tags question: http://stackoverflow.com/q/50589461
tags question: http://stackoverflow.com/q/50638692
tags question: http://stackoverflow.com/q/50554184
tags question: http://stackoverflow.com/q/50589295
tags question: http://stackoverflow.com/q/50563382
tags question: http://stackoverflow.com/q/50638802
tags question: http://stackoverflow.com/q/50674381
tags question: http://stackoverflow.com/q/50603665
type: Tag
tags question: http://stackoverflow.com/q/50638138
tags question: http://stackoverflow.com/q/50649827
tags question: http://stackoverflow.com/q/50673782
tags question: http://stackoverflow.com/q/50653270
tags question: http://stackoverflow.com/q/50573718
tags question: http://stackoverflow.com/q/50591546
tags question: http://stackoverflow.com/q/50610084
tags question: http://stackoverflow.com/q/50581883
tags question: http://stackoverflow.com/q/50602569

http://stackoverflow.com/q/50689296
tagged with: python-3.x
tagged with: kivy-language
tagged with: self
tagged with: python
type: AnsweredQuestion
has title: Issue in Kivy accessing text in a text input adding screens and screen manager to the program
has answer: http://stackoverflow.com/a/50689639
type: Question
accepted answer: http://stackoverflow.com/a/50689639
score: 0
answer count: 1
tagged with: kivy
has body: Prior to making it a multiple screen application there were no issues but now that I have made it one I get the error : if self.light_novel_list.adapter.selection: AttributeError: 'NoneType' object has no attribute 'adapter' Whenever I press the delete button while selecting an item in my list object. As I am getting a NoneType error I think that I am referring to the object in the kivy hierarchy incorrectly somehow but I am unsure how. My relevant code is: lightnovel.py: import kivy from urllib.request import Request, urlopen from kivy.uix.screenmanager import ScreenManager, Screen from bs4 import BeautifulSoup from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.properties import ObjectProperty from kivy.uix.listview import ListItemButton from kivy.properties import StringProperty class SavedListButton(ListItemButton): pass class LightNovel(Screen): light_novel_text_input = ObjectProperty() light_novel_list = ObjectProperty() def delete(self): if self.light_novel_list.adapter.selection: selection = self.light_novel_list.adapter.selection[0].text self.light_novel_list.adapter.data.remove(selection) self.light_novel_list._trigger_reset_populate() class Series(Screen): pass class LightNovelApp(App): def build(self): screen_manager = ScreenManager() screen_manager.add_widget(LightNovel(name="screen_one")) screen_manager.add_widget(Series(name="screen_two")) return screen_manager lnApp = LightNovelApp() lnApp.run() lightnovel.kv: #: import main lightnovel #: import ListAdapter kivy.adapters.listadapter.ListAdapter #: import ListItemButton kivy.uix.listview.ListItemButton &lt;LightNovel&gt;: BoxLayout: light_novel_text_input: searchbar light_novel_list: saved orientation: "vertical" id: main BoxLayout: id: secondbar size_hint: 1, .1 Button: id: delete size_hint: .5, 1 text: "Delete" on_press: root.delete() Button: id: goto size_hint: .5, 1 text: "Go to" on_press: root.goto() root.manager.transition.direction = 'left' root.manager.transition.durati…

http://stackoverflow.com/comment/88112228
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50550643
type: QuestionComment
has text: It's unclear what your code is supposed to do and what's not working correctly. Please see the [mcve] article.

http://stackoverflow.com/comment/88356884
score: 0
type: QuestionComment
has text: Did you try `pip install --user scikit-learn`?
type: Comment
comment on: http://stackoverflow.com/q/50673632

http://stackoverflow.com/q/50652211
answer count: 2
has comment: http://stackoverflow.com/comment/127789967
upvote count: 0
has title: How to save data to a file on separate items instead of one long string?
score: -1
tagged with: file-io
has answer: http://stackoverflow.com/a/50652357
favorite count: 0
linked to: http://stackoverflow.com/q/6159900
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50652322
tagged with: python
has comment: http://stackoverflow.com/comment/88315324
downvote count: 1
has comment: http://stackoverflow.com/comment/88316501
linked to: http://stackoverflow.com/q/5429064
type: Question
has comment: http://stackoverflow.com/comment/88315286
has body: I am having trouble simply saving items into a file for later reading. When I save the file, instead of listing the items as single items, it appends the data together as one long string. According to my Google searches, this should not be appending the items. What am I doing wrong? Code: with open('Ped.dta','w+') as p: p.write(str(recnum)) # Add record number to top of file for x in range(recnum): p.write(dte[x]) # Write date p.write(str(stp[x])) # Write Steps number

http://stackoverflow.com/q/50658649
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
has title: Display an image with Tkinter
type: Question
has body: I am trying to use Tkinter to display an image in Python 2.7. Below is an example of a code I tried to use, which displays all images in the folder (from http://code.activestate.com/recipes/521918-pil-and-tkinter-to-display-images/ ): import os, sys import Tkinter import Image, ImageTk def button_click_exit_mainloop (event): event.widget.quit() # this will cause mainloop to unblock. root = Tkinter.Tk() root.bind("&lt;Button&gt;", button_click_exit_mainloop) root.geometry('+%d+%d' % (100,100)) dirlist = os.listdir('.') old_label_image = None for f in dirlist: try: image1 = Image.open(f) root.geometry('%dx%d' % (image1.size[0],image1.size[1])) tkpi = ImageTk.PhotoImage(image1) label_image = Tkinter.Label(root, image=tkpi) label_image.place(x=0,y=0,width=image1.size[0],height=image1.size[1]) root.title(f) if old_label_image is not None: old_label_image.destroy() old_label_image = label_image root.mainloop() # wait until user clicks the window except Exception, e: # This is used to skip anything not an image. # Image.open will generate an exception if it cannot open a file. # Warning, this will hide other errors as well. pass For instance, a cross (top) will lead to the following displayed image in the Tkinter window (bottom): I have tried other codes (including some to display live my webcam), they all lead to the same result: I can see an image, it has the correct dimension, but each column has a constant pixel value (the one of the corresponding column of the first row of the original image).
downvote count: 0
favorite count: 0
tagged with: python-2.7
tagged with: tkinter
answer count: 0

http://stackoverflow.com/comment/88127531
score: 0
type: Comment
type: QuestionComment
has text: That's a different function.
comment on: http://stackoverflow.com/q/50558229

http://stackoverflow.com/comment/88394183
comment on: http://stackoverflow.com/a/50692322
type: AnswerComment
score: 0
type: Comment
has text: "I can provide a new way using set, which gives actually the same" nope.

http://stackoverflow.com/q/50668340
tagged with: python
score: 2
downvote count: 0
tagged with: classification
has title: How do I extract the estimation parameters (theta) from GaussianProcessClassifier
type: Question
has body: # Scale/ Normalize Independent Variables X = StandardScaler().fit_transform(X) #Split data into train an test set at 50% each X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5, random_state=42) gpc= GaussianProcessClassifier(1.0 * RBF(1.0), n_jobs=-1) gpc.fit(X_train,y_train) y_proba=gpc.predict_proba(X_test) #classify as 1 if prediction probablity greater than 15.8% y_pred = [1 if x &gt;= .158 else 0 for x in y_proba[:, 1]] The above code runs as expected. However, in order to explain the model, something like, 'a 1 unit change in Beta1 will result in a .7% improvement in probability of sucess' , I need to be able to see the theta. How do I do this? Thanks for the assist. BTW, this is for a homework assignment
has answer: http://stackoverflow.com/a/50671167
tagged with: gaussian
upvote count: 2
answer count: 2
tagged with: scikit-learn
favorite count: 0
has answer: http://stackoverflow.com/a/50668661
has comment: http://stackoverflow.com/comment/88444557
type: UnansweredQuestion

http://stackoverflow.com/comment/88177331
comment on: http://stackoverflow.com/a/50583418
type: AnswerComment
score: 0
has text: Yes but imagine you want sometimes to train model a with floatx set to 'float32' and sometimes train model b with floatx set to 'float16'. Then you would have to set it every time you start a training to make sure it's set to the right value. In my opinion such a config file is for having a preferred value. But if you want to change it only for one training. You shouldn't change the config file itself, because you can forget to change it back for the next training.
type: Comment

http://stackoverflow.com/a/50576165
has body: Here is a one-liner. df2.loc[:, 'value'] += [df1.set_index('id').loc[i, 'value'] for i in df2.id] print(df2) &gt;&gt;&gt; id value x y z 0 1 202 3 4 6 1 3 404 3 4 6 2 5 606 3 4 6 3 5 626 3 4 6
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50575247
downvote count: 0

http://stackoverflow.com/q/50673346
has comment: http://stackoverflow.com/comment/88356470
has answer: http://stackoverflow.com/a/50673408
has comment: http://stackoverflow.com/comment/88356402
tagged with: dataframe
tagged with: date
has body: Consider two date columns (Pandas dataframe) YYYY - MM - DD df1 = pd.DataFrame(data = {'col1' : ['2017-10-06','2017-11-15','2017-11-05','2018-10-06']}) df2 = pd.DataFrame(data = {'col1' : ['2017-10-06','2017-10-06','2018-12-05','2017-10-17','2019-10-06','2017-12-05','2017-3-30']}) df1: col1 0 2017-10-06 1 2017-11-15 2 2017-11-05 3 2018-10-06 Name: col1, dtype: object df2: col1 0 2017-10-06 1 2017-10-06 2 2018-12-05 3 2017-10-17 4 2019-10-06 5 2017-12-05 6 2017-3-30 Note : This is an imbalanced column Now i should return the count of each date value in df1 that has how many upcoming date count than df2 col1 date columns Output: df1 col1 count upcoming in df2 col1 0 2017-10-06 4 1 2017-11-15 3 2 2017-11-05 2 3 2018-10-06 2
type: Question
score: 0
has comment: http://stackoverflow.com/comment/88356473
has title: compare dates in two different columns of two dataframes and return count of upcoming date
tagged with: pandas
answer count: 1
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/88356438
has comment: http://stackoverflow.com/comment/88356411
type: UnansweredQuestion

http://stackoverflow.com/a/50555815
has comment: http://stackoverflow.com/comment/88122471
downvote count: 0
type: Answer
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/50555726
answers question: http://stackoverflow.com/q/50555726
has body: the main issue is that in takes order into account. In your list of lists, ['l1', 'l2', 'l6', 'm6', 'm8'] != ['l2', 'l1', 'l6', 'm6', 'm8'] So the trick is to apply a sort to the random pick, so you won't get the same group in different orders (read: How to efficiently compare two unordered lists (not sets) in Python?). Also, using in in a list is a performance issue. Better use a set for fast lookup, but in that case, convert your list to tuple (like a list, but immutable thus hashable) to be able to put it in the set. Last trick: your counting is clumsy. Count the elements which start by l by checking if the first letter is l, in a generator comprehension fed to the built-in sum function. import random people=["m1", "m2", "m3","m4", "m5", "m6" , "m7","m8", "l1", "l2", "l3", "l4", "l5", "l6", "l7", "l8", "l9"] combinations=set() for g in range(10000): a = tuple(sorted(random.sample(people, k=5))) b = sum(x[0]=="l" for x in a) if b&gt;=3: combinations.add(a) print (len(combinations))
type: AcceptedAnswer

http://stackoverflow.com/q/50669702
score: 2
type: AnsweredQuestion
tagged with: conv-neural-network
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/50690672
type: Question
has body: I am trying to use the DenseNet architecture to classify x-ray images from https://www.kaggle.com/nih-chest-xrays/data. The model produces a vector of binary labels, where each label indicates the presence or absence of 14 possible pathologies: Atelectasis, Cardiomegaly, Consolidation, Edema, Effusion, Emphysema, Fibrosis, Hernia, Infiltration, Mass, Nodule, Pleural Thickening, Pneumonia, and Pneumothorax. For example, a healthy patient would have a label of [0,0,0,0,0,0,0,0,0,0,0,0,0,0], while a patient with edema and effusion would have a label of [0,0,0,1,1,0,0,0,0,0,0,0,0,0]. I built this model with tensorflow, and since this is a multi-label classification problem, the cost function that I used was tf.reduce_mean(tf.losses.sigmoid_cross_entropy(labels, logits)), which is minimized with the AdamOptimizer. However, when I inspected the sigmoid output, the values are all below 0.5, resulting in tf.round(logits) to produce zeros for every prediction. The actual logits are different for different input, and are non-zero values after 10000 iterations, so I don't think vanishing gradients is the problem. I have two questions: Could this problem be caused by an incorrect implementation of the model? Would I be "cheating" if I reduce the threshold value for the sigmoid function to 0.25 from 0.5 to improve model accuracy? Thanks. Here's the code for the model: def DenseNet(features, labels, mode, params): depth = params["depth"] k = params["growth"] if depth == 121: N = db_121 else: N = db_169 bottleneck_output = 4 * k #before entering the first dense block, a conv operation with 16 output channels #is performed on the input images with tf.variable_scope('input_layer'): #l = tf.reshape(features, [-1, 224, 224, 1]) feature_maps = 2 * k l = layers.conv(features, filter_size = 7, stride = 2, out_chn = feature_maps) l = tf.nn.max_pool(l, padding='SAME', ksize=[1,3,3,1], strides=[1,2,2,1], name='max_pool') # each block is defined as a dense block + transition layer with tf.va…
has comment: http://stackoverflow.com/comment/88382137
has answer: http://stackoverflow.com/a/50690672
upvote count: 3
tagged with: deep-learning
answer count: 1
downvote count: 1
has title: Threshold value for sigmoid nonlinearity for multilabel classification
favorite count: 0
tagged with: classification
has comment: http://stackoverflow.com/comment/88351354
tagged with: python
has comment: http://stackoverflow.com/comment/88391156

http://stackoverflow.com/q/50602100
downvote count: 4
type: AnsweredQuestion
has body: Problem I'd like to perform a groupby on a dataframe, with the resulting dataframe containing a column with its elements being a list of the groupby parameter. Example I have a dataframe ship_cluster with ShipID, latitude, longitude and a column named cluster. In [4]: df = pd.DataFrame({"ShipID": [7, 7, 8, 9], "latitude": [51.872842, 51.872874, 51.872794, 51.872946], "longitude": [5.810379, 5.810729, 5.810754, 5.810548], "cluster": [0, 1, 0, 0]}) print(df) "ShipID" latitude longitude cluster 7 51.872842 5.810379 0 7 51.872874 5.810729 1 8 51.872794 5.810754 0 9 51.872946 5.810548 0 The desired output I wish to have would be: latitude longitude ShipID cluster 0 51.872860 5.810560 [7, 8, 9] 1 51.872874 5.810729 [7] So per cluster, I'd like to see the ShipID in a list. Obviously, I can first do a groupby: ship_cluster"latitude", "longitude", cluster".groupby("cluster").mean() but I do not know the next step, nor a simplified method. Any help?
type: Question
has title: Add a column that contains a list of ID's from another dataframe
tagged with: pandas-groupby
has answer: http://stackoverflow.com/a/50602226
tagged with: pandas
upvote count: 1
accepted answer: http://stackoverflow.com/a/50602226
answer count: 1
favorite count: 0
tagged with: python-3.x
score: -3
tagged with: python

http://stackoverflow.com/comment/88131386
type: AnswerComment
has text: If your batch size is larger than 1, you might have to reshape your tensor to be [-1,28,28,1] instead so that the first axis is the length of your batch size.
type: Comment
comment on: http://stackoverflow.com/a/50550091
score: 0

http://stackoverflow.com/q/50569782
tagged with: machine-learning
has answer: http://stackoverflow.com/a/50569956
has comment: http://stackoverflow.com/comment/88149651
type: UnansweredQuestion
has title: splitting data in to test train data when there is unbalance of data
type: Question
tagged with: python
has body: i have an unbalanced data set which has two categorical values. one has around 500 values of a particular class and other is only one single datapoint with another class.Now i would like to split this data into test train with 80-20 ratio. but since this is unbalanced , i would like to have the second class to be present in both the test and train data. I tried using the test-train-split from sklearn, but it does not give the second class data to be present in both of them. I even tried the stratified shuffle split, but that was also not giving data as i thought. Is there any way we can split the data from a data frame forcing both the test and train datasets to have the single datapoint?. I am new to python so having difficulty figuring it out. the data looks like: a b c d label 1 0 0 1 1 1 1 1 0 1 .......... ........ 1 0 0 1 0. the label has only 1 and 0 but the 0 is only one single observation but the rest of the 500 data points are having label as 1
has answer: http://stackoverflow.com/a/50583288
score: 0
answer count: 2

http://stackoverflow.com/comment/88222617
has text: its a tournament score system so it has to save data and then retrieve it , there will be 5 events and 4 teams which is why u have 4 x 5 bits of data as the data will be saved as the tournament progresses which is why i used combo boxes for the events and then 4 boxes for each team i want it so there is one button that works for each event and saving to set lines allows me to get the correct data back later, data will later be saved and retrieved.
score: 0
comment on: http://stackoverflow.com/q/50603658
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88268123
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50628787
has text: Only `test/` is added to the module search path. You'll need to explicitly add the absolute path to `src` to the python module search path.

http://stackoverflow.com/q/50627686
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50627790
downvote count: 0
has title: Remove fraction from an address in pandas data frame
favorite count: 0
type: Question
upvote count: 2
tagged with: python
tagged with: regex
answer count: 1
has body: I have a dataframe in pandas which I would like to remove fractions from the column with addresses. I can't figure out the correct regress implementation to remove them. The sample addresses look like: 580 1/4 Broadway Street 85 1/4 Grand Street Two things, I'm not sure how to loop through the dataframe to remove the special characters. And two what is the correct regex function and how do I regroup the flags? I came up with "^(.)\d+/\d+\s(.)" and "\1\2" to group the flags together Or is there just a better way to do this?
has answer: http://stackoverflow.com/a/50627790
tagged with: python-2.7
tagged with: pandas
score: 2

http://stackoverflow.com/q/50682466
tagged with: argparse
has answer: http://stackoverflow.com/a/50682807
tagged with: python
type: AnsweredQuestion
has title: python argument parser defines variable name for list type input
type: Question
has comment: http://stackoverflow.com/comment/88375023
has comment: http://stackoverflow.com/comment/88375422
has comment: http://stackoverflow.com/comment/88374614
score: 0
has comment: http://stackoverflow.com/comment/88375183
accepted answer: http://stackoverflow.com/a/50682807
answer count: 1
has comment: http://stackoverflow.com/comment/88375521
has comment: http://stackoverflow.com/comment/88375587
has body: I have an option to read a list of input from users. The list can have a random length. Here is my code: parser.add_argument('-at', '--addTests', metavar=('test_commands'), nargs='+') using 'metavar' is a good way to give names to variables but it does not work good when nargs is not fixed. The result I get from this line is : -at test_command [test_command ...], --addTests test_command [test_command] I hope the result only have "test_command" displays one time.

http://stackoverflow.com/q/50605310
tagged with: bioinformatics
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50605642
has answer: http://stackoverflow.com/a/50605569
tagged with: python
tagged with: biopython
has comment: http://stackoverflow.com/comment/88220528
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/88220358
has comment: http://stackoverflow.com/comment/88220295
has title: Make a list in python from a FASTA text file
has body: I have text file like this small example: &gt;ENST00000491024.1|ENSG00000187583.6|OTTHUMG00000040756.4|OTTHUMT00000097942.2|PLEKHN1-003|PLEKHN1|176 SLESSPDAPDHTSETSHSPLYADPYTPPATSHRRVTDVRGLEEFLSAMQSARGPTPSSPLPSVPVSVPASDPRSCSSGPAGPYLLSKKGALQSRAAQRHRGSAKDGGPQPPDAPQLVSSAREGSPEPWLPLTDGRSPRRSRDPGYDHLWDETLSSSHQKCPQLGGPEASGGLVQWI &gt;ENST00000433179.2|ENSG00000187642.5|OTTHUMG00000040757.3|-|C1orf170-201|C1orf170|696 MPTQDGQLRRPARPPGPRAWMEPRGGGSSQFSSCPGPASSGDQMQRLLQGPAPRPPGEPPGSPKSPGHSTGSQRPPDSPGAPPRSPSRKKRRAVGAKGGGHTGASASAQTGSPLLPAASPETAKLMAKAGQEELGPGPAGAPEPGPRSPVQEDRPGPGLGLSTPVPVTEQGTDQIRTPRRAKLHTVSTTVWEALPDVSRAKSDMAVSTPASEPQPDRDMAVSTPASEPQSDRDMAVSTPASEPQPDTDMAVSTPASEPQPDRDMAVSIPASKPQSDTAVSTPASEPQSSVALSTPISKPQLDTDVAVSTPASKHGLDVALPTAGPVAKLEVASSPPVSEAVPRMTESSGLVSTPVPRADAAGLAWPPTRRAGPDVVEMEAVVSEPSAGAPGCCSGAPALGLTQVPRKKKVRFSVAGPSPNKPGSGQASARPSAPQTATGAHGGPGAWEAVAVGPRPHQPRILKHLPRPPPSAVTRVGPGSSFAVTLPEAYEFFFCDTIEENEEAEAAAAGQDPAGVQWPDMCEFFFPDVGAQRSRRRGSPEPLPRADPVPAPIPGDPVPISIPEVYEHFFFGEDRLEGVLGPAVPLPLQALEPPRSASEGAGPGTPLKPAVVERLHLALRRAGELRGPVPSFAFSQNDMCLVFVAFATWAVRTSDPHTPDAWKTALLANVGTISAIRYFRRQVGQGRRSHSPSPSS &gt;ENST00000341290.2|ENSG00000187642.5|OTTHUMG00000040757.3|OTTHUMT00000097943.2|C1orf170-001|C1orf170|676 MEPRGGGSSQFSSCPGPASSGDQMQRLLQGPAPRPPGEPPGSPKSPGHSTGSQRPPDSPGAPPRSPSRKKRRAVGAKGGGHTGASASAQTGSPLLPAASPETAKLMAKAGQEELGPGPAGAPEPGPRSPVQEDRPGPGLGLSTPVPVTEQGTDQIRTPRRAKLHTVSTTVWEALPDVSRAKSDMAVSTPASEPQPDRDMAVSTPASEPQSDRDMAVSTPASEPQPDTDMAVSTPASEPQPDRDMAVSIPASKPQSDTAVSTPASEPQSSVALSTPISKPQLDTDVAVSTPASKHGLDVALPTAGPVAKLEVASSPPVSEAVPRMTESSGLVSTPVPRADAAGLAWPPTRRAGPDVVEMEAVVSEPSAGAPGCCSGAPALGLTQVPRKKKVRFSVAGPSPNKPGSGQASARPSAPQTATGAHGGPGAWEAVAVGPRPHQPRILKHLPRPPPSAVTRVGPGSSFAVTLPEAYEFFFCDTIEENEEAEAAAAGQDPAGVQWPDMCEFFFPDVGAQRSRRRGSPEPLPRADPVPAPIPGDPVPISIPEVYEHFFFGEDRLEGVLGPAVPLPLQALEPPRSASEGAGPGTPLKPAVVERLHLALRRAGELRGPVPSFAFSQNDMCLVFVAFATWAVRTSDPHTPDAWKTALLANVGTISAIRYFRRQVGQGRRSHSPSPSS &gt;ENST00000428771.2|ENSG00000188290.6|OTTHUMG00000040758.2|OTTHUMT00000097945.2|HES4-002|HES4|247 MAAD…
downvote count: 0
score: 4
favorite count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/88262573
has answer: http://stackoverflow.com/a/50605572
tagged with: fasta

http://stackoverflow.com/comment/88304910
type: Comment
comment on: http://stackoverflow.com/a/50646741
has text: @big11mac, precisely.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89158309
comment on: http://stackoverflow.com/a/50690440
has text: @Rahul before doing the line of code with `fillna(df1_master['col_C'])`, add this line: `df_output.loc[df_output['col_C'].isnull(),'col_A'] = '#' + df_output.loc[df_output['col_C'].isnull(),'col_A']`, should do the job if I understood well :)
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88346748
has text: Thank you very much, this is perfect! I didn't expect there to be such an elegant solution.
comment on: http://stackoverflow.com/a/50589207
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50605628
score: 1
tagged with: matplotlib
has title: I can't plot multi grayscale images
type: Question
tagged with: numpy
answer count: 2
tagged with: subplot
has answer: http://stackoverflow.com/a/67552257
downvote count: 0
possible better answer: http://stackoverflow.com/a/67552257
favorite count: 0
has answer: http://stackoverflow.com/a/50605791
has body: I have a training set with 31367 examples this data is RGB images, I want to convert them from RGB to grayscale and plot it in jupyter notebook. # Convert from RBG to grayscale X_train_gray = np.expand_dims(np.asarray([cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) for img in X_train]), 3) X_train_gray = np.reshape(X_train_gray, (len(X_train_gray), 32, 32)) X_train_gray = np.asarray(X_train_gray)/255 To plot 3 image I do this: figg, axx = plt.subplots(1,3) axx[1,1].imshow(X_train_gray[13]) axx[1,2].imshow(X_train_gray[14]) axx[1,3].imshow(X_train_gray[15]) I got this ERROR: IndexError Traceback (most recent call last) in () ---&gt; 17 axx[1,1].imshow(X_train_gray[14]) IndexError: too many indices for array Note: there's no error if i use plt.imshow(X_train_gray[14]), and it plots the gray image.
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50605791
type: AnsweredQuestion

http://stackoverflow.com/comment/88265998
has text: Sanjay this is pretty confusing to me. Can you clarify a little more?
comment on: http://stackoverflow.com/q/50627605
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/50690130
has body: First of all, all the date_event in your array of objects are all the same, so not much sense in sorting them.. Also your approach will not get you far, you need to convert the dates to native date/time objects so that you can sort them through a sorting function. The easiest way to parse properly formatted Date/Times is to use dateutil.parse.parser, and sorting an existing list is done by list.sort() - I made a quick example on how to use these tools, also i changed the date_event values to showcase it: https://repl.it/repls/BogusSpecificRate After you have decoded the JSON string (json.loads) and have a Python list to work with, you can proceed with sorting the list: # Ascending events.sort(key=lambda e: parser.parse(e['date_event'])) print([":".join([e['title'], e['date_event']]) for e in events]) # Descending events.sort(key=lambda e: parser.parse(e['date_event']), reverse=True) print([":".join([e['title'], e['date_event']]) for e in events])
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/88696527
type: Answer
answers question: http://stackoverflow.com/q/50689991
downvote count: 1

http://stackoverflow.com/comment/88236320
score: 0
has text: Hey Ajax. Exactly! The pages are looking like the following. There's a lot. It's webcrawled with bucky's spider: https://www.cashpoint.dk/en/bets/xtra.html?group=461392&game=312004790, https://www.cashpoint.dk/en/bets/xtra.html?group=461392&game=312004791, https://www.cashpoint.dk/en/bets/xtra.html?group=461392&game=312004792, https://www.cashpoint.dk/en/bets/xtra.html?group=461392&game=312004793, https://www.cashpoint.dk/en/bets/xtra.html?group=461392&game=312004794, https://www.cashpoint.dk/en/bets/xtra.html?group=461392&game=312004795
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50613071

http://stackoverflow.com/comment/88129834
type: AnswerComment
has text: @Alex - Not, you are wrong. You filter `DataFrame`, not `groupby` object
type: Comment
comment on: http://stackoverflow.com/a/50559590
score: 0

http://stackoverflow.com/q/50656478
has body: I am currently following the Holoviews tutorial. Everything in there is done in notebooks, and makes use of the '%' syntax. I've never used notebooks (and don't particularly want to either). How can I write these lines in a normal .py file? Here's an example: %opts Graph [width=400 height=400] I've tried a few things, such as: graph=hv.Graph.opts(width=400, height=400) graph=hv.Graph.opts(width=[400], height=[400]) hv.Graph(width=400, height=400) These all throw errors. How does that % syntax actually work? How are there no commas in that list? I just want to set the width and height of my graph normally. Thanks!
has comment: http://stackoverflow.com/comment/88323052
linked to: http://stackoverflow.com/q/10361206
has comment: http://stackoverflow.com/comment/88323028
has comment: http://stackoverflow.com/comment/88323218
score: 2
has comment: http://stackoverflow.com/comment/88323189
answer count: 1
downvote count: 0
duplicate of: http://stackoverflow.com/q/10361206
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88327108
has comment: http://stackoverflow.com/comment/88323288
tagged with: python
has answer: http://stackoverflow.com/a/50674323
has title: Converting Jupyter Notebook "%" commands to normal python
upvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/88323059
tagged with: ipython
has comment: http://stackoverflow.com/comment/88323123

http://stackoverflow.com/q/50619722
has comment: http://stackoverflow.com/comment/88251094
favorite count: 0
has comment: http://stackoverflow.com/comment/88249158
tagged with: python
tagged with: jupyter
has body: I'm working in an environment where, due to recent developments in auditing requirements, it has become necessary to log all Jupyter Notebook inputs when a user is accessing data, i.e. create an audit trail. The minimum requirement is to log all instances where a user reads, writes or displays data. Currently the audit trail is solid for the database, but stops there as each user can access the database locally and read, write or manipulate the data in a notebook. Standard logging facilities for Python seem suited for logging for the purposes of debugging rather than auditing. IPython does include a logging facility for logging all user input (through, for instance, the magic %logstart), but the user has direct control over the logging and may escape it (%logstop). One option I've explored is the use of JupyterHub, where using an IPython script on start-up would ensure that logging is initiated. However, the user may still stop the logging at any time. Is there a way to prevent this or to otherwise log all Jupyter notebook inputs when accessing data?
answer count: 0
upvote count: 3
type: UnansweredQuestion
has title: How to log Jupyter notebook inputs for auditing purposes?
has comment: http://stackoverflow.com/comment/88251663
downvote count: 1
tagged with: logging
has comment: http://stackoverflow.com/comment/88252636
score: 2
tagged with: audit-trail
has comment: http://stackoverflow.com/comment/88250149
tagged with: ipython
has comment: http://stackoverflow.com/comment/88251530
type: Question
has comment: http://stackoverflow.com/comment/88249269

supervised-learning
type: Tag
tag name: supervised-learning
tags question: http://stackoverflow.com/q/50575580
tags question: http://stackoverflow.com/q/50547709

http://stackoverflow.com/q/50552404
has answer: http://stackoverflow.com/a/56802109
has answer: http://stackoverflow.com/a/52283966
answer count: 17
favorite count: 0
has answer: http://stackoverflow.com/a/53762112
has answer: http://stackoverflow.com/a/56848926
has title: OSError: Initializing from file failed on csv in Pandas
has answer: http://stackoverflow.com/a/73843762
has answer: http://stackoverflow.com/a/55860050
tagged with: python
has answer: http://stackoverflow.com/a/52250992
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/53557425
has comment: http://stackoverflow.com/comment/88115861
has comment: http://stackoverflow.com/comment/88115947
accepted answer: http://stackoverflow.com/a/52283966
tagged with: dataframe
has answer: http://stackoverflow.com/a/60358753
has answer: http://stackoverflow.com/a/61842629
type: Question
possible better answer: http://stackoverflow.com/a/51716314
score: 39
has answer: http://stackoverflow.com/a/51716314
has answer: http://stackoverflow.com/a/56607830
has comment: http://stackoverflow.com/comment/88115594
has answer: http://stackoverflow.com/a/61561659
has answer: http://stackoverflow.com/a/55820452
has body: So far pandas read through all my CSV files without any problem, however now there seems to be a problem.. When doing: df = pd.read_csv(r'path to file', sep=';') I get: OSError Traceback (most recent call last) in () ----> 1 df = pd.read_csv(r'path Übersicht\Input\test\test.csv', sep=';') c:\program files\python36\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, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision) 703 skip_blank_lines=skip_blank_lines) 704 --> 705 return _read(filepath_or_buffer, kwds) 706 707 parser_f.name = name c:\program files\python36\lib\site-packages\pandas\io\parsers.py in _read(filepath_or_buffer, kwds) 443 444 # Create the parser. --> 445 parser = TextFileReader(filepath_or_buffer, **kwds) 446 447 if chunksize or iterator: c:\program files\python36\lib\site-packages\pandas\io\parsers.py in init(self, f, engine, **kwds) 812 self.options['has_index_names'] = kwds['has_index_names'] 813 --> 814 self._make_engine(self.engine) 815 816 def close(self): c:\program files\python36\lib\site-packages\pandas\io\parsers.py in _make_engine(self, engine) 1043 def _make_engine(self, engine='c'): 1044 if engine == 'c': -> 1045 self._engine = CParserWrapper(self.f, **self.options) 1046 else: 1047 if engine == 'python': c:\program files\python36\lib\site-packages\pandas\io\parsers.py in init(self, src, **kwds) 1682 kwds['allow_leading_cols'] = self.index_c…
has answer: http://stackoverflow.com/a/50553426
upvote count: 39
has answer: http://stackoverflow.com/a/58762582
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
downvote count: 0
has answer: http://stackoverflow.com/a/66997911

http://stackoverflow.com/a/50688899
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50688737
upvote count: 1
has body: The url url(r'^parties', PartyNumView), does not parse an argument pk, but it still calls the function PartyNumView. You would have to use a different view function for that specific url, or use a default value: def PartyNumView(request, pk=None, page_number = 1): I suggest you read the python style guide to maybe adjust your code to the standard praxis. For example, function names are usually all lowercase and separated by underscores; your PartyNumView could be renamed to party_num_view for example. Using this style helps other python programmers to understand your code and provide better answers.
score: 1
answers question: http://stackoverflow.com/q/50688737

http://stackoverflow.com/comment/88284598
comment on: http://stackoverflow.com/q/50637311
score: 1
has text: You don't have a `train` key in your `results` dictionary.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88312931
comment on: http://stackoverflow.com/q/50650983
score: 3
type: Comment
type: QuestionComment
has text: What might be a good idea is interspersing calls to different websites (so you contact e.g. Newegg and Bestbuy in two different threads at the same time) as then you avoid scraping any one webservice too intensively. @TemporalWolf I'm exaggerating slightly for comic effect. You are of course right.

gpu
tags question: http://stackoverflow.com/q/50556599
tag name: gpu
tags question: http://stackoverflow.com/q/50669990
tags question: http://stackoverflow.com/q/50648920
tags question: http://stackoverflow.com/q/50627963
tags question: http://stackoverflow.com/q/50587834
type: Tag
tags question: http://stackoverflow.com/q/50613139

http://stackoverflow.com/a/50577582
score: 6
type: AcceptedAnswer
downvote count: 0
has body: Mathematically, there is no difference between these two functions. Both compute the phase or argument of a complex number as: arg = arctan2(zimag, zreal) See documentation for cmath.phase and source code for numpy.angle. From software point of view, as @Julien mentioned in his comment, cmath.phase() will not work on numpy.ndarray.
type: Answer
accepted answer of: http://stackoverflow.com/q/50576732
upvote count: 6
answers question: http://stackoverflow.com/q/50576732

http://stackoverflow.com/q/50679145
tagged with: rabbitmq
score: 4
has comment: http://stackoverflow.com/comment/91395627
has comment: http://stackoverflow.com/comment/88380678
answer count: 5
upvote count: 4
has comment: http://stackoverflow.com/comment/88371825
has answer: http://stackoverflow.com/a/51943277
has answer: http://stackoverflow.com/a/52262564
has answer: http://stackoverflow.com/a/76292667
downvote count: 0
has comment: http://stackoverflow.com/comment/88380613
has title: How to match the routing key with binding pattern for RabbitMQ topic exchange using python regex?
possible better answer: http://stackoverflow.com/a/51943277
type: AnsweredQuestion
tagged with: regex
has comment: http://stackoverflow.com/comment/88380692
favorite count: 0
accepted answer: http://stackoverflow.com/a/52262564
type: Question
has comment: http://stackoverflow.com/comment/88379760
has comment: http://stackoverflow.com/comment/88380793
has answer: http://stackoverflow.com/a/52575862
has answer: http://stackoverflow.com/a/73678742
has body: I am basically working on RabbitMQ. I am writing a python code wherein I am trying to see if the routing key matches with the binding pattern in case of topic exchange. I came across this link- https://www.rabbitmq.com/tutorials/tutorial-five-java.html where it says- "However there are two important special cases for binding keys: * (star) can substitute for exactly one word. # (hash) can substitute for zero or more words. So how do I match the routing key of message with binding pattern of queue? For example routing key of message is "my.routing.key" and the queue is bound to topic exchange with binding pattern - "my.#.*". In general, how do I match these string patterns for topic exchange, preferably I am looking to use python regex.
tagged with: python

http://stackoverflow.com/comment/88382009
type: AnswerComment
comment on: http://stackoverflow.com/a/50686050
has text: I got it (and those case I know what to do). The problem is, imagine the list [1, 3, 2, 5, 4], then there are to maxims, 3 and 5, because 3>1, 3>2, 5>2 and 5>4. So, it is supposed to return [1, 3]. Thanks for your help.
score: 0
type: Comment

http://stackoverflow.com/comment/88517126
type: AnswerComment
comment on: http://stackoverflow.com/a/50702671
type: Comment
has text: I added a feature request - https://ibmwatsondataplatform.ideas.aha.io/ideas/IBMWDP-I-376. Please vote :)
score: 0

api
tags question: http://stackoverflow.com/q/50556752
tags question: http://stackoverflow.com/q/50684868
tags question: http://stackoverflow.com/q/50580600
tags question: http://stackoverflow.com/q/50546451
tags question: http://stackoverflow.com/q/50593871
tags question: http://stackoverflow.com/q/50588813
tags question: http://stackoverflow.com/q/50692101
tags question: http://stackoverflow.com/q/50651772
tags question: http://stackoverflow.com/q/50573857
type: Tag
tags question: http://stackoverflow.com/q/50676008
tags question: http://stackoverflow.com/q/50589034
tags question: http://stackoverflow.com/q/50563235
tag name: api
tags question: http://stackoverflow.com/q/50639797
tags question: http://stackoverflow.com/q/50678020
tags question: http://stackoverflow.com/q/50647042
tags question: http://stackoverflow.com/q/50621832
tags question: http://stackoverflow.com/q/50571638
tags question: http://stackoverflow.com/q/50685112
tags question: http://stackoverflow.com/q/50599276
tags question: http://stackoverflow.com/q/50672127
tags question: http://stackoverflow.com/q/50653345
tags question: http://stackoverflow.com/q/50607089
tags question: http://stackoverflow.com/q/50623935
tags question: http://stackoverflow.com/q/50657788
tags question: http://stackoverflow.com/q/50625319
tags question: http://stackoverflow.com/q/50654337

http://stackoverflow.com/q/50586146
tagged with: pandas
favorite count: 0
has title: Find first non-zero value in each column of pandas DataFrame
possible better answer: http://stackoverflow.com/a/50586307
has answer: http://stackoverflow.com/a/50586307
tagged with: python
score: 19
answer count: 4
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/50586265
accepted answer: http://stackoverflow.com/a/50586265
has answer: http://stackoverflow.com/a/71003727
type: Question
has body: What is a pandoric way to get a value and index of the first non-zero element in each column of a DataFrame (top to bottom)? import pandas as pd df = pd.DataFrame([[0, 0, 0], [0, 10, 0], [4, 0, 0], [1, 2, 3]], columns=['first', 'second', 'third']) print(df.head()) # first second third # 0 0 0 0 # 1 0 10 0 # 2 4 0 0 # 3 1 2 3 What I would like to achieve: # value pos # first 4 2 # second 10 1 # third 1 3
tagged with: dataframe
upvote count: 19
has answer: http://stackoverflow.com/a/50586403

http://stackoverflow.com/a/50574461
has body: Here is an approach using a sparse matrix: def pp(map_, maxitems=2): M = sparse.csr_matrix((map_[:, 1], map_[:, 0], np.arange(map_.shape[0]+1))) M = M.tocsc() sizes = np.diff(M.indptr) ids, = np.where(sizes) D = np.concatenate([M.data, np.zeros((maxitems - 1,), dtype=M.data.dtype)]) D = np.lib.stride_tricks.as_strided(D, (D.size - maxitems + 1, maxitems), 2 * D.strides) result = D[M.indptr[ids]] result[np.arange(maxitems) &gt;= sizes[ids, None]] = 0 return result Timings using @crisz's code but modified to use less repetitive test data. Also I added a bit of "validation": chrisz's and my solutions give the same answer, the other two output a different format, so I couldn't check them. Code: from scipy import sparse import numpy as np from collections import defaultdict, deque def pp(map_, maxitems=2): M = sparse.csr_matrix((map_[:, 1], map_[:, 0], np.arange(map_.shape[0]+1))) M = M.tocsc() sizes = np.diff(M.indptr) ids, = np.where(sizes) D = np.concatenate([M.data, np.zeros((maxitems - 1,), dtype=M.data.dtype)]) D = np.lib.stride_tricks.as_strided(D, (D.size - maxitems + 1, maxitems), 2 * D.strides) result = D[M.indptr[ids]] result[np.arange(maxitems) &gt;= sizes[ids, None]] = 0 return result def chrisz(a): return [[*a[a[:,0]==i,1],0][:2] for i in np.unique(a[:,0])] def piotr(a): d = defaultdict(lambda: deque((0, 0), maxlen=2)) for key, val in a: d[key].append(val) return d def karams(arr): cols = arr.shape[1] ids = arr[:, 0] inds = np.where(np.diff(ids) != 0)[0] + 1 sp = np.split(arr[:,1:], inds) result = [a[:2].ravel() if a.size &gt;= cols else np.pad(a.ravel(), (0, cols -1 * (cols - a.size)), 'constant')for a in sp] return result def make(nid, ntot): return np.c_[np.random.randint(0, nid, (ntot,)), np.random.randint(0, 2**30, (ntot,))] from timeit import timeit import pandas as pd import matplotlib.pyplot as plt res = pd.DataFrame( index=['pp', 'chrisz', 'piotr', 'karams'], columns=[10, 50, 100, 500, 1000, 5000, 10000],# 50000], dtype=float ) for c in res.columns…
upvote count: 2
type: Answer
score: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50573104
answers question: http://stackoverflow.com/q/50573104
downvote count: 0
has comment: http://stackoverflow.com/comment/88158360

http://stackoverflow.com/comment/88412738
has text: @AlexP. you can brief about it as well :)
comment on: http://stackoverflow.com/a/50689645
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88366228
has text: yes @bobrobbob `tuple` is a class but `__init__()` method of `tuple` class will initialize it.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50678082

http://stackoverflow.com/a/50633301
has body: In version 1 you create a list a, pass it in to the function under the pseudonym c, create another pseudonym d for the very same list, and then change the first value in that list. a, c, and d all refer to the same list. In version 2, you're using list(c) which, to Python, means "take the contents of this iterable thing named c and make a new, different, list from it named d". Now, there are two copies of your list floating around. One is referred to as a or c, and the other is d. Therefore, when you update d[0] you're operating a second copy of the list. a remains unchanged.
answers question: http://stackoverflow.com/q/50633189
score: 0
type: Answer

http://stackoverflow.com/comment/88273564
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50631426
has text: I'm voting to close this question as off-topic because you have answered your own question

http://stackoverflow.com/a/50623237
score: 0
has comment: http://stackoverflow.com/comment/88258117
has comment: http://stackoverflow.com/comment/88271092
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88257242
has comment: http://stackoverflow.com/comment/88271489
has body: according to this Link xlOpenXMLWorkbookMacroEnabled is 52. so, while saving just give the argument FileFormat = 52 as shown in the below code class ExcelMacro(unittest.TestCase): def test_excel_macro(self): try: xlApp = win32com.client.DispatchEx('Excel.Application') xlapp.DisplayAlerts=False xlsPath = os.path.expanduser('C:\Magic Samsung\Watch Samsung\Workbook.xlsm') wb = xlApp.Workbooks.Open(Filename=xlsPath) xlApp.Run('ArchiveMaster') wb.SaveAs(Filename=path_here, FileFormat=52) xlApp.Quit() print("Macro ran successfully!") except: print("Error found while running the excel macro!") xlApp.Quit() if __name__ == "__main__": unittest.main() Note: A pop-up appear's while using saveAs. This SO question and This So Post answer's this problem
has comment: http://stackoverflow.com/comment/88275060
type: Answer
has comment: http://stackoverflow.com/comment/88271400
has comment: http://stackoverflow.com/comment/88256941
accepted answer of: http://stackoverflow.com/q/50622888
has comment: http://stackoverflow.com/comment/88259939
has comment: http://stackoverflow.com/comment/88258157
answers question: http://stackoverflow.com/q/50622888
has comment: http://stackoverflow.com/comment/88262321

http://stackoverflow.com/a/70128475
has body: I'm not sure if this existed back when this question was asked, but it's possible today: https://learn.microsoft.com/en-us/windows/wsl/case-sensitivity Python doesn't support it properly, though, since pathlib assumes (now incorrectly) that all Windows paths are case-insensitive.
type: Answer
answers question: http://stackoverflow.com/q/50558784
score: 0

http://stackoverflow.com/q/50591517
has title: How to cat a file in this OS module example
tagged with: python
linked to: http://stackoverflow.com/q/3172470
has answer: http://stackoverflow.com/a/50591642
type: Question
score: 0
answer count: 1
has body: I need to cat a file inside the OS module of python. What I'm trying to do is what I have accomplished in Perl. Please note the cat /tmp/illinois.txt my $cmd = `$ENV{BB} $ENV{BBDISP} "status $host.$test $COLOR \`date\` \`cat /tmp/illinois.txt\`"`; I would like to do the same thing in python. cmd = "{BB} {BBDISP} \"status {NODE}.{TEST} {COLOR} {NOW}\n {MSG}\n\"".format( TEST = "gov-affairs-MemoryUtilization", BB = os.environ["BB"], BBDISP = os.environ["BBDISP"], COLOR = COLOR, NOW = datetime.datetime.now(), MSG=`cat /tmp/illinois.txt\`, NODE="xxxxx")
type: UnansweredQuestion

http://stackoverflow.com/comment/88402928
comment on: http://stackoverflow.com/q/50669030
score: 0
type: Comment
type: QuestionComment
has text: You are messing up the BCM notation with Board notation. You need to be consistent on whether you use BCM numbering or Board numbering. If you are using BCM, it should be 9 for MISO, 10 for MOSI, 11 for SCLK, 8 for CE0, and 9 for CE1. If you are using Board notation, it will be 21 for MISO, 19 for MOSI, 23 for SCLK, 24 for CE0, and 26 for CE1.

http://stackoverflow.com/comment/106735892
type: Comment
has text: I used the exact same code, but I am getting an keyerror on next_page_token
comment on: http://stackoverflow.com/a/50574148
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88437883
type: AnswerComment
type: Comment
has text: Thank you, turns out I had some duplicate data in my reference frame which was causing some funny results, your code really helped.
comment on: http://stackoverflow.com/a/50685537
score: 0

http://stackoverflow.com/comment/88190711
score: 1
has text: What do you mean by "the tuple"? Collecting the lines in an array instead of printing them, and then doing `TEXT = "\r\n".join(array)` is an obvious and straightforward solution.
comment on: http://stackoverflow.com/q/50590578
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88184896
type: QuestionComment
type: Comment
score: 0
has text: It is possible indeed, but really, using a html parser will make your life much easier (and your code much more maintainable).
comment on: http://stackoverflow.com/q/50587223

http://stackoverflow.com/q/50659797
favorite count: 0
tagged with: pyroot
has body: I am trying to read out values from a ROOT file using PyROOT and is stuck with this issue. Any help is appreciated. import ROOT rootFile = "file.root" f = ROOT.TFile(rootFile,'read') tree = f.Get('FCS_ParametrizationInput') leaves = tree.GetListOfLeaves() # define dynamically a python class containing root Leaves objects class PyListOfLeaves(dict) : pass # create an istance pyl = PyListOfLeaves() for i in range(0,leaves.GetEntries() ) : leaf = leaves.At(i) name = leaf.GetName() # add dynamically attribute to my class pyl.__setattr__(name,leaf) if name == 'TruthPz': break nev = tree.GetEntries() for iev in range(0,nev) : tree.GetEntry(iev) # get values from the tree using Python class pyl which contains leaves # objects px = pyl.TruthPx.GetValue() py = pyl.TruthPy.GetValue() pz = pyl.TruthPz.GetValue() print(px) if iev == 10: break I based my code on this link. I think I am following everything as is given in that example. However, instead of it reading out momentum values as it is supposed to, I am getting a constant output of zeros. My tree structure is given as in the figure as shown by TBrowser. Thanks!
answer count: 0
type: UnansweredQuestion
tagged with: python
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90959327
type: Question
upvote count: 2
has title: Reading Values using PyROOT
tagged with: root-framework

http://stackoverflow.com/q/50589727
downvote count: 0
has body: I'm trying to build a tracert with python. I made a loop that runs ttl times to show all the source ip's that the message has passed. I understand that there are some "stations" that doesn't return ttl exceeded, so I need to create a timeout request with the srp, I don't really know what does srp1(msg, timeout = 10) will return to me because I cant see the returned message I got the TTL size to run in the loop, just need to know what do to if timeout passed. for i in range(1,ttl+1): msg = Ether() / IP(dst = domain, ttl = i) / ICMP() ans = srp1(msg, verbose = 0, timeout = 10) print("%d: %s" % (i, ans[IP].src))
tagged with: scapy
has title: Scapy srp1 timeout request
type: Question
type: AnsweredQuestion
score: 1
tagged with: timeout
upvote count: 1
answer count: 1
favorite count: 0
tagged with: single-responsibility-principle
tagged with: python
has answer: http://stackoverflow.com/a/50591757
accepted answer: http://stackoverflow.com/a/50591757

http://stackoverflow.com/comment/88664005
score: 0
has text: One of the reasons (which I care about): Eventually you will have more complicated codes, and you will have function names which exist in multiple packages. For instance, there is `math.sin` which does not support numpy arrays as inputs. So you are setting yourself up for getting confused while debugging later.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50602337

http://stackoverflow.com/a/50644196
answers question: http://stackoverflow.com/q/50644011
has comment: http://stackoverflow.com/comment/88299256
type: Answer
has comment: http://stackoverflow.com/comment/88300341
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/50644011
has body: This is one way: # perform vectorised calculation arr = df.values / df1.loc[:, df.columns.map(db[0].get)].values # feed result into dataframe res = pd.DataFrame(arr, columns=df.columns) print(res) Green Blue Red Yellow 0 0.500000 3.000000 0.333333 1.666667 1 4.000000 3.500000 2.000000 2.500000 2 2.666667 1.333333 4.000000 8.000000
has comment: http://stackoverflow.com/comment/88300588

http://stackoverflow.com/comment/88118482
score: 0
type: AnswerComment
has text: @everestial007 - Super, glad can help! :)
type: Comment
comment on: http://stackoverflow.com/a/50552528

http://stackoverflow.com/comment/88389623
comment on: http://stackoverflow.com/q/50689857
score: 1
type: Comment
has text: You are writing the file as binary, maybe that's messing up the text: `open("exml.txt" , 'wb')`. Try `'w'` instead.
type: QuestionComment

http://stackoverflow.com/comment/88312892
score: 0
has text: You might want to look into the `enumerate()` or `dict.iteritems()` method.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50651015

http://stackoverflow.com/a/65841248
type: Answer
has comment: http://stackoverflow.com/comment/121380623
answers question: http://stackoverflow.com/q/50557234
has body: pip install -U mysql-connector-python this worked for me, if you already have installed mysql-connector-python and then follow https://stackoverflow.com/a/50557297/6202853 this answer
score: 4
upvote count: 4
downvote count: 0

http://stackoverflow.com/q/50590082
accepted answer: http://stackoverflow.com/a/50590187
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88189550
tagged with: math
has comment: http://stackoverflow.com/comment/88189594
type: Question
has answer: http://stackoverflow.com/a/50590187
has body: I have written python code to permute a list of numbers. class Solution: def __init__(self): self.permutations = [] def permute_helper(self, nums, chosen): if nums == []: print chosen self.permutations.append(chosen) else: for num in nums: #choose chosen.append(num) temp = nums[:] temp.remove(num) #explore self.permute_helper(temp, chosen) #un-choose chosen.remove(num) def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ self.permute_helper(nums, []) return self.permutations s = Solution() input = [1,2,3] print s.permute(input) It returns: [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 1, 2] [3, 2, 1] [[], [], [], [], [], []] I want all the permutations to appear in the returned list like this [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 1, 2] [3, 2, 1] [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] I think it has something to do with scoping but I have no idea what I've done wrong to make the list returning nothing.
tagged with: scope
score: 0
has title: Code not returning permutations
answer count: 1
tagged with: permutation

http://stackoverflow.com/q/50567281
has answer: http://stackoverflow.com/a/50567469
answer count: 3
has comment: http://stackoverflow.com/comment/88144697
has comment: http://stackoverflow.com/comment/88148696
duplicate of: http://stackoverflow.com/q/1663807
has comment: http://stackoverflow.com/comment/88144628
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88148847
has body: Hello i have a school exercise that i cant solve, im almost there but something is missing me, so i have 2 .txt files one with student names and other one with students grades they are like: nomesAlunos.txt : Ricardo Filipa Teresa Claúdio nomesNotas.txt : 14 15 14 17 14 14 13 10 13 10 11 i should create a new file where i have the student name followed by student average grades, my code is like: final=open('data/notasFinal.txt','w') nomes=open('data/nomesAlunos.txt') notas=open('data/nomesNotas.txt') for linha in nomes: final.write(linha) for line in notas: lista=line.split() media=(sum((int(numeros) for numeros in lista)))/(len(lista)) final.write(str(media)) nomes.close() notas.close() my final .txt file is like this right now: Ricardo 15.014.011.511.333333333333334Filipa Teresa Claúdio SOLVED: final=open('data/notasFinal.txt','w') nomes=open('data/nomesAlunos.txt') notas=open('data/nomesNotas.txt') media=[] i=0 for linhas in notas: lista=linhas.split() media.append((sum((int(numeros) for numeros in lista)))/(len(lista))) for nome in nomes: alunos=nome.split() final.write(f"{alunos[0]:30}{media[i]}\n") i+=1 nomes.close() notas.close() final.close()
tagged with: python
has title: Reading from two files and writing to one file
score: 0
tagged with: file
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50567409
has answer: http://stackoverflow.com/a/50567594
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1663807

http://stackoverflow.com/comment/88183462
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50552118
type: AnswerComment
has text: C This was the solution I was reffering to in the original post. I solved the problem by splitting the string, but it drives me crazy that I couldn't solve the problem as I expected (with if input == "%d permit" %number and number in range(1,101):, as Attersson posted earlier)

http://stackoverflow.com/comment/122248770
has text: anyone found a solution to this? when I run my code on my computer it goes ok, but when I do that on my prod environment (on AWS) I'm getting this 429
score: 0
comment on: http://stackoverflow.com/q/50571317
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50570511
has answer: http://stackoverflow.com/a/50575550
has answer: http://stackoverflow.com/a/50579611
tagged with: python
tagged with: nlp
linked to: http://stackoverflow.com/q/7591258
type: AnsweredQuestion
has title: Word n-gram list of sentences in python
type: Question
accepted answer: http://stackoverflow.com/a/50575550
tagged with: nltk
downvote count: 0
tagged with: n-gram
answer count: 2
score: 2
favorite count: 0
possible better answer: http://stackoverflow.com/a/50579611
upvote count: 2
has body: I want to generate char-n-grams of sizes 2 to 4. This is what I have by now: from nltk import ngrams sentence = ['i have an apple', 'i like apples so much'] for i in range(len(sentence)): for n in range(2, 4): n_grams = ngrams(sentence[i].split(), n) for grams in n_grams: print(grams) This will give me: ('i', 'have') ('have', 'an') ('an', 'apple') ('i', 'have', 'an') ('have', 'an', 'apple') ('i', 'like') ('like', 'apples') ('apples', 'so') ('so', 'much') ('i', 'like', 'apples') ('like', 'apples', 'so') ('apples', 'so', 'much') How can I do this in an optimal way? I have a very large entry data and my solution contains for in for so the complexity is a bit huge and it takes a lot of time for the algorithm to finish.

http://stackoverflow.com/q/50680621
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50684524
has body: Referring to This example: https://lorensen.github.io/VTKExamples/site/Cxx/Utilities/Animation/ I made a small change in the callback function, to stop it after certain number of timer count. #include &lt;vtkSmartPointer.h&gt; #include &lt;vtkSphereSource.h&gt; #include &lt;vtkPolyData.h&gt; #include &lt;vtkPolyDataMapper.h&gt; #include &lt;vtkActor.h&gt; #include &lt;vtkCommand.h&gt; #include &lt;vtkRenderer.h&gt; #include &lt;vtkRenderWindow.h&gt; #include &lt;vtkRenderWindowInteractor.h&gt; #include &lt;iostream&gt; using namespace std; class vtkTimerCallback2 : public vtkCommand { public: static vtkTimerCallback2 *New() { vtkTimerCallback2 *cb = new vtkTimerCallback2; cb-&gt;TimerCount = 0; return cb; } virtual void Execute(vtkObject *caller, unsigned long eventId, void * vtkNotUsed(callData)) { if (vtkCommand::TimerEvent == eventId) { ++this-&gt;TimerCount; } vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::SafeDownCast(caller); std::cout &lt;&lt; this-&gt;TimerCount &lt;&lt; std::endl; if(TimerCount&lt;20) { actor-&gt;SetPosition(this-&gt;TimerCount, this-&gt;TimerCount,0); iren-&gt;GetRenderWindow()-&gt;Render(); } else { //iren-&gt;DestroyTimer(); //The following will print 1 if timer is destroyed //And 0, if it is not destroyed cout &lt;&lt; "Timer Destroyed: " &lt;&lt;iren-&gt;DestroyTimer() &lt;&lt; endl;; } } private: int TimerCount; public: vtkActor* actor; }; int main(int, char* []) { // Create a sphere vtkSmartPointer&lt;vtkSphereSource&gt; sphereSource = vtkSmartPointer&lt;vtkSphereSource&gt;::New(); sphereSource-&gt;SetCenter(0.0, 0.0, 0.0); sphereSource-&gt;SetRadius(5.0); sphereSource-&gt;Update(); // Create a mapper and actor vtkSmartPointer&lt;vtkPolyDataMapper&gt; mapper = vtkSmartPointer&lt;vtkPolyDataMapper&gt;::New(); mapper-&gt;SetInputConnection(sphereSource-&gt;GetOutputPort()); vtkSmartPointer&lt;vtkActor&gt; actor = vtkSmartPointer&lt;vtkActor&gt;::New(); actor-&gt;SetMapper(mapper); // Create a renderer, render window, and …
type: Question
downvote count: 0
has title: Stopping VTK Timer Callback
tagged with: vtk
upvote count: 1
answer count: 1
favorite count: 0
tagged with: c++
accepted answer: http://stackoverflow.com/a/50684524
tagged with: qvtkwidget

http://stackoverflow.com/comment/88215512
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50602875
type: Comment
has text: @jceg316 - so if check `print(m1)` and `print (m2)` it working correctly? Because it should working.

http://stackoverflow.com/comment/88210561
score: 0
type: Comment
type: QuestionComment
has text: This loop would go on forever would it not? it obviously can't cope with infinite results
comment on: http://stackoverflow.com/q/50600651

http://stackoverflow.com/comment/88166634
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50578649
has text: @Silvia You will need to upgrade your version of pandas for `agg` to work. For now, use `apply(''.join, 1)`,
type: Comment

http://stackoverflow.com/a/50933246
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: The concept of the following could be relevant (tap a heatmap, get a timeseries) http://holoviews.org/reference/streams/bokeh/Tap.html and this one (draw a box, get a timeseries) http://holoviews.org/gallery/demos/bokeh/box_draw_roi_editor.html#bokeh-gallery-box-draw-roi-editor
type: Answer
accepted answer of: http://stackoverflow.com/q/50633040
answers question: http://stackoverflow.com/q/50633040
score: 1

http://stackoverflow.com/comment/88337992
type: QuestionComment
has text: Oh, I pressed ^ + J in pycharm for the method documentation
comment on: http://stackoverflow.com/q/50663920
score: 0
type: Comment

http://stackoverflow.com/a/50582780
accepted answer of: http://stackoverflow.com/q/50576669
has comment: http://stackoverflow.com/comment/88198525
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50576669
has comment: http://stackoverflow.com/comment/88215126
score: 0
type: Answer
has body: I can see that the alert you have received is a VB Script based pop-up and as far as I am aware "alert" in Selenium handles Javascript related pop-ups. In order to handle these kind of .net based alerts you have to either make use of Autoit or Winnium.
has comment: http://stackoverflow.com/comment/88253390
has comment: http://stackoverflow.com/comment/88207520

http://stackoverflow.com/comment/88171586
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50580671
has text: I'd probably also use a `csv.DictReader` so that you 1) don't have to skip headers and 2) access it such as `line['ROLLNO']` etc... if one wanted to be a bit more explicit as to what's going on in there... (Or maybe even just drop that bit and go for `d[line['ROLLNO'], int(line['COUNT'])] += int(line['AMOUNT'])`...

http://stackoverflow.com/comment/88218310
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50596432
type: AnswerComment
has text: Also ArcPy only runs on Windows.

http://stackoverflow.com/comment/88385234
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50661107
has text: Also make sure that cv2 is installed and available to the selected environment as that can also help with Pylint's errors about not finding attributes on a module.

http://stackoverflow.com/comment/88225522
score: 0
has text: I was confused if this would satisfy the requirements of ,not loading the images all at the same time in tensor form.What I am looking for is that the images are only decoded at the time of training /testing that also in a batch of say 1, until then they are in something like (filename,label) dataset form.
comment on: http://stackoverflow.com/a/50607548
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/88147740
has text: Yup got it working
score: 0
comment on: http://stackoverflow.com/q/50561959
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50670754
accepted answer: http://stackoverflow.com/a/50670789
downvote count: 0
has answer: http://stackoverflow.com/a/50670978
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88351315
has answer: http://stackoverflow.com/a/50670789
tagged with: python
has comment: http://stackoverflow.com/comment/88351419
score: 2
upvote count: 2
tagged with: set
type: Question
has title: Get single "set" object from the list values present in the dictionary
tagged with: set-comprehension
type: AnsweredQuestion
has body: I'm trying to build a set from the values of a dictionary. Each dictionary value is a list of strings. {'a': ['a','b','c'],'b':['a','b','d'],...} I am trying to use .update(x) to concatenate a set containing values from the dictionary. I already have success with a standard for-loop: ingredientSet = set() for values in recipes.values(): ingredientSet.update(values) What I would like to do, if possible, is to do this in a set comprehension. So far I have this: ingredientSet = { ingredientSet.update(x) for x in recipes.values() } but my IDE is giving me an error that "ingredientSet" is referenced before its assignment. Is it possible to use .update(x) in the comprehension, or is there another way to concatenate the items into the set in a comprehension?
tagged with: list-comprehension
possible better answer: http://stackoverflow.com/a/50670978
answer count: 2

http://stackoverflow.com/comment/88374020
score: 0
type: Comment
type: QuestionComment
has text: Instead of counting words. You have solve this problem with regex. Provide some sample input so that we can help you to solve problem.
comment on: http://stackoverflow.com/q/50681710

http://stackoverflow.com/q/50626358
tagged with: pandas
has answer: http://stackoverflow.com/a/50627142
type: Question
tagged with: python
score: 0
answer count: 1
tagged with: graph
tagged with: matplotlib
type: UnansweredQuestion
has title: How can I plot multiple kind of data on a single graph with Python?
has body: I'm aware this may be a newbie question but I was forced to learn data analysis through Python without a proper background knowledge (I tried vb.net 10 years ago, that's all), and I need to solve a problem very fast. I was asked to plot a graph about the speed of a vehicle during a period starting from a dataset like this: ID CITY SPEED TIME 0 Milan 45 25/05/2018 17:35:30 1 Milan 60 25/05/2018 17:35:45 2 Milan 80 25/05/2018 17:36:00 .... 2000 Rome 0 25/05/2018 21:05:15 2001 Rome 0 25/05/2018 21:05:30 2002 Rome 0 25/05/2018 21:05:45 Every dataset I need to analyze have an average of 3000/4000 rows and contain columns I don't need. Now I was able to import the dataset from a file Excel, I created 3 objects with data took from the columns I need: speed = Dataset'speed' time = Dataset'time' city = Dataset'city' What I need is to plot a graph that has the speed as the main data to be visualized, and then the time (on x-axes). When the speed is 0 I also need to show the city. I know how to plot the graph of the speed, but I don't know what to do in order to get time and city where I need them. It should be something like this: graph I need to obtain Any kind of help is really appreciated since I don't know what I need to do to reach this result. Thanks in advance!

http://stackoverflow.com/q/50646321
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/50646707
has title: Need to get or convert data from a site to be valid JSON
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/50646707
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
tagged with: rest
has body: I am working on a script that will get data from a Website (Cisco Patches site) and based on the data received, I need to post it to another site (ServiceNow Event Management). The POST needs to be REST/JSON with specific keys for this to work. I have enough code to GET the data and I have the code to POST working. I am having a hard time with converting the data I get from GET to map it into valid JSON key value pairs to POST. I am using the following code to get a list of new patches from Cisco website. I am getting the correct data but the format if the data is not how I can use it to post to another tool in JSON format (using different keys but values from the returned information. This works - def getjson(ciscourl): response = urllib.request.urlopen(ciscourl) ciscodata = response.read().decode("utf-8") return json.loads(ciscodata) The data I get back looks like below (this query resulted in 2 patches): [{"identifier":"cisco-sa-20180521-cpusidechannel","title":"CPU Side-Channel Information Disclosure Vulnerabilities: May 2018","version":"1.5","firstPublished":"2018-05-22T01:00:00.000+0000","lastPublished":"2018-05-31T20:44:16.123+0000","workflowStatus":null,"id":1,"name":"Cisco Security Advisory","url":"https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20180521-cpusidechannel","severity":"Medium","workarounds":"No","cwe":null,"cve":"CVE-2018-3639,CVE-2018-3640","ciscoBugId":"","status":"Updated","summary":"On May 21, 2018, researchers disclosed two vulnerabilities that take advantage of the implementation of speculative execution of instructions on many modern microprocessor architectures to perform side-channel information disclosure attacks. These vulnerabilities could allow an unprivileged, ","totalCount":6,"relatedResource":[]},{"identifier":"cisco-sa-20180516-firepwr-pb","title":"Cisco Firepower Threat Defense Software Policy Bypass Vulnerability","version":"1.0","firstPublished":"2018-05-16T16:00:00.000+0000","lastPublished":"2…

http://stackoverflow.com/comment/88212321
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50572997
has text: *"...sometimes loose part of their running modules, in this case the server socket and dependent core modules..."* - huh? Are you saying that if you have a running program then parts of the *running* program can suddenly vanish (i.e. without being explicitly freed by code designed to do this) while the rest is still running? If this would be the case then computing would be much more unreliable than it actually is. It would be different if you mean that some process crashes, but then it is the whole process and not some part of it.

http://stackoverflow.com/comment/88347060
type: Comment
type: QuestionComment
has text: pymysql quotes the parameters as required automatically for you, therefore you should remove the quotes `'` surrounding `%s` when using with pymysql or other connectors
comment on: http://stackoverflow.com/q/50668588
score: 1

http://stackoverflow.com/a/50838099
answers question: http://stackoverflow.com/q/50682248
score: 0
type: Answer
has body: I finally got this fixed. @Abihijith Asokan was right. For anyone else who runs into this issue with Django. Basically, there are two environments inside my Django App, one outside environment, one working environment. It was originally installing to this outside environment, so the app could not find it. All I had to do was activate my virtual environment. Locate your activate file, mine was(/var/www/project_name/venv/bin/activate) in the terminal run source /path/to/project/activate then install twilio with pip Now it installed to a different directory and works with out problems.

qpropertyanimation
tag name: qpropertyanimation
tags question: http://stackoverflow.com/q/50611712
type: Tag

http://stackoverflow.com/q/50678693
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50679167
has answer: http://stackoverflow.com/a/50678927
downvote count: 0
has answer: http://stackoverflow.com/a/52119035
has answer: http://stackoverflow.com/a/50679701
favorite count: 0
has comment: http://stackoverflow.com/comment/88366854
has answer: http://stackoverflow.com/a/52579727
answer count: 5
type: UnansweredQuestion
tagged with: python
has title: Automate the Boring Stuff with Python - Comma Code
has comment: http://stackoverflow.com/comment/88366941
has body: So I've come up with a working solution that doesn't use an oxford comma through a bit of a bodge, is there a cleaner way to do this? def stringy(spam): output = "" for thing in spam[:-1]: output = output + thing + ", " output = output[:-2] + " and " + spam[-1] #removes the last 2 chars return output spam = ['cats','cats','cats','cats', 'apples', 'bananas', 'tofu', 'cats'] print(stringy(spam))`
score: 1

http://stackoverflow.com/comment/88125961
type: AnswerComment
has text: thanks Muhammad, but this is not what I needed. Please check out the accepted response.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50551787

http://stackoverflow.com/q/50686613
has comment: http://stackoverflow.com/comment/88383113
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50687081
accepted answer: http://stackoverflow.com/a/50687081
type: Question
has body: I'm new to python so forgive me if I make any stupid errors. I've been trying to figure out how to pass a command to cmd.exe for about an hour now and have encountered an error every time. Recently I've gotten this error: TypeError: bad operand type for unary +: 'str'. Any help would be appreciated, thanks. #defines a function to run BDP command with subprocess def runcommand(command): """Runs command in cmd.exe""" import subprocess cmd = command returned_value = subprocess.call(cmd, shell=True) # returns the exit code in unix print('returned value:', returned_value) #defines a messagebox function to tell user what file to get def messagebox(displayinfo): """Presents a messagebox telling the user to select a file""" from tkinter import messagebox messagebox.showinfo(message = displayinfo) #Sets home to users home path eg C:/users/hsun2 from pathlib import Path home = str(Path.home()) from tkinter import filedialog #asks user for location of bfc file messagebox('Select the bfc.nii.gz file') bfcfile = filedialog.askopenfilename() print(bfcfile) #asks user for location of DTI.nii files messagebox('Select your DTI.nii file') dtinii = filedialog.askopenfilename() #asks user for location of bval file messagebox('Select bval file') bvalfile = filedialog.askopenfilename() #asks user for bvec file messagebox('Select bvec file') bvecfile = filedialog.askopenfilename() output = r"'C:\Program Files\BrainSuite18a\bdp\bdp.exe' " + bfcfile + " --FRT --FRACT --tensor --nii " + dtinii + " -g " + bvalfile + " -b " + bvecfile #print(output) #runs bdp command with user input #output = runcommand("'C:\Program Files\BrainSuite18a\bdp\bdp.exe' " + bfcfile + #" --FRT --FRACT --tensor --nii " + dtinii + " -g " + bvalfile + #" -b " + bvecfile) Returns C:/Users/hsun2/Desktop/localBDP/MTS/testpy/MTS126028/BrainSuite/sagT1MPRAGE_we_normal.bfc.nii.gz Traceback (most recent call last): File "bdpcommandtest.py", line 44, in &lt;module&gt; + " --FRT --FRACT --tensor --nii " + dtinii + " -g " + bval…
has answer: http://stackoverflow.com/a/50686922
has comment: http://stackoverflow.com/comment/88383090
has comment: http://stackoverflow.com/comment/88383178
has comment: http://stackoverflow.com/comment/88383394
score: -1
has comment: http://stackoverflow.com/comment/88383099
has comment: http://stackoverflow.com/comment/88383230
possible better answer: http://stackoverflow.com/a/50686922
has comment: http://stackoverflow.com/comment/88383032
has title: Getting TypeError: bad operand type for unary +: 'str' when trying to use subprocess
answer count: 2
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/88382961
favorite count: 0

http://stackoverflow.com/q/50677544
has answer: http://stackoverflow.com/a/52009522
tagged with: padding
downvote count: 0
possible better answer: http://stackoverflow.com/a/53349976
tagged with: keras
accepted answer: http://stackoverflow.com/a/50679524
favorite count: 0
tagged with: zero-padding
answer count: 5
tagged with: python
has body: I'm using keras to build a convolutional neural network for image segmentation and I want to use "reflection padding" instead of padding "same" but I cannot find a way to to do it in keras. inputs = Input((num_channels, img_rows, img_cols)) conv1=Conv2D(32,3,padding='same',kernel_initializer='he_uniform',data_format='channels_first')(inputs) Is there a way to implement a reflection layer and insert it in a keras model ?
has answer: http://stackoverflow.com/a/50677669
upvote count: 6
type: AnsweredQuestion
tagged with: conv-neural-network
has answer: http://stackoverflow.com/a/60116269
score: 6
type: Question
has title: Reflection padding Conv2D
has answer: http://stackoverflow.com/a/50679524
has answer: http://stackoverflow.com/a/53349976

http://stackoverflow.com/comment/88306798
has text: @eyllanesc for sure i will use it in qml, since i am going to maybe present some of the data visually.Lets just say i have a label in my qml, on which i will show artist when the song starts. the code is "working" atm, instead of thread what would you suggest ?
comment on: http://stackoverflow.com/q/50626583
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50652758
tagged with: apache-zookeeper
accepted answer: http://stackoverflow.com/a/50828825
answer count: 1
tagged with: kazoo
downvote count: 0
has body: I am able to get current contenders using election.lock._get_sorted_children() and respective identifiers using election.lock.contenders(). But election.lock.contenders() also sorts the list, so will election.lock.contenders()[0] always be the leader? Note, election = zk.Election("/path", "uuid") where zk is the KazooClient Is there any better way to verify the leader?
favorite count: 0
has title: getting current leader of election recipe in kazoo
has answer: http://stackoverflow.com/a/50828825
tagged with: python
type: AnsweredQuestion
type: Question
score: 4
upvote count: 4

http://stackoverflow.com/comment/88352888
has text: @optilude adding the explanation line by line :-)
score: 0
comment on: http://stackoverflow.com/a/50661825
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50545506
tagged with: convolution
has answer: http://stackoverflow.com/a/50545910
has body: I am following this StackOverflow question and answer. However, I am still confused of the start index and padding strategy of tf.nn.conv2d after doing the following tests, hopefully, someone can give me a clue here, especially on odd and even strides. array height(h),kernel size(f), stride number(s) h,f,s = 4,3,2 padding number on left column (pl) padding on right column (pr) of matrix x pl = int((f-1)/2) pr = int(np.ceil((f-1)/2)) tf.reset_default_graph() x = np.arange(1*h*h*1).reshape(1,h,h,1) w = np.ones((f,f,1,1)) xc = tf.constant(x,np.float32) wc = tf.constant(w,np.float32) xp = np.pad(x,((0,0),(pl,pr),(pl,pr),(0,0)),'constant',constant_values = 0) xcp = tf.constant(xp,np.float32) zs = tf.nn.conv2d(xc,wc,strides=[1,s,s,1],padding='SAME') zv = tf.nn.conv2d(xc,wc,strides=[1,s,s,1],padding='VALID') zp = tf.nn.conv2d(xcp,wc,strides=[1,s,s,1],padding='VALID') with tf.Session() as sess: os = sess.run(zs) ov = sess.run(zv) op = sess.run(zp) print('x shape: ', x.shape,' kernel: ',f,' stride: ',s,'\n',x[0,:,:,0]) print(' 'SAME' os shape: ', os.shape,'\n',os[0,:,:,0]) print(' 'VALID' ov shape: ', ov.shape,'\n',ov[0,:,:,0]) print(' 'VALID' op shape: ', op.shape,' pl: ',pl,' pr: ', pr,'\n',op[0,:,:,0]) In the case of pooling in convolution, the zero padding should pad around the array x like how I define xp, however, I cannot figure out the conv2d start index of it. Original matrix x x shape: (1, 4, 4, 1) kernel: 3 stride: 2 [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] In 'same' type convolution, why doesn't tf.nn.conv2d pad zero on the left in this case? 'SAME' os shape: (1, 2, 2, 1) [[45. 39.] [66. 50.]] Valid convolution on matrix x: 'VALID' ov shape: (1, 1, 1, 1) [[45.]] 'valid' type convolution after zero padding from xp (as my expected result). 'VALID' op shape: (1, 2, 2, 1) pl: 1 pr: 1 [[10. 24.] [51. 90.]]
linked to: http://stackoverflow.com/q/44853243
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50545910
score: 1
tagged with: tensorflow
type: Question
downvote count: 0
answer count: 1
has title: What is the padding strategy of TensorFlow conv2d?
favorite count: 0

http://stackoverflow.com/comment/88249085
has text: Thanks for your comments. But when I use `model.build_vocab` I get this error: `AttributeError: 'KeyedVectors' object has no attribute 'build_vocab'. How can I use build_vocab?
comment on: http://stackoverflow.com/q/50618993
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50694909
tagged with: sql-server
score: 0
has body: I am working on a program that requires a Microsoft SQL server to run, I need some kind of environment that can easily be shared with other developers, naturally docker came in mind. Can I have an installation of the Microsoft SQL server with my scripts, dependencies, python installation etc. in a docker container? is this something to be avoided? Thank you.
has comment: http://stackoverflow.com/comment/88399533
tagged with: python
has title: Can/Should I add a database in a Docker container?
answer count: 0
type: UnansweredQuestion
type: Question
tagged with: database
has comment: http://stackoverflow.com/comment/88399356
tagged with: docker

http://stackoverflow.com/comment/88312038
type: QuestionComment
comment on: http://stackoverflow.com/q/50642738
score: 0
has text: I tried to do something like this: verbnet.classids(wordnetid='take.v.01')
type: Comment

http://stackoverflow.com/comment/88324801
type: QuestionComment
comment on: http://stackoverflow.com/q/50656955
has text: In any case, you didn't answer what your ultimate problem is, because there could be a better way than relying on the free Google API limits (unless you _need_ real-time traffic)
score: 0
type: Comment

http://stackoverflow.com/a/50662321
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/88335140
answers question: http://stackoverflow.com/q/50661910
score: 3
accepted answer of: http://stackoverflow.com/q/50661910
has body: I don't know PIL but if your code works for the first image and your problem is the iteration, then you can do: import pandas as pd from PIL import ImageFont from PIL import Image from PIL import ImageDraw ruta_excel=pd.read_excel('C:/Users/san_2/Documents/Script/ARCPY/Direc.xls',sheet_name=0) # iterate over rows with itertuples for row in ruta_excel.itertuples(index=False): print (row) # to help you see what is happening but not necessary after # row is tuple, doing row[0] access to the first item (the first column) ruta=row[0] image_files = Image.open(ruta) font_type = ImageFont.truetype('C:/Windows.old/Windows/Fonts/Arial.ttf',18) draw = ImageDraw.Draw(image_files) # here you use row[1] and row[2] draw.text(xy=(20,550),text= row[1],fill=(255,255,255),font=font_type) draw.text(xy=(20,570),text= row[2],fill=(255,255,255),font=font_type) image_files.save(ruta, 'JPEG', quality=90)
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50564099
accepted answer: http://stackoverflow.com/a/50564266
answer count: 1
tagged with: scikit-learn
score: 0
has answer: http://stackoverflow.com/a/50564266
has body: I am using following code for LatentDirichletAllocation through scikit of python library: tf_vectorizer = CountVectorizer(max_df=0.95, min_df=2, stop_words='english') tf = tf_vectorizer.fit_transform(documents) lda_model = LatentDirichletAllocation(n_components=10, max_iter=5, learning_method='online', learning_offset=50.,random_state=0).fit(tf) lda_W = lda_model.transform(tf) lda_H = lda_model.components_ when I print shape of lda_H it returns (10, 236), I understand 10 is for topic numbers and 236 are the words. I wish to see the effect of alpha on this so i changed the above code to : lda_model = LatentDirichletAllocation(n_components=10,doc_topic_prior=.01, max_iter=5, learning_method='online', learning_offset=50.,random_state=0).fit(tf) lda_W = lda_model.transform(tf) lda_H = lda_model.components_ however i found there is no effect of alpha on the words in the Topics and lda_H still returns (10, 236). I wonder why alpha does not change the words in the topic. i tried different values of the alpha but no changed is observed in lda_H Please any comments on it is appreciated.
has comment: http://stackoverflow.com/comment/88138489
tagged with: python
tagged with: lda
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88138723
type: Question
has title: LatentDirichletAllocation python
has comment: http://stackoverflow.com/comment/88138376

http://stackoverflow.com/comment/88120026
score: 0
has text: the data package is a package created by me - it just hold logic to get data from the databases. i think my problem has to do with custom packages missing something to import properly in a streamlined and fast way, but what could that be? - not asking you to debug my project of course, but i m sure other people might have had the same problem while creating there own packages.
type: Comment
comment on: http://stackoverflow.com/a/50554426
type: AnswerComment

http://stackoverflow.com/a/50594288
has body: Use dynamic shapes, you can find the details here. Your input_shape should be: inputs_shape = tf.shape(inputs) ... batch_size, inputs_height, inputs_width, n_channel = inputs_shape[0],inputs_shape[1],inputs_shape[2],inputs_shape[3]
has comment: http://stackoverflow.com/comment/88199014
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50577055
accepted answer of: http://stackoverflow.com/q/50577055
upvote count: 2
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/50593550
has title: assert self._state in (CLOSE, TERMINATE) when using python multiprocess
score: 5
has comment: http://stackoverflow.com/comment/88196412
has comment: http://stackoverflow.com/comment/88218305
tagged with: threadpool
downvote count: 0
has body: I am currently trying to use python multiprocessing. The library I use is multiprocess (NOT multiprocessing). I have the following code, which creates a number of computing jobs, and runs it through a map operation: pool = multiprocess.Pool(4) all_responses = pool.map_async(wrapper_singlerun, range(10000)) pool.join() pool.close() However, whenever I run this snippet of code, I get the following error: pool.join() File "/Users/davidal/miniconda3/lib/python3.6/site-packages/multiprocess/pool.py", line 509, in join assert self._state in (CLOSE, TERMINATE) AssertionError Do you have any idea why this error happens? I used pool.map_async before, but figured that I need to have a pool rendez-vous command. Otherwise, my PC created something like a forkbomb, which created too many threads (at least, that's what I think it does...) Any ideas are appreciated!
answer count: 1
has comment: http://stackoverflow.com/comment/88215186
tagged with: multiprocess
favorite count: 0
upvote count: 5
has comment: http://stackoverflow.com/comment/88196593
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88196463
has answer: http://stackoverflow.com/a/50610452
type: Question
accepted answer: http://stackoverflow.com/a/50610452
tagged with: python-multiprocessing
tagged with: multiprocessing

http://stackoverflow.com/q/50671180
duplicate of: http://stackoverflow.com/q/28232673
has answer: http://stackoverflow.com/a/50671265
favorite count: 0
tagged with: python-3.x
upvote count: 2
tagged with: python
type: AnsweredQuestion
has body: I want to define a function that returns the values of the roots. It is supposed to return always something. If b**2 - 4ac &lt; 0, then it is supposed to return [ ], but it appears as an error. My code is this by now: from math import* def solve(a, b, c): x = sqrt(b**2 - 4*a*c) if x &gt; 0: x1 = (-b + x)/(2*a) x2 = (-b - x)/(2*a) return [x1, x2] elif x == 0: x1 = x2 = -b/(2*a) return [x1] else: return []
has title: Roots of a quadratic function: math domain error
tagged with: math
accepted answer: http://stackoverflow.com/a/50671282
type: Question
answer count: 2
score: 2
tagged with: square-root
downvote count: 0
linked to: http://stackoverflow.com/q/28232673
possible better answer: http://stackoverflow.com/a/50671265
has answer: http://stackoverflow.com/a/50671282

http://stackoverflow.com/a/50629379
has comment: http://stackoverflow.com/comment/88289768
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50626526
has comment: http://stackoverflow.com/comment/88465118
has body: There is different option, one way is: ref_date_POE = min(df['POETime']) # or any date you want df['POEHours'] = (df['POETime'] - ref_date_POE).dt.days*24 + df['POETime'].dt.hour +1 Here (df['POETime'] - ref_date_POE).dt.days give you the number of days between the date in df['POETime'] and ref_date_POE, so *24 give you what you want. For the +1, it seems that you have 3 when it's 2:18 and df['POETime'].dt.hour would give you 2, so just add 1.

sum
tags question: http://stackoverflow.com/q/50637863
tags question: http://stackoverflow.com/q/50544788
type: Tag
tag name: sum
tags question: http://stackoverflow.com/q/50565860
tags question: http://stackoverflow.com/q/50592401
tags question: http://stackoverflow.com/q/50669785
tags question: http://stackoverflow.com/q/50548051

http://stackoverflow.com/a/50689701
downvote count: 0
answers question: http://stackoverflow.com/q/50689599
upvote count: 2
type: Answer
score: 2
has body: We can do this by creating two models: Post (that will in reality contain extra data like the message, author, etc.), and Like that is acts as a many-to-many relation between a Post and a User: class Post(models.Model): total_likes = models.IntegerField(default=0) likes = models.ManyToManyField(User, through='app.Like') def like(self, user): _, created = Like.objects.get_or_create(user=user, post=self) if created: self.total_likes += 1 self.save() @classmethod def update_likes(cls): cls.objects.annotate(total=Count('likes')).update(total_likes=F('total')) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) So the like(..) function is used to like a post (with as parameter the user). We can thus call somepost.like(someuser). It will fetch or create a new Like object that maps to the specific post and the specific user. In case the Like instance already existed, nothing happend, otherwise we increment the total_likes field that stores the total number of likes. Perhaps you do not want to update this counter every time a user likes a post: after all, it creates some extra load on the server. In that case, the if created: part can be omitted, and we regularly should call Post.update_likes. This function will perform an aggregate per Post that counts the number of likes, and it will update the total_likes field. Regardless whether you update total_likes constantly, it is better to every now and then update the total number of likes per post. Since other views, models, etc. can - given you the developers are not looking very strict to this - remove Like objects. Furthermore Users can be removed, etc. and we have not much control about that. Yes we can create signals that are triggered after Likes and Users are removed (and created), but still there can be problems with counting the number of likes like race conditions. Therefore I would advice to periodically update the number of likes…
accepted answer of: http://stackoverflow.com/q/50689599
type: AcceptedAnswer

http://stackoverflow.com/comment/88137535
has text: Ports don't matter. See js source code on website: `var rnd= parseInt (Math.random()*40)+50;`, it is just a random number between `8050` and `8090`. You can use any of them in your python code.
comment on: http://stackoverflow.com/q/50563465
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88223579
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50606572
score: 0
has text: How do I run it as administrator? and how do i set it to path variables? im using macos

http://stackoverflow.com/comment/88245077
has text: Thanks a lot bro. It helped
type: Comment
comment on: http://stackoverflow.com/a/50617059
type: AnswerComment
score: 0

powershell
tags question: http://stackoverflow.com/q/50607851
type: Tag
tag name: powershell

http://stackoverflow.com/q/50602160
has comment: http://stackoverflow.com/comment/88227464
type: Question
has body: I am having problem with understanding how data should be prepared for different models: One to many Many to one Many to many(A) Many to many(B) Is the right way to think o it this way. Shape numbers are no relevant and do not match the one on picture. I am just trying to understand logic behind.: import numpy as np #1. one to many # X for input y for output X = np.ones([10,1,5]) y = np.zeros([10,3]) #3 represnts size of output vector #2. many to one X = np.ones([10,5,5]) y = np.zeros([10,1]) #3. many to many X = np.ones([10,5,5]) y = np.zeros([10,5]) # in this case cell should be different than y. It must be bigger to shift some data #4. many to many X = np.ones([10,5,5]) y = np.zeros([10,5]) # in this case cell is the same shape as y
tagged with: neural-network
tagged with: lstm
tagged with: numpy
has title: structuring data in numpy for ltsm (examples)
tagged with: deep-learning
downvote count: 0
has comment: http://stackoverflow.com/comment/88227061
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88213896
answer count: 0
score: 1
upvote count: 1

tkinter
tags question: http://stackoverflow.com/q/50583251
tags question: http://stackoverflow.com/q/50594802
tags question: http://stackoverflow.com/q/50598723
tags question: http://stackoverflow.com/q/50663034
tags question: http://stackoverflow.com/q/50686913
tags question: http://stackoverflow.com/q/50602212
tags question: http://stackoverflow.com/q/50608927
tags question: http://stackoverflow.com/q/50630793
tags question: http://stackoverflow.com/q/50570446
tags question: http://stackoverflow.com/q/50542514
tags question: http://stackoverflow.com/q/50634982
tags question: http://stackoverflow.com/q/50550375
tags question: http://stackoverflow.com/q/50682186
tags question: http://stackoverflow.com/q/50640564
tags question: http://stackoverflow.com/q/50541892
tags question: http://stackoverflow.com/q/50583643
tags question: http://stackoverflow.com/q/50557281
tags question: http://stackoverflow.com/q/50551765
tags question: http://stackoverflow.com/q/50587961
tags question: http://stackoverflow.com/q/50594778
tags question: http://stackoverflow.com/q/50664196
tags question: http://stackoverflow.com/q/50563162
tags question: http://stackoverflow.com/q/50601867
tags question: http://stackoverflow.com/q/50673249
tag name: tkinter
tags question: http://stackoverflow.com/q/50668894
tags question: http://stackoverflow.com/q/50555522
tags question: http://stackoverflow.com/q/50581791
tags question: http://stackoverflow.com/q/50615371
tags question: http://stackoverflow.com/q/50548034
tags question: http://stackoverflow.com/q/50614498
tags question: http://stackoverflow.com/q/50555395
tags question: http://stackoverflow.com/q/50662147
tags question: http://stackoverflow.com/q/50616685
tags question: http://stackoverflow.com/q/50659944
tags question: http://stackoverflow.com/q/50696588
tags question: http://stackoverflow.com/q/50677265
tags question: http://stackoverflow.com/q/50608245
tags question: http://stackoverflow.com/q/50551198
tags question: http://stackoverflow.com/q/50670098
tags question: http://stackoverflow.com/q/50658649
tags question: http://stackoverflow.com/q/50557594
tags question: http://stackoverflow.com/q/50588646
tags question: http://stackoverflow.com/q/50689035
tags question: http://stackoverflow.com/q/50549536
tags question: http://stackoverflow.com/q/50571515
tags question: http://stackoverflow.com/q/50675182
tags question: http://stackoverflow.com/q/50578034
tags question: http://stackoverflow.com/q/50613392
tags question: http://stackoverflow.com/q/50612882
tags question: http://stackoverflow.com/q/50625818
tags question: http://stackoverflow.com/q/50607505
tags question: http://stackoverflow.com/q/50581000
tags question: http://stackoverflow.com/q/50624741
tags question: http://stackoverflow.com/q/50689840
tags question: http://stackoverflow.com/q/50548012
tags question: http://stackoverflow.com/q/50553846
tags question: http://stackoverflow.com/q/50618171
tags question: http://stackoverflow.com/q/50667026
tags question: http://stackoverflow.com/q/50662638
tags question: http://stackoverflow.com/q/50684088
tags question: http://stackoverflow.com/q/50588820
tags question: http://stackoverflow.com/q/50633440
tags question: http://stackoverflow.com/q/50581645
tags question: http://stackoverflow.com/q/50574809
tags question: http://stackoverflow.com/q/50650012
tags question: http://stackoverflow.com/q/50683910
tags question: http://stackoverflow.com/q/50606250
tags question: http://stackoverflow.com/q/50607811
tags question: http://stackoverflow.com/q/50557438
tags question: http://stackoverflow.com/q/50589632
tags question: http://stackoverflow.com/q/50643397
tags question: http://stackoverflow.com/q/50568880
tags question: http://stackoverflow.com/q/50614920
tags question: http://stackoverflow.com/q/50690426
tags question: http://stackoverflow.com/q/50573260
tags question: http://stackoverflow.com/q/50542331
tags question: http://stackoverflow.com/q/50605101
tags question: http://stackoverflow.com/q/50665205
tags question: http://stackoverflow.com/q/50590385

pointers
tags question: http://stackoverflow.com/q/50596131
tags question: http://stackoverflow.com/q/50610334
type: Tag
tag name: pointers

http://stackoverflow.com/comment/88366441
type: Comment
has text: well that is logical, you can try to use `time__in=all_groups`, but this looks like simply wrong modeling. You have no guarantees whatsoever that there is only one `Groups_By_Dates`, so this can raise a `MultipleObjectsReturned` error.
score: 1
comment on: http://stackoverflow.com/q/50678420
type: QuestionComment

http://stackoverflow.com/comment/88201646
has text: Selenium 2.53.2 and IEdriverserver 3.9 version
score: 0
comment on: http://stackoverflow.com/q/50595740
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88305414
has text: The loop will execute as long as the input isn't zero!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50647383

http://stackoverflow.com/comment/88110981
comment on: http://stackoverflow.com/q/50549910
has text: https://ideone.com/CFEtD3
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/50628885
answers question: http://stackoverflow.com/q/50628724
has body: Just drop .head() in print(df.head()) because that's meant to yield the first 5 rows. https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.head.html
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88273272
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/50628724

http://stackoverflow.com/q/50572233
has title: How globally accurate is Python's time.time function?
has body: I'm trying to measure the total time of a one-way trip UDP multicast. I have a device sending out a message on the multicast group every half second, and I have another device listening. I want to measure how long that takes, so I had the idea of taking a timestamp on the send side with time.time(), sending it as the message, and then subtracting that from the timestamp at the other end when the message is received. However, I'm getting some negative numbers. I think that some of this has to do with decimal accuracy, which is something I'm still figuring out, but it is making me ask the question: How globally accurate is time.time()? Will time.time() be the same down to the millisecond or microsecond for the same instant on two different devices? Some code: Sender: import time import decimal [... socket setup ...] current = str(decimal.Decimal(time.time())) socket.sendto(current, ...) Receiver: import time [... socket setup ...] stamp = sock.recv(10240) current = time.time() diff = current - stamp # stamp should be positive... Edit: this is not a duplicate. That high-precision question has to do with relative precision, I'm asking about global precision (precision between devices). A device may be precise to the microsecond relative to itself, but be on a different second than another machine. Edit 2: It seems that my actual question is, how globally accurate are Unix clocks?
type: Question
tagged with: time
tagged with: python
score: 0
linked to: http://stackoverflow.com/q/1938048
duplicate of: http://stackoverflow.com/q/1938048
has comment: http://stackoverflow.com/comment/88154643
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88154578
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/88159750
answer count: 0

http://stackoverflow.com/q/50583868
has comment: http://stackoverflow.com/comment/88177263
has comment: http://stackoverflow.com/comment/88176964
accepted answer: http://stackoverflow.com/a/50585643
has comment: http://stackoverflow.com/comment/88177446
favorite count: 0
linked to: http://stackoverflow.com/q/42973200
tagged with: series
tagged with: pandas
has comment: http://stackoverflow.com/comment/88177483
has comment: http://stackoverflow.com/comment/88178094
tagged with: python
has comment: http://stackoverflow.com/comment/88177137
has comment: http://stackoverflow.com/comment/88177920
score: 6
has comment: http://stackoverflow.com/comment/88177621
upvote count: 7
downvote count: 1
has comment: http://stackoverflow.com/comment/88177195
possible better answer: http://stackoverflow.com/a/50584443
tagged with: indexing
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50584443
has title: Append values to Pandas series
has body: I am selecting values from an SQL database through pandas, but when I want to add new values to the existing pandas series, I receive a "cannt concatenate a non-NDframe object". So I am not really sure how I should proceed. sql = "select * from table" df = pd.read_sql(sql, conn) datovalue = df['Datovalue'] datovalue.append(35) This is is how the datovalues look like when i print it out: 0 736722.0 1 736722.0 2 736723.0 3 736723.0 4 736725.0 How do add an extra (5th index in this case) value?
type: Question
has answer: http://stackoverflow.com/a/50585643
answer count: 2

http://stackoverflow.com/a/50698520
answers question: http://stackoverflow.com/q/50698349
has body: Create new Series by compare shiftd merged columns with ne (!=) and add cumsum for consecutive groups Series: a['date'] = pd.to_datetime(a['date']) s = a['name'] + '_' + a['food'] a['r'] = a.groupby(s.ne(s.shift()).cumsum())['date'].rank().astype(int) Or: a['r'] = a.groupby(s.ne(s.shift()).cumsum())['date'].cumcount().add(1) print (a) name date food r 0 Mary 2018-06-01 pizza 1 1 Mary 2018-06-02 pizza 2 2 Mary 2018-06-03 burger 1 3 Mary 2018-06-04 burger 2 4 Mary 2018-06-05 pizza 1 5 Mary 2018-06-06 burger 1 6 Bob 2018-06-03 pizza 1 7 Bob 2018-06-04 burger 1 8 Bob 2018-06-05 burger 2 9 Bob 2018-06-05 pizza 1 Detail: print (s.ne(s.shift()).cumsum()) 0 1 1 1 2 2 3 2 4 3 5 4 6 5 7 6 8 6 9 7 dtype: int32
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50698349
type: Answer
upvote count: 1

http://stackoverflow.com/q/50603385
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/88216482
type: Question
has comment: http://stackoverflow.com/comment/88216299
has comment: http://stackoverflow.com/comment/88215912
tagged with: python
has comment: http://stackoverflow.com/comment/88216486
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/88219028
score: 0
has comment: http://stackoverflow.com/comment/88216125
answer count: 1
has title: Python xml parsing with beautifulsoup
has answer: http://stackoverflow.com/a/50607433
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88220734
accepted answer: http://stackoverflow.com/a/50607433
has body: I have below xml file, I would like to extract all the href, I know how to do that, but I want to mark end of each main 'parent' tag with ---- I need an output like this: xxxx yyyy ----- zzzz tttt ------ wwww qqqqq ssss uuuu oooo pppp ----- mmmm nnnnn ---- xml: <root> <child herf='xxx'/> <child herf ='yyyy'/> <child herf='zzzz'/> <child herf ='tttt'/> <child herf='wwww'/> <child herf ='qqqqq'/> <child herf='ssss'/> <child herf ='uuuu'/> <child herf='oooo'/> <child herf ='pppp'/> <child herf='mmmm'/> <child herf ='nnnnn'/> This is my code : xml= soupTop.findChildren(recursive=False) for tag in xml: s =tag.findAll("child", {"href" : re.compile(r".*")}) print (s)

http://stackoverflow.com/comment/88280384
has text: But that in AddressSerializer, location field is a must have. To be clear with, I need the AddressSerializer to be optional(required=False), I m aware that required=False only for fields and not for serialisers. But, how to achieve that..?
type: Comment
comment on: http://stackoverflow.com/a/50635090
score: 0
type: AnswerComment

http://stackoverflow.com/a/50593796
has body: The code here may be of interest: https://github.com/python-openxml/python-docx/issues/276#issuecomment-199502885. What you're looking for, I believe, is a way to iterate the block level items in a document, in the order they appear. A Word document has two types of block-level items, paragraphs and tables. The function at the link above allows you to iterate those in document order.
type: Answer
accepted answer of: http://stackoverflow.com/q/50589771
has comment: http://stackoverflow.com/comment/88224021
answers question: http://stackoverflow.com/q/50589771
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/50672927
has comment: http://stackoverflow.com/comment/88550479
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88419922
type: Answer
score: 2
upvote count: 2
has body: In my case, you can add 'tensorflow.contrib' in your hiddenimport from the .spec file. However, I met another problem after I fix the import, but you can first try this at least.
answers question: http://stackoverflow.com/q/50628915
accepted answer of: http://stackoverflow.com/q/50628915

http://stackoverflow.com/comment/88256120
has text: I'm Developing for Python 2.4 (lowest server version, unfortunately something I have no control over) but my local machine is running python2.7.14 I'll look into separating out the classes, but considering it was meant to be a migration script for non-developers (i.e. a script, sample config file and a jargon-free work doc) I'd perfer to explore other options first if I can.
score: 0
comment on: http://stackoverflow.com/q/50622568
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88320393
score: 0
type: QuestionComment
type: Comment
has text: I see... You should add some code to the question.
comment on: http://stackoverflow.com/q/50654530

http://stackoverflow.com/q/50557914
has body: link.here/python.php Linux link2.here/python.php Linux link3.here/python.php Linux here is an example of code and i want to extract the link on it using python can anyone help me please ?
answer count: 1
downvote count: 1
favorite count: 0
has title: How can i extract html data with python?
tagged with: extract
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/88126846
upvote count: 0
has answer: http://stackoverflow.com/a/50557987
has comment: http://stackoverflow.com/comment/88126692
accepted answer: http://stackoverflow.com/a/50557987
has comment: http://stackoverflow.com/comment/88126714
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88126749
score: -1

merge
tags question: http://stackoverflow.com/q/50696386
tags question: http://stackoverflow.com/q/50555555
tags question: http://stackoverflow.com/q/50631670
tags question: http://stackoverflow.com/q/50657714
tags question: http://stackoverflow.com/q/50592595
tags question: http://stackoverflow.com/q/50635104
tags question: http://stackoverflow.com/q/50580408
tags question: http://stackoverflow.com/q/50655370
tags question: http://stackoverflow.com/q/50596972
tags question: http://stackoverflow.com/q/50580759
tags question: http://stackoverflow.com/q/50662613
tags question: http://stackoverflow.com/q/50628767
type: Tag
tags question: http://stackoverflow.com/q/50684852
tags question: http://stackoverflow.com/q/50549759
tags question: http://stackoverflow.com/q/50658181
tags question: http://stackoverflow.com/q/50684663
tags question: http://stackoverflow.com/q/50608520
tag name: merge
tags question: http://stackoverflow.com/q/50573457
tags question: http://stackoverflow.com/q/50678599
tags question: http://stackoverflow.com/q/50548818

http://stackoverflow.com/a/50657088
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50656964
has comment: http://stackoverflow.com/comment/88324258
has comment: http://stackoverflow.com/comment/88324514
answers question: http://stackoverflow.com/q/50656964
has comment: http://stackoverflow.com/comment/88324453
score: 4
has comment: http://stackoverflow.com/comment/88324468
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88324178
has body: Without having used asyncpg, I assume like in most asyncio compliant packages that there is an async context manager allowing exactly what you are asking for. Something like: async with asyncpg.create_pool(**kwargs) as pool: async with pool.acquire() as connection: async with connection.transaction(): result = await connection.fetchval(fetch stuff) connection.execute(insert stuff with result) (as taken from this question) Check the docs for mentions of context managers or examples with async with statements or if nothing else then check classes in the source code which have implement the __aenter__, __aexit__ methods. Edit 1: The example above is partly taken from the question I've linked to and partly contrived for completeness. But to address your comments about what the with statements are doing: async with asyncpg.create_pool(**kwargs) as pool: #in this block pool is created and open async with pool.acquire() as connection: # in this block connection is acquired and open async with connection.transaction(): # in this block each executed statement is in a transaction execute_stuff_with_connection(connection) # now we are back up one logical block so the transaction is closed do_stuff_without_transaction_but_with_connection(connection) # now we are up another block and the connection is closed and returned to the pool do_more_stuff_with_pool(pool) # now we are up another level and the pool is closed/exited/cleaned up done_doing_async_stuff() I'm not sure how good of an explanation this is, perhaps you should read up on context managers.
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/88324311

http://stackoverflow.com/a/50625086
answers question: http://stackoverflow.com/q/50608443
type: Answer
upvote count: 27
has comment: http://stackoverflow.com/comment/97056196
accepted answer of: http://stackoverflow.com/q/50608443
has comment: http://stackoverflow.com/comment/101858303
has body: If you look closely into PyCharm sources, from the whole pytest output, PyCharm uses a single line the to parse the data for displaying in the Click to see difference dialog. This is the AssertionError: &lt;message&gt; line: def test_spam(): > assert v1 == v2 E AssertionError: assert {'foo': 'bar'} == {'foo': 'baz'} E Differing items: E {'foo': 'bar'} != {'foo': 'baz'} E Use -v to get the full diff If you want to see the full diff line without truncation, you need to customize this line in the output. For a single test, this can be done by adding a custom message to the assert statement: def test_eggs(): assert a == b, '{0} != {1}'.format(a, b) If you want to apply this behaviour to all tests, define custom pytest_assertrepr_compare hook. In the conftest.py file: # conftest.py def pytest_assertrepr_compare(config, op, left, right): if op in ('==', '!='): return ['{0} {1} {2}'.format(left, op, right)] The equality comparison of the values will now still be stripped when too long; to show the complete line, you still need to increase the verbosity with -vv flag. Now the equality comparison of the values in the AssertionError line will not be stripped and the full diff is displayed in the Click to see difference dialog, highlighting the diff parts:
type: AcceptedAnswer
downvote count: 0
score: 27
has comment: http://stackoverflow.com/comment/101923191

http://stackoverflow.com/comment/88163616
comment on: http://stackoverflow.com/q/50577241
score: 0
type: QuestionComment
has text: Iterate in reverse, with the appropriate condition, or use a list comprehension: `t = set(lst2); lst1 = [x for x in lst1 if x not in t]`
type: Comment

http://stackoverflow.com/comment/88111575
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50549922
type: Comment
has text: Thanks for the detail. I will modify with your code. Can we send images like this using WhatsApp API?

http://stackoverflow.com/comment/88383296
score: 0
has text: There's also a major problem with the second for loop: `for amount2 ...` vs `while float(line2)`, even if `while` was the correct control statement to use. Given the first readline seems to be to throw away a header line, I'd actually expect an exception to be thrown if it ever reached the second loop.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50686608

http://stackoverflow.com/a/50592719
upvote count: 13
has comment: http://stackoverflow.com/comment/88194993
downvote count: 0
answers question: http://stackoverflow.com/q/50592576
has body: As @Antti said in a comment, this is equivalent to looking for combinations of positions of the input list which determine which bits in the output are 1. from itertools import combinations def binary_permutations(lst): for comb in combinations(range(len(lst)), lst.count(1)): result = [0] * len(lst) for i in comb: result[i] = 1 yield result for perm in binary_permutations([1, 1, 0, 0]): print(perm) Output: [1, 1, 0, 0] [1, 0, 1, 0] [1, 0, 0, 1] [0, 1, 1, 0] [0, 1, 0, 1] [0, 0, 1, 1]
type: Answer
score: 13

http://stackoverflow.com/comment/88295310
has text: Were the spaces already in your lists and how did you create those two lists?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50642551
score: 0

http://stackoverflow.com/q/50648543
answer count: 0
tagged with: subprocess
downvote count: 0
tagged with: popen
score: 1
has comment: http://stackoverflow.com/comment/88308288
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/88308394
favorite count: 0
type: UnansweredQuestion
has body: Hello to whoever reads this. I have spent too long on this issue and exhausted my options. The subprocess docs are quite poor in my opinion and I've read countless stackoverflow questions to no avail. I simply would like to use the pushd command on windows to change directories. Once there, I will want to use communicate() to issue a command. For this examples purpose. I will say that command is dir. I would also like to "pop" back directories but am not sure if that is possible with another communicate method. If anyone can provide any insight, then that would be great. Right now my program is not outputting anything to me. Printing p.stdout.readline() is not working either. p = subprocess.Popen([r"pushd", r"C:\MishaMachine"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) p.communicate('dir')
tagged with: python
has title: Subprocess popen with pushd command

http://stackoverflow.com/a/50650524
has body: Assuming the "can't" above is not really in your code, if possible update your question to omit the "'" as it messes up the readability or change to some other placeholder text. As the error indicates, you have not assigned a value yet to counter, the method "on_status" will try to increment counter, but this is only local to the method, not the object, thus it fails. def on_status(self, status): #prints status text. can be replaced with a counter probably. counter = counter + 1 print(status.text) You should initialize the counter in an init method and then use self.counter instead. Add ... class MySteamListener(tweepy.StreamListener): def __init__(self): # Not sure if necessary, to make this work, but you could # Initialize the inherited class as well (this may work only in Python 3) # super().__init__() self.counter = 0 ... Modify on_status to def on_status(self, status): #prints status text. can be replaced with a counter probably. self.counter = self.counter + 1 # Can be written as 'self.counter += 1' print(status.text)
downvote count: 0
has comment: http://stackoverflow.com/comment/88312285
score: 1
accepted answer of: http://stackoverflow.com/q/50650345
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88421421
answers question: http://stackoverflow.com/q/50650345
upvote count: 1
type: Answer

http://stackoverflow.com/a/50557524
type: AcceptedAnswer
score: 0
type: Answer
has body: Okay, you seem to be confused about some of the terminology. Let's define some terms: Region: A geographic location containing multiple Availability Zones, eg London, Ohio Availability Zone: A data centre (or multiple). Each AZ in a region is geographically separated to ensure High Availability. Regional service: A few services, including Amazon S3 is a regional service. This means it automatically copies data amongst the AZs. Bucket: Storage location for objects in Amazon S3. A bucket exists in only one region. Object: A file in a bucket. Now, to answer your questions: An object exists in one bucket only. An object cannot be split between buckets. (And since a bucket exists i na region, it cannot also be split between regions.) If you wish to replicate objects between regions, use Cross-Region Replication. This will automatically copies objects from one bucket to another. The maximum size of an object in Amazon S3 is 5TB, but you really, really don't want to get that large. Most big data applications use many, smaller files (eg 5MB in size). This allows parallel loading across multiple processes, which is commonly done in Hadoop. It also allows the additional of new data by simply adding files, rather than updating an existing file. (By the way, you cannot append to an S3 object, you can only replace it.) The easiest way to upload data to S3 is by using the AWS Command-Line Interface (CLI). Multi-part uploads are merely a means of uploading a single object by splitting it into multiple parts, uploading each part, then stitching them together. The method of upload is unrelated to the actual objects once they have been uploaded. You should always store your data close to where it is being processed. So, only replicate data between regions if it needs to be processed in multiple regions.
accepted answer of: http://stackoverflow.com/q/50556549
answers question: http://stackoverflow.com/q/50556549

http://stackoverflow.com/q/50649461
score: 0
has comment: http://stackoverflow.com/comment/88309798
answer count: 2
has title: Adjust Figure in Matplotlib
tagged with: python-3.x
has body: I have the following plot which has variable X and Y values. In order to explain the issue I have assigend constant values for X and Y in the code below. I want that the figure coordinates will start from (0,0) and also how can I put the text values(a,b,Sxy,r,R^2) under each other and not next to each other as showen below. Note that I can't use specific values of X,Y because they are variable. So thats why I have to use min() and max() functions as coordinates to show the text values on upper left corner. code: import numpy as np from matplotlib.pyplot import * X = np.arange(0,10,0.1) A = 2 plot(X,X**2+A*X+2,'b-') text(min(X), max(X**2+A*X+2),r'a=12, b=2.09 $S_{xy}$= 0.71 r= 0.9 $R^2$= 0.85',fontsize=12,fontweight='bold') xlabel('X_value') ylabel('Y_value') grid(True) show()
tagged with: python
has answer: http://stackoverflow.com/a/50649591
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50649584
possible better answer: http://stackoverflow.com/a/50649591
has comment: http://stackoverflow.com/comment/88309821
type: Question
has answer: http://stackoverflow.com/a/50649584
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/88309900

http://stackoverflow.com/q/50570062
tagged with: decomposition
type: AnsweredQuestion
score: 1
has title: Pandas time series decomposition based on leap year
upvote count: 1
has answer: http://stackoverflow.com/a/50570379
type: Question
tagged with: time-series
linked to: http://stackoverflow.com/q/31169774
tagged with: pandas
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50570379
duplicate of: http://stackoverflow.com/q/31169774
favorite count: 0
tagged with: python
has body: I have a pandas Time Series (called df) that has one column (with name data) that contains data with a daily frequency over a time period of 5 years. The following code produces some random data: import pandas as pd import numpy as np df_index = pd.date_range('01-01-2012', periods=5 * 365 + 2, freq='D') df = pd.DataFrame({'data': np.random.rand(len(df_index))}, index=df_index) I want to perform a simple yearly trend decomposition, where for each day I subtract its value one year ago. Aditionally, I want to attend leap years in the subtraction. Is there any elegant way to do that? My way to do this is to perform differences with 365 and 366 days and assign them to new columns. df['diff_365'] = df['data'].diff(365) df['diff_366'] = df['data'].diff(366) Afterwards, I apply a function to each row thats selects the right value based on whether the same date from last year is 365 or 366 days ago. def decide(row): if (row.name - 59).is_leap_year: return row[1] else: return row[0] df['yearly_diff'] = df'diff_365', 'diff_366'.apply(decide, axis=1) Explanation: the function decide takes as argument a row from the DataFrame consisting of the columns diff_365 and diff_366 (along with the DatetimeIndex). The expression row.name returns the date of the row and assuming the time series has daily frequency (freq = 'D'), 59 days are subtracted which is the number of days from 1st January to 28th February. Based on whether the resulting date is a day from a leap year, the value from the diff_366 column is returned, otherwise the value from the diff_365 column. This took 8 lines and it feels that the subtraction can be performed in one or two lines. I tried to apply a similiar function directly to the data column (via apply and taking the default argument axis=0). But in this case, I cannot take my DatetimeIndex into account. Is there a better to perform the subtraction?

http://stackoverflow.com/comment/88240887
comment on: http://stackoverflow.com/q/50615396
score: 0
type: QuestionComment
type: Comment
has text: I also used 100 images per each class. Would this be a problem?

http://stackoverflow.com/q/50615482
tagged with: python
duplicate of: http://stackoverflow.com/q/240178
tagged with: list
type: Question
has comment: http://stackoverflow.com/comment/88240888
has answer: http://stackoverflow.com/a/50615500
has title: why does it do this when initializing a 2d list
score: 0
answer count: 1
tagged with: python-3.x
has body: when I initialize an array in python like so and then assign an element to a different value and then print out the 2d list dist = [[0]*3]*3 dist[1][1] = 1 It gives me this [[0,1,0],[0,1,0],[0,1,0]] Can someone explain to me why the whole column has changed instead of just the specific element?
has comment: http://stackoverflow.com/comment/88240893
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/240178

http://stackoverflow.com/q/50575900
tagged with: sqlite
downvote count: 0
favorite count: 0
tagged with: python-3.x
upvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/50576206
type: AnsweredQuestion
score: 2
has title: Pyqt5: Pass a value dynamically in QlineEdit box when event is clicked
tagged with: pyqt5
has answer: http://stackoverflow.com/a/50584775
type: Question
possible better answer: http://stackoverflow.com/a/50584775
has body: In need a pass a result from an event to QlineEdit box(rs_QLineEdit) If the event is clicked by passing the Book name it displays book name and price. There is no problem with database connection as it works well and displays the result in python shell. I want to pass the price dynamically which is to pass m[2] to rs_QLineEdit from PyQt5.QtCore import QRegExp from PyQt5.QtGui import QRegExpValidator from PyQt5 import QtCore, QtGui, QtWidgets import sqlite3 def fetch(nm): store=sqlite3.connect("store.db") book=store.cursor() book.execute("select * from books where title='"+nm+"';") m=book.fetchone() if m==None: print("Book is not Found") else: print("the name is {} ".format(nm)) #The Wings of Fire print(m[2]) #200 store.close() class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(635, 510) self.find = QtWidgets.QPushButton(Form) self.find.setGeometry(QtCore.QRect(370, 200, 93, 28)) self.find.setObjectName("find_button") self.find.setToolTip("Press this") self.name = QtWidgets.QLabel(Form) self.name.setGeometry(QtCore.QRect(100, 200, 55, 16)) self.name.setObjectName("name_label") self.price = QtWidgets.QLabel(Form) self.price.setGeometry(QtCore.QRect(100, 260, 55, 16)) self.price.setObjectName("price_label") self.rs = QtWidgets.QLineEdit(Form) self.rs.setGeometry(QtCore.QRect(230, 260, 55, 16)) self.rs.setObjectName("rs_QLineEdit") self.lineEdit = QtWidgets.QLineEdit(Form) self.lineEdit.setGeometry(QtCore.QRect(220, 200, 113, 22)) self.lineEdit.setObjectName("lineEdit") self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) self.find.clicked.connect(lambda : fetch(str(self.lineEdit.text()))) reg_ex = QRegExp("[0-9]+.?[0-9]{,2}") input_validator = QRegExpValidator(reg_ex, self.rs) self.rs.setValidator(input_validator) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Form")) self.find.setText(_translate("Form", "Find")) self.name.setText(_translate("Form"…
has answer: http://stackoverflow.com/a/50576206
answer count: 2
tagged with: pyqt

http://stackoverflow.com/q/50620564
has body: models.py: class office_list(models.Model): name = models.CharField(max_length= 100) num_of_pax = models.IntegerField() class tg_list(models.Model): name = models.CharField(max_length= 100) num_of_pax = models.IntegerField() How can I check that the office_list name equals to the tg_list name? I want to check if any of the office_list.name == any of the tg_list.name
type: Question
upvote count: 1
has answer: http://stackoverflow.com/a/50620711
possible better answer: http://stackoverflow.com/a/50620678
has answer: http://stackoverflow.com/a/72553347
answer count: 3
has comment: http://stackoverflow.com/comment/88251039
has title: How can I check if two models equal each other in Django?
tagged with: python
favorite count: 0
tagged with: django
has answer: http://stackoverflow.com/a/50620678
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88250986
downvote count: 0
score: 1
tagged with: models
has comment: http://stackoverflow.com/comment/88250950
accepted answer: http://stackoverflow.com/a/50620711

http://stackoverflow.com/q/50688992
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88388539
favorite count: 0
has comment: http://stackoverflow.com/comment/88388022
upvote count: 2
has comment: http://stackoverflow.com/comment/88388740
has comment: http://stackoverflow.com/comment/88387993
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/88388552
has comment: http://stackoverflow.com/comment/88388784
has comment: http://stackoverflow.com/comment/88387922
type: Question
tagged with: rounding
tagged with: algorithm
has answer: http://stackoverflow.com/a/50689944
accepted answer: http://stackoverflow.com/a/50689944
has title: Finding round intervals in a range
has body: Drawing programs such as matplotlib, find n round intervals for the plot axis. For instance, if x is in the range of 0.05 - 0.9, the round numbers in the axis are 0, 0.2, 0.4, 0.6, 0.8, 1.0. My question is: what is the logic for such algorithm (I do not need the code, it can be in any programming language)? We have a range and need to find n round intervals within when we do not know the precision for rounding OR if n intervals can give round values. My thought: Find the closet round value within x% (acceptable padding of the plot) above and below the range. Set n (say between 4-8) to have round intervals between the min and max. If it is a practical approach to do so, I still have no idea how to manage the algorithm for either step.

http://stackoverflow.com/comment/88341412
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50665505
score: 0
has text: @Ollie The Python file (.py) is saved as a file at my Desktop

http://stackoverflow.com/comment/88124215
score: 0
type: AnswerComment
has text: Yes but there is no end to that granularity. As I mentioned, I'm not holding the state of the instances. That architecture is useful for its own use cases but not applicable everywhere. Using a class does neither immediately necessitates a modular design made up of different classes nor OOP has a single implementation paradigm. That's why I am asking for implicit problems. I am quite aware of Java mindset. And that's why I am using Python.
type: Comment
comment on: http://stackoverflow.com/a/50555335

http://stackoverflow.com/q/50678858
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50683611
has title: Python pandas parse table from website does not work
tagged with: web-scraping
tagged with: html-parsing
has comment: http://stackoverflow.com/comment/88367926
type: Question
has comment: http://stackoverflow.com/comment/88368142
has body: I want to extract a table from a website. So I wrote the following code which works for a German weather website: import pandas as pd df, = pd.read_html("https://www.dwd.de/DE/leistungen/beobachtung/beobachtung.html") print(df) Since I was satisfied I tried the same code to the table of the following Russian website: import pandas as pd df= pd.read_html("https://www.ifm.com/ru/ru/category/010/010_010/010_010_020#!/S/DD/DM/1/D/0/F/0/T/24")[0] print(df) But now the output looks kind of strange: {{'LABEL_PRODUCTS' | translate }} \ 0 {{product.product.name}} {{product.description}} 1 {{'ORDER_DETAIL_SUBTOTAL' | translate}}: {{'SHOPPING_CART_QUANTITY' | translate}} \ 0 {{product.quantity}} 1 {{'LABEL_SUM' | translate}} 0 {{product.totalPrice.formattedValue | showPric... 1 NaN [Program finished] Now I don't know why it cannot properly parse for the table content. Is the table too complicated or not tagged properly?
score: 0
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/50683611
has comment: http://stackoverflow.com/comment/88367758
has comment: http://stackoverflow.com/comment/88367701

http://stackoverflow.com/comment/88378492
type: AnswerComment
comment on: http://stackoverflow.com/a/50684032
type: Comment
has text: Actually, `(?x)` is an inline `RegexOptions.IgnorePatternWhitespace` modifier, it provides the same functionality. I'd also add that literal `#` should be escaped in the meaningful parts of the patterns when using this modifier.
score: 1

http://stackoverflow.com/q/50641053
has title: python pandas loc return empty dataframe
favorite count: 0
has comment: http://stackoverflow.com/comment/88292411
accepted answer: http://stackoverflow.com/a/50641227
has answer: http://stackoverflow.com/a/50641478
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88292462
type: AnsweredQuestion
has body: I am trying to get the subset dataframe using the below code: dprev = "eiffel tower" df.loc[df['place'] == dprev] -&gt; returns empty drandom = random.choice(df['place'].unique()) df.loc[df['place'] == drandom] -&gt; returns the subset why am i not seeing the same thing when dprev is string variable?
linked to: http://stackoverflow.com/q/17071871
type: Question
has answer: http://stackoverflow.com/a/50641227
has comment: http://stackoverflow.com/comment/88292594
possible better answer: http://stackoverflow.com/a/50641100
has comment: http://stackoverflow.com/comment/88292201
score: 0
has comment: http://stackoverflow.com/comment/88292431
has answer: http://stackoverflow.com/a/50641100
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/88292479
tagged with: python

http://stackoverflow.com/q/50559252
possible better answer: http://stackoverflow.com/a/50559456
has comment: http://stackoverflow.com/comment/88129027
has title: Python While true, Try/Except, returning value
linked to: http://stackoverflow.com/q/19158339
tagged with: return
has body: When I try to return a value after making a variable and putting a while True, try/except commands, the variable doesn't return the value. I am trying to globalize this "starting" so that it can be used. def start_time(): while True: try: starting = int(input("Please enter a starting hour(HH): ")) if starting &lt; 0: print("There are no negative hours!") elif starting &gt; 24: print("There are only 24 hours in a day!") else: break except ValueError: print("Please enter in a correct format (HH)") return starting def end_time(): while True: try: ending = int(input("Please enter an ending hour (HH): ")) if ending &lt; starting: print("You can only plan a day!") elif ending &lt; 0: print("There are only 24 hours in a day!") elif ending &gt; 24: print("There are only 24 hours in a day!") else: break except ValueError: print("Please enter in a correct format (HH)") return ending #obtain starting and ending time start_time() end_time() #confirm starting and ending time Thanks
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50559306
type: Question
score: 0
answer count: 2
tagged with: try-except
has answer: http://stackoverflow.com/a/50559456
tagged with: while-loop
accepted answer: http://stackoverflow.com/a/50559306
tagged with: python
tagged with: global

http://stackoverflow.com/a/50610170
has comment: http://stackoverflow.com/comment/88234833
upvote count: 1
answers question: http://stackoverflow.com/q/50608568
score: 1
has comment: http://stackoverflow.com/comment/88235038
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88230934
downvote count: 0
has comment: http://stackoverflow.com/comment/88237153
has body: Your code needs a lot of refactoring, but lets give it a try: # Keep doing this while we have movies to click while len(driver.find_element_by_class_name('movies-list--large-item')): # This will iterate through each movie for movie in driver.find_element_by_class_name('movies-list--large-item'): # Now get the button to see the movie details movie.find_element_by_class_name('cineplanet-icon_more').click() # Once you are in the movie details view do an assertion # Go back in the browser to the previous page driver.back() # If you reach this it means that you clicked all the movies in the current view # So click the View more movies button to go to the next page driver.find_element_by_css_selector('.movies-list--view-more-button-wrapper .call-to-action--text') A couple of extra things that I noticed in your code: - Do not use time.sleep(5) is unreliable. Use Webdriver waits and expected conditions to wait for elements to be present: http://selenium-python.readthedocs.io/waits.html Do not use Xpaths, its also unreliable. Use ID's if possible or class names Surface your exceptions, you are doing: except: pass that way you wont know when your code fails Organize your code in a Test Suite approach, maybe consider using Unittest2 for python Hope it helps!
accepted answer of: http://stackoverflow.com/q/50608568
type: Answer
has comment: http://stackoverflow.com/comment/88231688
has comment: http://stackoverflow.com/comment/88233101

http://stackoverflow.com/q/50580700
score: 1
type: Question
upvote count: 1
answer count: 1
favorite count: 0
tagged with: dxf
type: UnansweredQuestion
has title: Understanding DXF file format. Relation between Label and Geometry
tagged with: python
has comment: http://stackoverflow.com/comment/88310232
has answer: http://stackoverflow.com/a/50649721
has body: I'm very new to CAD system and trying to extract information from dxf file for my project. I have dxf files for floor plan. My aim is to extract geometries for the room and label associated with it. Though i was able to extract room geometries and room labels separately, but i'm finding it hard to map the both. Is there a tag that i've missed that has link between geometry and labels? Room Label: 0 INSERT 5 53CF 330 2 100 AcDbEntity 8 __X_Polyline_Data 100 AcDbBlockReference 66 1 2 ROOM_DATA 10 11.15367175915704 20 10.40315868785525 30 0.0 1001 AEC_XDATA_BOUND_SPACE 1070 100 1070 1 0 ATTRIB 5 53D1 330 53CF 100 AcDbEntity 8 __X_Polyline_Data 6 Continuous 100 AcDbText 10 11.12027175915704 20 10.44215868785524 30 0.0 40 0.25 1 AE.22 100 AcDbAttribute 280 0 2 PART_AOID 70 0 280 1 Room Text : 0 TEXT 5 62C 330 2 100 AcDbEntity 8 X_Raumnummer 370 0 100 AcDbText 10 11.15367175915704 20 10.40315868785525 30 0.0 40 0.8 1 AE.22 Room Coordinates : 0 LWPOLYLINE 5 239B 330 2 100 AcDbEntity 8 A_DEC_Durchbrüche 370 0 100 AcDbPolyline 90 4 70 1 43 0.0 10 10.95 20 12.215 10 14.6 20 12.215 10 14.6 20 12.48499999999999 10 10.95 20 12.48499999999999 Code that i've written to extract the data: lines = [entity for entity in dwg.entities if entity.dxftype == 'LWPOLYLINE'] room_lines = [entity for entity in lines if entity.layer == '__X_Polyline'] lines_data = [entity for entity in dwg.entities if entity.dxftype == 'TEXT'] room_text = [entity for entity in lines_data if entity.layer == 'X_Raumnummer'] I've used dxfgrabber library to extract information. I'm sorry if my question is stupid, I'm not able to find the link and i'm fairly new to this field. I was able to extract AE.22 and it's 4 coordinates, but now able to map them together.
downvote count: 0

http://stackoverflow.com/comment/88225584
type: QuestionComment
comment on: http://stackoverflow.com/q/50607804
score: 1
has text: Once you run your converter on the two inputs, one of them should match the output and the other shouldn't. So just keep the one that doesn't match the sanitized output.
type: Comment

http://stackoverflow.com/a/50650878
answers question: http://stackoverflow.com/q/50650704
upvote count: 22
has comment: http://stackoverflow.com/comment/91084755
has body: The timestamp method was added in Python 3.3. So if you're using Python 2.0, or even 2.7, you don't have it. There are backports of current datetime to older Python versions on PyPI, but none of them seems to be official, or up-to-date; you might want to try searching for yourself. There are also a number of third-party replacement libraries that add functionality that isn't in (2.x) datetime, including the ability to convert to Unix timestamps. You can just copy the function out of the source code from 3.3 or later: def timestamp(self): "Return POSIX timestamp as float" if self._tzinfo is None: s = self._mktime() return s + self.microsecond / 1e6 else: return (self - _EPOCH).total_seconds() … but you will have to modify things a bit to get them to work, because: _EPOCH is deleted at the end of the module. The 3.x _EPOCH is a tz-aware object built with a proper UTC timezone, which you don't have in 2.x unless you're using a third-party library like pytz. The _mktime method and _tzinfo attribute don't exist on 2.x datetime, so you need to simulate what they do as well. If you don't need the same function to work equally well for naive, GMT, and tz-aware datetimes, it won't be that hard, but it's still not quite trivial—and if you do need the full functionality, it's going to be more painful. Or it may be easier to port the equivalent code given in the docs. For aware datetime instances: (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds() Of course you still don't have that timezone.utc, but for this purpose, you don't need a full timezone object; you can use an instance of the example UTC class in the 2.x tzinfo docs. … for naive: timestamp = dt.replace(tzinfo=timezone.utc).timestamp() … or: timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1) Since you don't have aware datetimes, that last one is all you need. If your Python is old enough, timedelta may not have a __div__ method. In that case (if you haven't found a backport), you have to do d…
type: Answer
score: 21
has comment: http://stackoverflow.com/comment/91084878
downvote count: 1
has comment: http://stackoverflow.com/comment/91099220

http://stackoverflow.com/comment/88342680
has text: Are you sure your data is in the correct order? (Long Jump second?)
score: 1
comment on: http://stackoverflow.com/q/50666057
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50549757
has comment: http://stackoverflow.com/comment/88110532
type: UnansweredQuestion
score: 3
tagged with: python
answer count: 0
upvote count: 3
has title: how to run python script through mininet host without mistakes?
has comment: http://stackoverflow.com/comment/88199622
type: Question
tagged with: mininet
tagged with: ubuntu
tagged with: ryu
downvote count: 0
has body: I have a problem running python script via host command inside the Mininet topology code. I want run HTTPServer.py on h1 and host.py on other hosts, so that they can send HTTP requests to h1. The following is my code ...Build a mininet topology... h1 = net.get('h1') h1.cmd('python HTTPServer.py &amp;') for i in ... ho = net.get('h%s' % i) ho.cmd('python host.py &amp;') The Mininet executed without errors and it is running these scripts. But after for a while, it does not seem to be running. But if I run HTTPServer.py and host.py through hosts via xterm, they can run without mistakes. I don't why they do like this.
has comment: http://stackoverflow.com/comment/88110579
favorite count: 0
tagged with: linux

http://stackoverflow.com/q/50597966
has comment: http://stackoverflow.com/comment/95087468
favorite count: 0
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/95187171
upvote count: 1
has title: Zookeeper server health check/monitor using python kazoo client
has body: I have a python script to monitor the Zookeeper server health check - basically check if Zookeeper is up and running. This runs every minute. So I have just written a simple python method which will create a new zookeeper kazoo client and then start and stop the client. def __zookeeper_check(self): self.__logger.debug('inside the Healthcheck.__zookeeperCheck') try: zk = KazooClient(os.environ['ZOO_SERVERS']) zk.start() self.__logger.debug('Connected to Zookeeper') output = 0 zk.stop() except Exception: self.__logger.error(traceback.format_exc()) output = 1 return output Is this the right way to do it? Obviously, it's working fine in my local environment, but considering when this goes into the live production environment, it should not cause some performance issue or break anything else considering that other zookeeper clients would also be actively connected to the same Zookeeper server.
type: Question
tagged with: apache-zookeeper
downvote count: 0
tagged with: kazoo
score: 1

http://stackoverflow.com/a/50655665
type: Answer
has body: Your attempt was close. You should change '{creation_time}, {filter_time}, {total_time}'.format(test) to '{test.creation_time}, {test.filter_time}, {test.total_time}'.format(test=test)
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50655608
downvote count: 0

http://stackoverflow.com/comment/88407671
has text: @SvenFestersen , thks for your suggestion I updated the code, could you check please ?
score: 0
comment on: http://stackoverflow.com/q/50697969
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88194558
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50592552
type: Comment
has text: I'm thinking using two for loop to check the pixel element, but I got 5,000 images like this, will it be to slow to do it in this way?

http://stackoverflow.com/a/50546003
has body: To help the algorithm find the right direction, you need to separate your constraints: def f(params): print(params) x, z = params if abs(x - 15) &lt; 2 and abs(z + 10) &lt; 2: return -9999999 return (x - 15) ** 2 + (z + 10) ** 2 * numpy.sqrt(numpy.abs(numpy.sin(x))) # Last: 15.00024144, -9.99939634 result = optimize.minimize(f, (-15, -15), bounds=((-15.01, 15.01,), (-15.01, 15.01,),), method="SLSQP", options={'disp':True, 'maxiter': 1024 * 1024}, jac=False, constraints=({ 'type': 'ineq', 'fun': lambda params : abs(params[0] - 15) -2, }, { 'type': 'ineq', 'fun': lambda params : abs(params[1] + 10) -2, },) ) print(result) print(f(result.x)) Gives: Optimization terminated successfully. (Exit mode 0) Current function value: 6.5928117149596535 Iterations: 6 Function evaluations: 24 Gradient evaluations: 6 fun: 6.5928117149596535 jac: array([-1.2001152, 2.5928117]) message: 'Optimization terminated successfully.' nfev: 24 nit: 6 njev: 6 status: 0 success: True x: array([13., -8.]) [13. -8.] 6.5928117149596535 Bingo!
has comment: http://stackoverflow.com/comment/88105426
type: Answer
accepted answer of: http://stackoverflow.com/q/50545630
score: 4
answers question: http://stackoverflow.com/q/50545630
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50659994
has answer: http://stackoverflow.com/a/50660813
has title: Do I understand well the use of word embedding for instance with logistic regression?
tagged with: deep-learning
downvote count: 0
answer count: 1
tagged with: scikit-learn
tagged with: nlp
favorite count: 0
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
score: 3
upvote count: 3
type: Question
has body: I wonder if I understood correctly the idea of using word embedding in natural language processing. I want to show you how I perceive it and ask whether my interpretation is correct. Let's assume that we want to predict whether sentence is positive or negative. We will use a pre-trained word embedding prepared on a very large text corpus with dimension equals 100. It means that for each word we have 100 values. Our file looks in this way: ... new -0.68538535 -0.08992791 0.8066535 other 97 values ... man -0.6401568 -0.05007627 0.65864474 ... many 0.18335487 -0.10728102 0.468635 ... doesnt 0.0694685 -0.4131108 0.0052553082 ... ... Obviously we have test and train set. We will use sklearn model to fit and predict results. Our train set looks in this way: 1 This is positive and very amazing sentence. 0 I feel very sad. And test set contains sentences like: In my opinion people are amazing. I have mainly doubts related to the preprocessing of input data. I wonder whether it should be done in this way: We do for all sentences for instance tokenization, removing of stop words, lowercasing etc. So for our example we get: 'this', 'is', 'positive', 'very', 'amazing', 'sentence' 'i', 'feel', 'very', 'sad' 'in', 'my', 'opinion', 'people', 'amazing' We use pad_sequences: 1,2,3,4,5,6 7,8,4,9 10,11,12,13,5 Furthermore we check the length of the longest sentence in both train set and test set. Let's assume that in our case the maximum length is equals to 10. We need to have all vectors of the same length so we fill the remaining fields with zeros. 1,2,3,4,5,0,0,0,0,0 6,7,4,8,0,0,0,0,0,0 10,11,12,13,5,0,0,0,0,0 Now the biggest doubt - we assign values from our word embedding word2vec file to all words from the prepared vectors from the training set and the test set. Our word embedding word2vec file looks like this: ... in -0.039903056 0.46479827 0.2576446 ... ... opinion 0.237968 0.17199863 -0.23182874... ... people 0.2037858 -0.29881874 0.12108547 ... ... amazing 0.20736384 0.22415…
has comment: http://stackoverflow.com/comment/88357346

http://stackoverflow.com/q/50582390
has title: Map different values in range intervals
has comment: http://stackoverflow.com/comment/88175835
has body: I have the following dataframe: df_data = pd.DataFrame({'Time_0': [5, 5, 5], 'Time_1': [8, 10, 12], 'Values': [10.0, 15.0, 20.0]}) I need to distribute the Values into a new cash flow dataframe, in every row within the time_0 and time_1 intervals. I currently have it mapped into one row: df_CF = pd.DataFrame({'Values': [0.0 for n in (range(0, 16))], 'Months': range(0, 16)}) df_CF['Values'] = df_CF['Months'].map(df_data.set_index('Time_1')['Values']).fillna(value=0) However, I'm not quite sure how I can extend it to the whole range. The output should be: **Time Values** 0 0 1 0 2 0 3 0 4 0 5 45 6 45 7 45 8 45 9 35 10 35 11 20 12 20 13 0 14 0 15 0 16 0
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/88175881
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88181855
has answer: http://stackoverflow.com/a/50583650
accepted answer: http://stackoverflow.com/a/50583650
type: Question

http://stackoverflow.com/a/50549801
upvote count: 1
has comment: http://stackoverflow.com/comment/88127036
answers question: http://stackoverflow.com/q/50549742
has body: you can append the username into a list then use collection.counter to get the count: from collections import Counter usernamelist = [] usernamelist.append('tom') usernamelist.append('tom') usernamelist.append('tom') usernamelist.append('sam') usernamelist.append('louis') c = Counter(usernamelist) list_of_user_more_than_one = [i for i in c if c[i] &gt; 1] print(list_of_user_more_than_one) ---&gt;['tom']
downvote count: 0
has comment: http://stackoverflow.com/comment/88110444
has comment: http://stackoverflow.com/comment/88110776
type: Answer
has comment: http://stackoverflow.com/comment/88110773
score: 1
has comment: http://stackoverflow.com/comment/88126982

http://stackoverflow.com/q/50694739
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/88398995
favorite count: 0
has comment: http://stackoverflow.com/comment/88399627
has title: Dividing pairs of data frame rows by common names
tagged with: python
type: AnsweredQuestion
has body: I have a dataframe which looks like that: 1 2 a_value 2 8 a_ref 4 2 b_value 6 10 b_ref 3 15 c_value 7 3 note that some indices are pairs of name_value and name_ref and others are not I want to find those pairs, and for each pair get four rows in my new dataframe: name_value, name_ref, name_ref/name_value, name_value/name_ref so my output dataframe looks like this: 1 2 a_value 2.0 8.000 a_ref 4.0 2.000 a_value/a_ref 0.5 4.000 a_ref/a_value 2.0 0.250 b_value 6.0 10.000 b_ref 3.0 15.000 b_value/b_ref 2.0 0.666 b_ref/b_value 0.5 1.500 I currently do it by iterating over the indices looking for ones that end with value and then trying to find the matching ref, but knowing pandas, it seems that there should be an easier way, maybe using groupby somehow. So.. is there?
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50695018
accepted answer: http://stackoverflow.com/a/50695018
score: 0

http://stackoverflow.com/q/50577454
downvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50577932
upvote count: 0
has answer: http://stackoverflow.com/a/50577932
tagged with: node.js
type: AnsweredQuestion
has body: Currently built a python program that gathers data. I have a set of data, but my web application will run NodeJS for the backend. How do I display the data collected into my NodeJS application? Thanks.
has title: I have a python program, but how can I display the data onto a NodeJS based web application?
score: -1
type: Question
answer count: 1
favorite count: 0

http://stackoverflow.com/q/50610739
upvote count: 3
possible better answer: http://stackoverflow.com/a/50611077
has title: substitute all numbers in a matrix with equivalent letters when Na exists
has answer: http://stackoverflow.com/a/50611077
type: Question
has comment: http://stackoverflow.com/comment/88271713
has answer: http://stackoverflow.com/a/50610968
has comment: http://stackoverflow.com/comment/88231792
has answer: http://stackoverflow.com/a/50611135
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/88231509
downvote count: 0
tagged with: string
tagged with: sequence
favorite count: 0
has comment: http://stackoverflow.com/comment/88231747
accepted answer: http://stackoverflow.com/a/50610968
tagged with: python
has comment: http://stackoverflow.com/comment/88231505
type: AnsweredQuestion
has body: There is a huge matrix whose elements are numbers in the range of 1 to 15. I want to transform the matrix to the one whose elements be letters such that 1 becomes "a", 2 becomes "b", and so on. Finally I want to merge each row and create a sequence of it. As a simple example: import pandas as pd import numpy as np, numpy.random numpy.random.seed(1) A = pd.DataFrame (np.random.randint(1,16,10).reshape(2,5)) A.iloc[1,4]= np.NAN A # 0 1 2 3 4 #0 6 12 13 9 10.0 #1 12 6 1 1 NaN If there were no Na in the dataset, I would use this code: pd.DataFrame(list(map(''.join, A.applymap(lambda n: chr(n + 96)).as_matrix()))) Here, it gives this error: TypeError: ('integer argument expected, got float', 'occurred at index 4') The expected output is: 0 0 flmij 1 lfaa The first row should have 5 elements and the second one should have 4 elements.
score: 3

http://stackoverflow.com/comment/94161411
type: AnswerComment
score: 5
type: Comment
has text: or using `PyList_Append`, this could be : `PyObject *list = PyList_New(0); iterate through the array/list; PyList_Append(list, PyFloat_FromDouble(element)); return list;`
comment on: http://stackoverflow.com/a/50683462

http://stackoverflow.com/comment/88358027
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50668767
has text: PhantomJS works for me with Selenium v3.12.0 on Python 2.7. If you want to use the headless chrome browser, that's also fine. https://intoli.com/blog/running-selenium-with-headless-chrome/

o-d-matrix
tags question: http://stackoverflow.com/q/50656955
tag name: o-d-matrix
type: Tag

psutil
tags question: http://stackoverflow.com/q/50671671
tags question: http://stackoverflow.com/q/50647469
type: Tag
tag name: psutil

http://stackoverflow.com/q/50589937
linked to: http://stackoverflow.com/q/604939
answer count: 0
type: UnansweredQuestion
score: 2
tagged with: sqlite
has comment: http://stackoverflow.com/comment/88189226
downvote count: 0
favorite count: 0
type: Question
upvote count: 2
has body: I have a table in sqlite3 CREATE TABLE exhibit( id INTEGER PRIMARY KEY, name TEXT NOT NULL, text1 TEXT NOT NULL, text2 TEXT, text3 TEXT, photo TEXT, audio TEXT, video TEXT, location TEXT NOT NULL); And I have this code for getting types and names of columns: def get_columns(obj): con = sqlite3.connect('mydatabase.db') with con: cur = con.cursor() obj.__str__ sql_req = 'PRAGMA table_info('+obj+');' cur.execute(sql_req) data = cur.fetchall() result1 = [] result2 = [] for d in data: result1.append(d[1]) result2.append(d[2]) result = [] result.append(result1) result.append(result2) #print(result) if len(result1)&gt;0: return(1, result) But in my program I need to know if the type is "NOT NULL" or not. How can I get it? I`m a newcomer in programing and I have no idea:( Please, help
has title: How to get 'NOT NULL' from sqlite3
tagged with: python

http://stackoverflow.com/a/50570165
has body: Just run the script in a background thread, and make sure you update the GUI back on the FX Application Thread, either using Platform.runLater(...) or by encapsulating the command as a Task and using the setOnSucceeded handler. The best practice here is to use an ExecutorService to manage the threads. For example: private final ExecutorService exec = Executors.newCachedThreadPool(); public void launchCommand(String inputDir, String outputDir) { String command = ".\\venv\\Scripts\\python.exe ./test.py -i " + inputDir + " -o " + outputDir; Task&lt;String&gt; commandTask = new Task&lt;String&gt;() { @Override protected String call() { return executeCommand(command); } }; commandTask.setOnSucceeded(event -&gt; { // this is executed on the FX Application Thread, // so it is safe to update the UI here if you need System.out.println(commandTask.getValue()); }); commandTask.setOnFailed(event -&gt; { commandTask.getException().printStackTrace(); }); exec.execute(commandTask); }
downvote count: 0
has comment: http://stackoverflow.com/comment/88151549
has comment: http://stackoverflow.com/comment/88151218
has comment: http://stackoverflow.com/comment/88151339
answers question: http://stackoverflow.com/q/50569970
has comment: http://stackoverflow.com/comment/88150556
has comment: http://stackoverflow.com/comment/88150637
type: Answer
has comment: http://stackoverflow.com/comment/88151161
upvote count: 2
has comment: http://stackoverflow.com/comment/88151180
has comment: http://stackoverflow.com/comment/88151631
has comment: http://stackoverflow.com/comment/88151366
score: 2

http://stackoverflow.com/q/50678549
tagged with: django-rest-framework
has body: I am trying to create a custom JSON in Django rest framework. (The method used is serializers.ModelSerializer). I am not sure what approach is taken to achieve this. Logic: Check for some data in a model and based on that data further calculation is done over another model. This will go on un till desired output is obtained. How do I setup my serializer and viewset. class DataPointSerializer(serializers.ModelSerializer): class Meta: model = DataPoint fileds = (what goes here ?) def to_representation(self,instance): model_one = model_one.objects.all() calculation using model_one model_two.objects.filter(by calculated data) construct JSON return JSON I would like to know the approach that would take to accomplish this task. TK-01 `def get_representation(self,instance): data = [] Shifts = Shift.objects.all() for shift in Shifts: data.append(shift.shift_name) return data` TK-02 I'm trying to create something like this Link but instead of APIView I need it in serializers
has comment: http://stackoverflow.com/comment/88370036
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88390624
type: UnansweredQuestion
type: Question
tagged with: django-models
has answer: http://stackoverflow.com/a/50678701
has title: Django Rest - Custom JSON based on applied logic
score: 0
answer count: 1

http://stackoverflow.com/a/50573539
has comment: http://stackoverflow.com/comment/88158105
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/88158057
answers question: http://stackoverflow.com/q/50571592
has comment: http://stackoverflow.com/comment/127253192
downvote count: 0
has body: Seaborn uses a FixedLocator and a FixedFormatter. If you unilaterally change the formatter, it is expected that the results become useless. If the motivation to use a Formatter is to keep the fixed labels, but change the number of decimal places, an easy solution could be to reformat the present labels. def fmt(s): try: n = "{:.2f}".format(float(s)) except: n = "" return n ax.set_xticklabels([fmt(label.get_text()) for label in ax.get_xticklabels()])
type: Answer

http://stackoverflow.com/q/50595638
answer count: 0
downvote count: 0
linked to: http://stackoverflow.com/q/43592879
type: UnansweredQuestion
score: 1
tagged with: tensorflow
type: Question
tagged with: anaconda
has body: I have installed tensorflow 1.5.0 on my machine using conda. I created an environment named py35 with python 3.5 and installed tensorflow 1.0.0 in it. now in py35 env when I import tensorflow in spyder it is importing 1.5.0, not 1.0.0. In terminal it is importing correct version of tensorflow. this is kind of weird. I am new to this so maybe I am doing a noob mistake somewhere. if anyone can help me with this it would be great. I am checking verson by: import tensorflow print(tensorflow.__version__)
has comment: http://stackoverflow.com/comment/88215057
has title: importing wrong version of tensorflow
upvote count: 1
has comment: http://stackoverflow.com/comment/88200481
favorite count: 0
has comment: http://stackoverflow.com/comment/88203187
tagged with: spyder
tagged with: python

http://stackoverflow.com/q/50555569
answer count: 1
tagged with: python-3.x
has title: discord.py client.say @user only using ctx argument
has answer: http://stackoverflow.com/a/50555682
tagged with: python
has body: Using: @client.command(pass_context=True) async def bla(ctx): I want to add a await client.say that could @ the user. I have been trying to use the (ctx.message.author)) but the I only got this printed in the Discord server: click here Code used in image above: await client.say("Bla bla bla! @{}".format(ctx.message.author)) I don't want to add another argument to the async def bla(ctx):
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50555682
score: 0
type: Question
tagged with: discord.py

http://stackoverflow.com/a/58351515
has body: I followed a suggestion from https://github.com/microsoft/LightGBM/issues/586, however it did not solved my problem. It turned out that the path to libnvidia-opencl.so was not aware by LightGBM library. So I modified the path to libnvidia-opencl.so.1, in my case, into /usr/lib/x86_64-linux-gnu/libnvidia-opencl.so.1. Then it worked. A one-line solution is: mkdir -p /etc/OpenCL/vendors &amp;&amp; \ echo "/usr/lib/x86_64-linux-gnu/libnvidia-opencl.so.1" &gt; /etc/OpenCL/vendors/nvidia.icd Of course you have to make sure Nvidia driver is properly installed. For Ubuntu 18.04, you can follow this instruction https://www.linuxbabe.com/ubuntu/install-nvidia-driver-ubuntu-18-04
downvote count: 0
answers question: http://stackoverflow.com/q/50627963
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/a/50661799
type: Answer
has comment: http://stackoverflow.com/comment/88334063
answers question: http://stackoverflow.com/q/50661733
score: 0
has body: note that I would just make a set seen and add each index to that. def list_jump(jumps): i = 0 seen = {0} while True: try: i += jumps[i] if i &lt; 0: # negative indices are legal, but we should exit if we have one. return "out-of-bounds" except IndexError: # we've escaped the list: non-cyclic! return "out-of-bounds" else: if i in seen: return "cycle" else: seen.add(i)

http://stackoverflow.com/comment/88187218
has text: this is the error that happens in try, except `ValueError: could not convert string to float: '90.09.'` this is because `x=90.09'` and `s='90.09.'` and when you do `float('90.09.')` it fails as there is an extra `.` which you have added for some reason.
comment on: http://stackoverflow.com/q/50588852
score: 0
type: Comment
type: QuestionComment

weblate
tag name: weblate
type: Tag
tags question: http://stackoverflow.com/q/50627667

http://stackoverflow.com/a/50632737
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: You can do something like this: &gt;&gt;&gt; newDoc = [' '.join(word for word in sentence.split() if len(word) &gt;= 3) for sentence in train_pos] &gt;&gt;&gt; newDoc ['like apples', 'apples are favorite fruits']
accepted answer of: http://stackoverflow.com/q/50632664
type: Answer
answers question: http://stackoverflow.com/q/50632664
score: 2

http://stackoverflow.com/q/50685530
has answer: http://stackoverflow.com/a/50685614
has comment: http://stackoverflow.com/comment/88380814
upvote count: 3
type: UnansweredQuestion
downvote count: 2
tagged with: python
has body: So I want to send my python script to another computer, nonetheless, it doesn't have the same package installed on it. Is there any way to send the whole python code as a folder which will also include all that packages? ( I have tried creating a virtual environment through the problem relies on the fact that a lot of the code in the virtual environment is made of aliased files which might not exist on the other computer). Thank you very much in advance for your help.
has comment: http://stackoverflow.com/comment/88381101
score: 1
has comment: http://stackoverflow.com/comment/88380828
has comment: http://stackoverflow.com/comment/88381165
has title: How to properly send Python code?
type: Question
has comment: http://stackoverflow.com/comment/88381452
answer count: 2
tagged with: file-transfer
tagged with: virtualenv
has answer: http://stackoverflow.com/a/50685571
favorite count: 0
linked to: http://stackoverflow.com/q/5458048

http://stackoverflow.com/q/50690826
tagged with: conditional-statements
has answer: http://stackoverflow.com/a/50690862
type: UnansweredQuestion
has body: I am writing a program where i need to check if 2 of these 4 booleans are true. Obviously i can write out every combination in an if statement, which is easy enough for 4 (alltho a pain). However, if the problem has 100 variables, and needs to know if at least 2 are true, now we have a much bigger problem. Is there a simpler solution to this? Is there a module that can do this for me? What if i want at least x to be true?
score: 1
has title: Is there an efficient way to write if x of these variables are true in Python?
type: Question
tagged with: python
tagged with: module
favorite count: 0
has comment: http://stackoverflow.com/comment/88391442
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/88391473
downvote count: 1
has comment: http://stackoverflow.com/comment/88392231
has answer: http://stackoverflow.com/a/50690871

http://stackoverflow.com/q/50545386
favorite count: 0
linked to: http://stackoverflow.com/q/38758708
has answer: http://stackoverflow.com/a/50545420
possible better answer: http://stackoverflow.com/a/50545782
tagged with: python
has body: I want to multiply each of the first 9 items in listA by the first item in ListB, then the next group of 9 items in ListA by the second item in listB, and so on through ListA. So far, I have the following but it does not work -- newlist contains only one group of 9 items (it should be 12 groups of 9 items). k = 0 n = 0 for i, factor in enumerate(listA[k:k+9]): newlist.append(factor * ListB[n]) k += 9 n += 1
type: AnsweredQuestion
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/50545448
type: Question
has answer: http://stackoverflow.com/a/50545522
has title: Iterating through groups in List A and multiplying by item in List B
accepted answer: http://stackoverflow.com/a/50545448
downvote count: 0
answer count: 6
has answer: http://stackoverflow.com/a/50545525
has answer: http://stackoverflow.com/a/50545689
has answer: http://stackoverflow.com/a/50545782

http://stackoverflow.com/a/50596846
type: Answer
accepted answer of: http://stackoverflow.com/q/50584236
has body: Instead of passing the whole Storage object to compare(), you should access a_year in form01, a_month in form02 and a_day in form03 objects like form01.a_year, form2.a_month or form3.a_day So your function call should look something like greeting = "Your result from app02 is %s" % (new5.compare(form01.a_year, form02.a_month, form03.a_day)) Also, note this from the docs Note that the web.input() values will be strings even if there are numbers passed to it. so you'll need to typecast your web.input from string to the required type(here int) like so if int(a) - 3 == 8:
answers question: http://stackoverflow.com/q/50584236
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88322755

http://stackoverflow.com/q/50598063
type: UnansweredQuestion
has body: class node: def __init__(self,data): self.data=data self.nextNode=None def remove(self,data,previousNode): if self.data == data: previousNode.nextNode=self.nextNode del self.data del self.nextNode else: if self.nextNode is not None: self.nextNode.remove(data,self)
tagged with: python
has answer: http://stackoverflow.com/a/50598661
score: 0
has comment: http://stackoverflow.com/comment/88205343
type: Question
has title: can somebody explain how self.nextNode.remove(data,self) call remove() method?
tagged with: data-structures
answer count: 1

http://stackoverflow.com/a/50661017
accepted answer of: http://stackoverflow.com/q/50659758
upvote count: 1
type: AcceptedAnswer
has body: I tried to recreate what you want to do. Try it: import sys from PyQt5 import QtWidgets, QtGui, QtCore class Window(QtWidgets.QWidget): def __init__(self, parent=None): super(Window, self).__init__(parent) self.lineEditTotalPDFnumber = QtWidgets.QLineEdit('QLineEdit') self.lineEditTotalPDFnumber.setReadOnly(True) self.listWidgetPDFlist = QtWidgets.QListWidget() self.vlayout = QtWidgets.QVBoxLayout() self.vlayout.addWidget(self.listWidgetPDFlist) self.vlayout.addWidget(self.lineEditTotalPDFnumber) self.btnAddItems = QtWidgets.QPushButton() self.btnAddItems.setText('add items') self.vlayout.addWidget(self.btnAddItems) self.btnAddItems.clicked.connect(self.addItems) self.btnPrintItems = QtWidgets.QPushButton() self.btnPrintItems.setText('print the total number of checked items') self.vlayout.addWidget(self.btnPrintItems) self.btnPrintItems.clicked.connect(self.printItems) self.setLayout(self.vlayout) def addItems(self): Files = ["file1", "file2", "file3",] print("\nFiles ", Files) self.ListFilesInViewer(Files) def ListFilesInViewer(self, Files): for item1 in Files: item = QtWidgets.QListWidgetItem(item1) print("\titem =",item) item.setCheckState(QtCore.Qt.Unchecked) #Unchecked item.setText('`{}` - QListWidget item № `{}`'.format(str(item1), str(self.listWidgetPDFlist.count()))) self.listWidgetPDFlist.addItem(item) # listWidgetPDFlist def printItems(self): checkedItem = 0 for index in range(self.listWidgetPDFlist.count()): if self.listWidgetPDFlist.item(index).checkState() == QtCore.Qt.Checked: print("checked item ==&gt;{}, index={}".format(self.listWidgetPDFlist.item(index), index)) checkedItem += 1 self.lineEditTotalPDFnumber.setText("checked items --&gt; {}".format(str(checkedItem))) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) window = Window() window.resize(500, 400) window.show() sys.exit(app.exec_())
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50659758

http://stackoverflow.com/a/50658992
score: 0
answers question: http://stackoverflow.com/q/50658705
type: Answer
has body: Problem solved. Apparently reloading UWSGI (= to serve Flask with Nginx) wasn't done properly and didn't pick up code changes. After restart it worked and the path variable worked. The html file I was using had a form. As I didn't passed a variable within the route that points to a form function, it didn't render the page. After swapping it with a minimal HTML file to test, it worked.

http://stackoverflow.com/a/50547895
upvote count: 4
answers question: http://stackoverflow.com/q/50547593
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50547593
has body: The problem in your case is that you must activate both properties with the operator | self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint) Complete code: import sys from PyQt5.QtCore import Qt, QPoint from PyQt5.QtGui import QFont from PyQt5.QtWidgets import QApplication, QLabel, QStyle class Invisible(QLabel): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__press_pos = QPoint() self.initUI() def initUI(self): self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint) self.setAttribute(Qt.WA_TranslucentBackground) self.setText("Drag me...") self.setFont(QFont("Times", 50, QFont.Bold)) self.adjustSize() self.setGeometry( QStyle.alignedRect( Qt.LeftToRight, Qt.AlignCenter, self.size(), QApplication.instance().desktop().availableGeometry() ) ) def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.__press_pos = event.pos() def mouseReleaseEvent(self, event): if event.button() == Qt.LeftButton: self.__press_pos = QPoint() def mouseMoveEvent(self, event): if not self.__press_pos.isNull(): self.move(self.pos() + (event.pos() - self.__press_pos)) def main(): app = QApplication(sys.argv) w = Invisible() w.show() return app.exec_() if __name__ == '__main__': sys.exit(main()) setMask() serves to give a different border to the widget, for example for an example I got the following:
has comment: http://stackoverflow.com/comment/88106496
score: 4

http://stackoverflow.com/q/50637863
linked to: http://stackoverflow.com/q/11964130
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50639183
tagged with: python-internals
has body: At first, I want to test the memory usage between generator and list-comprehension.The book give me a little bench code snippet and I run it on my PC(python3.6, Windows),find something unexpected. On the book, it said, because list-comprehension has to create a real list and allocate memory for it, itering from a list-comprehension must be slower than itering from a generator. Ofcourse, list-comprehension use more memory than generator. FOllowing is my code,which is not satisfy previous opinion(within sum function). import tracemalloc from time import time def timeIt(func): start = time() func() print('%s use time' % func.__name__, time() - start) return func tracemalloc.start() numbers = range(1, 1000000) @timeIt def lStyle(): return sum([i for i in numbers if i % 3 == 0]) @timeIt def gStyle(): return sum((i for i in numbers if i % 3 == 0)) lStyle() gStyle() shouldSize = [i for i in numbers if i % 3 == 0] snapshotL = tracemalloc.take_snapshot() top_stats = snapshotL.statistics('lineno') print("[ Top 10 ]") for stat in top_stats[:10]: print(stat) The output: lStyle use time 0.4460000991821289 gStyle use time 0.6190001964569092 [ Top 10 ] F:/py3proj/play.py:31: size=11.5 MiB, count=333250, average=36 B F:/py3proj/play.py:33: size=448 B, count=1, average=448 B F:/py3proj/play.py:22: size=136 B, count=1, average=136 B F:/py3proj/play.py:17: size=136 B, count=1, average=136 B F:/py3proj/play.py:14: size=76 B, count=2, average=38 B F:/py3proj/play.py:8: size=34 B, count=1, average=34 B Two points: Generator use more time and same memory space. The list-comprehension in sum function seems not create the total list I think maybe the sum function did something i don't know.Who can explain this? The book is High Perfoamance Python.chapter 5.But i did sth myself different from the book to check the validity in other context. And his code is here book_code,he didn't put the list-comprehension in sum funciton.
type: UnansweredQuestion
score: 5
tagged with: python
has comment: http://stackoverflow.com/comment/88286449
has comment: http://stackoverflow.com/comment/88285955
has comment: http://stackoverflow.com/comment/88287056
tagged with: generator
has comment: http://stackoverflow.com/comment/88289376
tagged with: sum
upvote count: 5
type: Question
has comment: http://stackoverflow.com/comment/88291090
has comment: http://stackoverflow.com/comment/88286007
has title: What does sum do?
downvote count: 0
has comment: http://stackoverflow.com/comment/88287307
linked to: http://stackoverflow.com/q/16940293

http://stackoverflow.com/comment/88332444
type: Comment
type: QuestionComment
score: 4
comment on: http://stackoverflow.com/q/50661184
has text: Browsers run javascript not http libraries. Look in dev tools and see if the data is retrieved though an ajax request.

http://stackoverflow.com/q/50656813
has title: Python | Payment Calculator [ Computer Science Circles ]
favorite count: 0
tagged with: python
has body: Image Of the QUestion Hello , Everyone The picture I attached is the image of the question and here is my code : p1 = balance * 0.021; p2 = balance * 10; p3 = max(p1,p2); if ( balance &lt;= p3 ) : print(p3); else : print(balance); But It doesn't return the correct result . any help?
has comment: http://stackoverflow.com/comment/88323590
has answer: http://stackoverflow.com/a/50656974
type: AnsweredQuestion
downvote count: 3
upvote count: 1
type: Question
score: -2
has answer: http://stackoverflow.com/a/50656938
accepted answer: http://stackoverflow.com/a/50656974
has comment: http://stackoverflow.com/comment/88323588
has answer: http://stackoverflow.com/a/50657054
possible better answer: http://stackoverflow.com/a/50656938
answer count: 3

http://stackoverflow.com/comment/88352699
score: 0
type: Comment
has text: Thank you! How would I do part 2? I just edited it. Thank you
comment on: http://stackoverflow.com/a/50671422
type: AnswerComment

http://stackoverflow.com/comment/88276025
has text: The parenthesis in paragraph 1 seems unnecessary. "we do not call the dict function" -> we do not call dict (might be confusing to call dict a function after calling it a class?)
comment on: http://stackoverflow.com/a/50632753
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50633851
has comment: http://stackoverflow.com/comment/88277937
type: Question
has title: Why doesn't my wav music file play in Qsound?
accepted answer: http://stackoverflow.com/a/50634022
tagged with: media-player
has body: This is my code : from PyQt5.QtMultimedia import QSound QSound("1.wav").play() It doesn't play the music. The file is 37 MB.
tagged with: pyqt
answer count: 1
downvote count: 0
favorite count: 0
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/50634022
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/88325322
type: AnswerComment
type: Comment
score: 1
has text: What does this answer have to do with the question at all?
comment on: http://stackoverflow.com/a/50657682

http://stackoverflow.com/q/50608927
tagged with: python
tagged with: tkinter
score: 0
type: AnsweredQuestion
tagged with: matplotlib
has answer: http://stackoverflow.com/a/50609121
type: Question
has title: Pickable matplotlib plot in tkk frame
answer count: 1
has body: I would like to have a GUI where one part of the interface contains a plot and the rest of the window some tools to work around the plot. I would like to use mpl_connect to connect the matplotlib canvas with the tkk frame so that I can choose points in the plot to work with. This was my try, which cowardly refuses to do what I think it should do: import Tkinter as tk import ttk from matplotlib.backends.backend_tkagg import ( FigureCanvasTkAgg, NavigationToolbar2TkAgg) import matplotlib.pyplot as plt import numpy as np class Frame_examples_program(): def __init__(self): self.window = tk.Tk() self.window.title("Amazing GUI 5000") self.create_widgets() def create_widgets(self): self.window['padx'] = 10 self.window['pady'] = 10 # - - - - - - - - - - - - - - - - - - - - - # Frame frame1 = ttk.Frame(self.window, relief=tk.RIDGE) frame1.grid(row=0, column=0, sticky=tk.E + tk.W + tk.N + tk.S, padx=0, pady=0) frame2 = ttk.Frame(self.window, relief=tk.RIDGE) frame2.grid(row=1, column=0, sticky=tk.E + tk.W + tk.N + tk.S, padx=0, pady=0) self.PlotFrame(frame1, frame2) class PlotFrame(): # The plot def __init__(self, parent1, parent2): self.parent1 = parent1 self.parent2 = parent2 canvas = self.plot() self.plot_toolbar(canvas) def plot(self): # the actual plot fig, ax = plt.subplots() plt.imshow(np.ones((100,100)),picker=True) canvas = FigureCanvasTkAgg(fig, self.parent1) canvas.mpl_connect('button_press_event', self.onclick) return(canvas) def plot_toolbar(self, canvas): # the tool bar to the plot toolbar = NavigationToolbar2TkAgg(canvas, self.parent2) toolbar.update() canvas.get_tk_widget().grid(row=1, column=1) canvas.draw() def onclick(self, event): # the devilish thing that does nothing! print('WOHOOOO') # Create the entire GUI program program = Frame_examples_program() # Start the GUI event loop program.window.mainloop() As you'll see when you run this, the matplotlib toolbar nicely works, but I just can't call the onclick event! Why?
accepted answer: http://stackoverflow.com/a/50609121

http://stackoverflow.com/comment/88487810
comment on: http://stackoverflow.com/a/50606636
has text: Can u write that above program for me to work efficiently?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50675178
has title: tf.ones(dtype=tf.float32) or tf.ones(dtype=tf.int32) behave differently
has comment: http://stackoverflow.com/comment/88360404
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/88360950
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/88360483
has body: When I use dtype = tf.float32, import tensorflow as tf z = tf.Variable(tf.ones(5, dtype=tf.float32), name='z') init = tf.global_variables_initializer() with tf.Session() as session: session.run(init) print("z=" , session.run(z)) for i in range(5): z = z +1 print(session.run(z)) I got the result like this: ('z=', array([0., 0., 0., 0., 0.], dtype=float32)) [0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.] However, when I use dtype=tf.int32， z = tf.Variable(tf.ones(5, dtype=tf.int32), name='z') I got the result: ('z=', array([1, 1, 1, 1, 1], dtype=int32)) [2 2 2 2 2] [3 3 3 3 3] [4 4 4 4 4] [5 5 5 5 5] [6 6 6 6 6] Can you help me why it seems not correctly when use tf.float32?

http://stackoverflow.com/comment/88313724
score: 0
comment on: http://stackoverflow.com/a/50648943
type: Comment
has text: @thecode, I tested this with a file containing over 200,000 words, one per line. What format and size file are you working with?
type: AnswerComment

cql3
tags question: http://stackoverflow.com/q/50630585
tag name: cql3
type: Tag

experimental-design
type: Tag
tags question: http://stackoverflow.com/q/50544709
tag name: experimental-design

discord
tags question: http://stackoverflow.com/q/50574239
tags question: http://stackoverflow.com/q/50588375
tags question: http://stackoverflow.com/q/50646101
tags question: http://stackoverflow.com/q/50557466
tags question: http://stackoverflow.com/q/50563138
type: Tag
tags question: http://stackoverflow.com/q/50542899
tags question: http://stackoverflow.com/q/50616115
tags question: http://stackoverflow.com/q/50595572
tags question: http://stackoverflow.com/q/50546847
tags question: http://stackoverflow.com/q/50574359
tags question: http://stackoverflow.com/q/50597188
tags question: http://stackoverflow.com/q/50678419
tag name: discord
tags question: http://stackoverflow.com/q/50571984
tags question: http://stackoverflow.com/q/50686388
tags question: http://stackoverflow.com/q/50662953
tags question: http://stackoverflow.com/q/50548910
tags question: http://stackoverflow.com/q/50548316
tags question: http://stackoverflow.com/q/50664888

http://stackoverflow.com/comment/88120212
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50554426
has text: Thx, I went down the road of looking into 3.7 before, but i think i gave up due to the difficulty of porting the whole project in it. I thought they were maybe common snags when creating own modules that other people might know of. Anyway thx for your help - I will have a look at the import-profiler module too!

http://stackoverflow.com/q/50640023
score: 1
has comment: http://stackoverflow.com/comment/88290439
upvote count: 1
has title: Failed to create sub-process in Python on Windows 10
tagged with: multiprocessing
type: Question
has body: I found the code below on the python website. However the code does not compile on Windows 10 with Python 3.6.5 installed. I've tried the same code on Ubuntu 16.04 (Python 2.7) and the code works fine. from multiprocessing import Process def f(name): print ('hello', name) if __name__ == '__main__': p = Process(target=f, args=('bob',)) p.start() p.join() The error I get is shown below. I've only shown the last line of the stack trace since this seems to be where the error is generated. I've done a lot searching but have not found a solution. File "J:\Programs\Python\Python36\lib\multiprocessing\context.py", line 321, in _Popen from .popen_spawn_win32 import Popen ImportError: cannot import name 'Popen' Thanks in advance for any help.
downvote count: 0
linked to: http://stackoverflow.com/q/29630217
has comment: http://stackoverflow.com/comment/88342825
favorite count: 0
has comment: http://stackoverflow.com/comment/88527637
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88339364
answer count: 0

http://stackoverflow.com/comment/123251043
type: QuestionComment
score: 0
has text: If you figured out the answer to your own question, post it as an answer and then accept it, so other people can see how you solved it (rather than editing it into the question itself).
comment on: http://stackoverflow.com/q/50662071
type: Comment

http://stackoverflow.com/comment/88311709
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50650407
has text: `float.__pow__` does not use the `math.pow` function, at least not in CPython. They do, however, both ultimately use the same `pow` function from the C stdlib (after a bunch of pre-checks and conversions that are not identical for the two), which is probably what you should be saying here.
score: 0

http://stackoverflow.com/comment/88351193
score: 0
type: QuestionComment
has text: How about your function takes a list of `treeNode`s and recursively deals with every single one of them?
type: Comment
comment on: http://stackoverflow.com/q/50670669

http://stackoverflow.com/a/50564189
upvote count: 17
type: Answer
has comment: http://stackoverflow.com/comment/88145427
has body: Seaborn seems to work the same as matplotlib in this regard: tips = sns.load_dataset("tips") ax = sns.boxplot(x=tips["total_bill"], whis=[5, 95]) plt.grid(True) plt.boxplot(tips["total_bill"], whis=[5, 95], vert=False) plt.grid(True) I guess seaborn just pass whis to the matplotlib method. The docstring might have been copied from an earlier version of matplotlib.
accepted answer of: http://stackoverflow.com/q/50554235
score: 17
answers question: http://stackoverflow.com/q/50554235
has comment: http://stackoverflow.com/comment/136188124
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88223520
has text: Of course this is possible, and information on how to do this is abundant on stack overflow. See [this](https://stackoverflow.com/a/17126015/3714930), [this](https://stackoverflow.com/a/34901558/3714930) and many more questions.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50606250
score: 1

http://stackoverflow.com/a/50684010
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50683810
upvote count: 5
answers question: http://stackoverflow.com/q/50683810
type: Answer
score: 5
has body: Consider using a list of dataframes and access multiple resultsets with nextset(): cur = connection.cursor() df_list = [] # FIRST RESULTSET rows = cur.execute(sql).fetchall() columns = [column[0] for column in cur.description] df_list.append(pd.DataFrame.from_records(rows, columns=columns)) print(df.head()) # SUBSEQUENT RESULTSETS while (cur.nextset()): rows = cur.fetchall() columns = [column[0] for column in cur.description] df_list.append(pd.DataFrame.from_records(rows, columns=columns)) print(df.head()) cur.close() # RUN ANY DATAFRAME OPERATION BY EACH ITEM OF df_list df_list[[1]].describe() df_list[[2]].head() df_list[[3]].tail() df_list[[4]].dtypes df_list[[5]].columns
type: AcceptedAnswer

http://stackoverflow.com/comment/88407693
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50698425
has text: I used it, that helps! Also I can see the running processes from Task Manager (as Python.exe). One last thing: I want the window to appear only to get input from the user. But with .pyw I don't see the window anytime. Shall I use another package to force the window to stay open until the user gives an input and close until the next scheduled time?

http://stackoverflow.com/q/50593797
has answer: http://stackoverflow.com/a/50604262
type: UnansweredQuestion
has title: Pandas Expanding Mean with Group By and before current row date
tagged with: python
has answer: http://stackoverflow.com/a/50594273
linked to: http://stackoverflow.com/q/20109391
score: 1
has body: I have a Pandas dataframe as follows df = pd.DataFrame([['John', '1/1/2017','10'], ['John', '2/2/2017','15'], ['John', '2/2/2017','20'], ['John', '3/3/2017','30'], ['Sue', '1/1/2017','10'], ['Sue', '2/2/2017','15'], ['Sue', '3/2/2017','20'], ['Sue', '3/3/2017','7'], ['Sue', '4/4/2017','20'] ], columns=['Customer', 'Deposit_Date','DPD']) . What is the best way to calculate the PreviousMean column in the screen shot below? The column is the year to date average of DPD for that customer. I.e. Includes all DPDs up to but not including rows that match the current deposit date. If no previous records existed then it's null or 0. Screenshot: Notes: the data is grouped by Customer Name and expanding over Deposit Dates within each group, the expanding mean is calculated using only values from the previous rows. at the start of each new customer the mean is 0 or alternatively null as there are no previous records on which to form the mean the data frame is ordered by Customer Name and Deposit_Date
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/117501179
answer count: 3
tagged with: pandas
downvote count: 1
has answer: http://stackoverflow.com/a/50593935
favorite count: 0

http://stackoverflow.com/q/50605148
has answer: http://stackoverflow.com/a/50605318
type: Question
has body: I'm using Python and lxml. My xml file: <Some.Node> // ... </Some.Node> <Some.Node> <Known.Node KnownAttribute="123"/> <Some.Stuff> <Nothing.Important>Bla</Nothing.Important> </Some.Stuff> <Relevant.Node> Some True Known.Name Desired Value Some.Other Yes // ... </Relevant.Node> // ... </Some.Node> <Some.Node> // ... </Some.Node> There are multiple <Some.Node> nodes and I'm only interested in the one with KnownAttribute equal to 123. This part I got: query = "//Known.Node[@KnownAttribute='%s']" % attribute_value However, I need to get the value of <Relevant.Node>/ / where has value Known.Name. This was my best try but it didn't work: root = etree.parse(xml_file).getroot() query = "//Known.Node[@KnownAttribute='%s']/..//Property[Name='Known.Name']/Value" % attribute_value result = root.xpath(query) print(result[0].text) It should print, of course, Desired Value but it just returns empty value/whitespace. How can I get the value I need?
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50605318
tagged with: http://stackoverflow.com/tag/xml
tagged with: xpath
type: AnsweredQuestion
has title: How to select a sibling's child node using XPath in Python?
downvote count: 0
score: 1

http://stackoverflow.com/a/50685454
has comment: http://stackoverflow.com/comment/88381689
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88381383
has comment: http://stackoverflow.com/comment/107642113
accepted answer of: http://stackoverflow.com/q/50685409
answers question: http://stackoverflow.com/q/50685409
type: Answer
upvote count: 43
has comment: http://stackoverflow.com/comment/88381587
downvote count: 0
has comment: http://stackoverflow.com/comment/92688780
score: 43
has body: To get a list of evenly spaced indices, use np.linspace: idx = np.round(np.linspace(0, len(arr) - 1, numElems)).astype(int) Next, index back into arr to get the corresponding values: arr[idx] Always use rounding before casting to integers. Internally, linspace calls astype when the dtype argument is provided. Therefore, this method is NOT equivalent to: # this simply truncates the non-integer part idx = np.linspace(0, len(array) - 1, numElems).astype(int) idx = np.linspace(0, len(arr) - 1, numElems, dtype='int')

http://stackoverflow.com/comment/88210203
has text: I did it Daniel, but the error still remains
comment on: http://stackoverflow.com/q/50551480
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88164749
score: 0
type: QuestionComment
type: Comment
has text: @RameshMaharjan have installed..jdk1.8.0_144
comment on: http://stackoverflow.com/q/50576243

http://stackoverflow.com/q/50548263
has answer: http://stackoverflow.com/a/50548490
has comment: http://stackoverflow.com/comment/88110680
has title: Update Function Call within Python Coroutine
has comment: http://stackoverflow.com/comment/88111005
has body: I have a simple class for fetching URLs while periodically updating the access token using a new loop on separate thread: import asyncio import aiohttp from threading import Thread from random import randint LOOP = asyncio.get_event_loop() NEW_LOOP = asyncio.new_event_loop() t = Thread(target=NEW_LOOP.run_forever) t.start() class SOME_CLASS(object): def __init__(self, loop=LOOP, new_loop=NEW_LOOP): self.token = None self.loop = loop self.new_loop = new_loop self.semaphore = asyncio.Semaphore(3) self.session = aiohttp.ClientSession(loop=self.loop) asyncio.run_coroutine_threadsafe(self.get_token(), self.new_loop) def _get_headers(self): headers = { 'x-access-token': str(self.token), 'content-type': 'application/json', } return headers async def get_token(self): while True: self.token = randint(1, 100) await asyncio.sleep(2) async def fetch(self, url): async with self.semaphore: headers = self._get_headers() async with self.session.get(url, headers=headers) as response: await response.read() return headers async def fetch_all(self): urls = ['https://httpbin.org/get?x={i}'for i in range(1000)] futures = asyncio.as_completed([self.fetch(url) for url in urls]) for future in futures: await asyncio.sleep(1) headers = await future print(f'headers: {headers} token: {self.token}') def run(self): self.loop.run_until_complete(self.fetch_all()) if __name__ == '__main__': sc = SOME_CLASS() sc.run() However, I noticed that even though the self.token is indeed being updated every two seconds, the token stored within the headers stays unchanged. It seems as though self._get_headers() gets called well in advance and not after it acquires a semaphore: headers: {'x-access-token': '8', 'content-type': 'application/json'} token: 8 headers: {'x-access-token': '8', 'content-type': 'application/json'} token: 8 headers: {'x-access-token': '8', 'content-type': 'application/json'} token: 78 headers: {'x-access-token': '8', 'content-type': 'application/json'} token: 78 headers: {'x-access-token'…
has answer: http://stackoverflow.com/a/50548326
type: Question
has comment: http://stackoverflow.com/comment/88155924
has comment: http://stackoverflow.com/comment/88115508
has comment: http://stackoverflow.com/comment/88126115
has comment: http://stackoverflow.com/comment/88130948
score: 0
answer count: 2
tagged with: python-asyncio
has comment: http://stackoverflow.com/comment/88109975
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88110243
tagged with: aiohttp

http://stackoverflow.com/comment/88164503
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50577309
has text: It returns `InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'spatial_pyramid_pooling_7_input' with dtype float and shape [?,?,?,?,3] [[Node: spatial_pyramid_pooling_7_input = Placeholder[dtype=DT_FLOAT, shape=[?,?,?,?,3], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]`
score: 0

http://stackoverflow.com/comment/88207403
score: 0
type: Comment
type: QuestionComment
has text: See give us a clarity about your question there are two URLs
comment on: http://stackoverflow.com/q/50596456

http://stackoverflow.com/q/50639137
tagged with: python-3.x
type: Question
accepted answer: http://stackoverflow.com/a/50641763
has comment: http://stackoverflow.com/comment/88289219
tagged with: class-variables
tagged with: python
possible better answer: http://stackoverflow.com/a/50639268
has answer: http://stackoverflow.com/a/50639268
has comment: http://stackoverflow.com/comment/88289583
score: 0
answer count: 2
has body: I have the following situation in Python 3: class A: d = {} class B(A): pass class C(A): pass I work with the classes only, no instances get created. When I access B.d I will get a shared reference to A.d. That's not what I want. I would like to have each class which inherits A have its own d which is set to a dictionary. d is an implementation detail to A. All access to d is done in the code of A. Just B's d should not be identical to A's d. With instances, I would create that dictionary in the __init__() function. But in my case I work with the classes only. Is there a standard way to achieve this (EDIT: without changing the implementation of the subclasses B and C)? Is there something analog to __init__() which gets called for (or in) each derived class at the time of deriving?
has comment: http://stackoverflow.com/comment/88290129
has answer: http://stackoverflow.com/a/50641763
tagged with: inheritance
tagged with: class
has title: Prevent sharing of class variables with base class in Python
has comment: http://stackoverflow.com/comment/88288413
type: AnsweredQuestion

http://stackoverflow.com/comment/88187447
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50581267
has text: I generally don't mind reopening dupes, but it does rub me the wrong way if it's done without any form of communication. In the case that my dupe was straight up incorrect, I *definitely* want to know about it; and even if it's just less-than-ideal, I'd still prefer to be informed of the question being reopened - if only because I may want to link the related question in the comments. But in this particular case, I have to say I really don't see the need for an answer. If it's about rewriting the loop to a list comprehension, well, we have lots of answers about that already. Why add another?
score: 0

http://stackoverflow.com/q/50698111
has answer: http://stackoverflow.com/a/50698166
has comment: http://stackoverflow.com/comment/88409996
type: Question
score: -2
tagged with: numpy
has title: Write data in one line
tagged with: pandas
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88405673
type: UnansweredQuestion
has body: I have data written in a csv file in the format below: [(789,255,25,33.0),(855,275,25,33.0)............] I want it to be converted into a format like: 1. 789,255,25,33.0 2. 855,275,25,33.0 .............. So all i want is convert the tuples in the list into a new csv file with each tuple in a new line. The values in the list are in string and i want to convert it into float as well how do i accomplish it?
tagged with: python
downvote count: 2

http://stackoverflow.com/comment/137911002
type: QuestionComment
has text: Encountered this in some legacy unittests due to multiple `QtWidgets.QApplication` instances. See e.g. https://stackoverflow.com/q/74303807
comment on: http://stackoverflow.com/q/50620954
score: 0
type: Comment

http://stackoverflow.com/a/50634026
downvote count: 0
has comment: http://stackoverflow.com/comment/114261407
score: 1
has comment: http://stackoverflow.com/comment/88285461
has body: Unfortunately, this is currently not something that's possible to type using PEP 484 type hints. The best you can do is use overloads to approximate a signature: basically, we hard-code what the signature ought to be up to a certain number then fall back to inferring 'Any': from typing import TypeVar, overload, Any, Callable T1 = TypeVar('T1') T2 = TypeVar('T2') T3 = TypeVar('T3') T4 = TypeVar('T4') @overload def chain_call(input_value: T1, *f_rest: Callable[[T1], T1]) -&gt; T1: ... @overload def chain_call(input_value: T1, f1: Callable[[T1], T2], f2: Callable[[T2], T3], f3: Callable[[T3], T4], f4: Callable[[T4], Any], *f_rest: Callable[[Any], Any]) -&gt; Any: ... @overload def chain_call(input_value: T1, f1: Callable[[T1], T2], f2: Callable[[T2], T3], f3: Callable[[T3], T4]) -&gt; T4: ... @overload def chain_call(input_value: T1, f1: Callable[[T1], T2], f2: Callable[[T2], T3]) -&gt; T3: ... @overload def chain_call(input_value: T1, f1: Callable[[T1], T2]) -&gt; T2: ... def chain_call(input_value, *f_rest): for function in f_rest: input_value = function(input_value) return input_value Here, I hard-coded what ought to happen up to 3 input functions (and started with an overload for the special case where all the callables happen to have the same input and output type). This technique is how typeshed currently types things like the zip function, which can accept an arbitrary number of iterables. Note: you may need to use the latest version of mypy from master for this code to work verbatim.
upvote count: 1
answers question: http://stackoverflow.com/q/50570524
type: Answer

http://stackoverflow.com/comment/88374079
type: QuestionComment
score: 2
has text: Think about it: how would `l.remove(max(l))` "know" to return the next maximum value in `l`? Or what value might you even expect it to return?
comment on: http://stackoverflow.com/q/50682183
type: Comment

http://stackoverflow.com/a/50559158
has body: import time from selenium import webdriver from selenium.common.exceptions import NoSuchElementException capabilities = { 'browserName': 'chrome', 'chromeOptions': { 'useAutomationExtension': False, 'forceDevToolsScreenshot': True, 'args': ['--start-maximized', '--disable-infobars'] } } driver = webdriver.Chrome(executable_path='./chromedriver_2.38.exe', desired_capabilities=capabilities) driver.get("""https://www.amazon.com/gp/goldbox/ref=gbps_ftr_s-4_bedf_page_10? gb_f_deals1=enforcedCategories:2972638011, dealStates:AVAILABLE%252CWAITLIST%252CWAITLISTFULL, includedAccessTypes:,page:10,sortOrder:BY_SCORE, dealsPerPage:32&pf_rd_p=afc45143-5c9c-4b30-8d5c-d838e760bedf& pf_rd_s=slot-4&pf_rd_t=701&pf_rd_i=gb_main& pf_rd_m=ATVPDKIKX0DER&pf_rd_r=ZDV4YBQJFDVR3PAY4ZBS&ie=UTF8""") time.sleep(15) golds = driver.find_elements_by_css_selector(".widgetContainer #widgetContent > div.singleCell") print("found %d golds" % len(golds)) template = """\ \ {2} \ {3} """ lines = [] for gold in golds: goldInfo = {} goldInfo['title'] = gold.find_element_by_css_selector('#dealTitle > span').text goldInfo['link'] = gold.find_element_by_css_selector('#dealTitle').get_attribute('href') goldInfo['image'] = gold.find_element_by_css_selector('#dealImage img').get_attribute('src') try: goldInfo['price'] = gold.find_element_by_css_selector('.priceBlock > span').text except NoSuchElementException: goldInfo['price'] = 'No price display' print goldInfo['title'] line = template.format(goldInfo['image'], goldInfo['link'], goldInfo['title'], goldInfo['price']) lines.append(line) html = """\ {0} \ """ f = open('./result.html', 'w') f.write(html.format('\n'.join(lines))) f.close()
has comment: http://stackoverflow.com/comment/88186736
has comment: http://stackoverflow.com/comment/88152606
has comment: http://stackoverflow.com/comment/88158161
score: 0
has comment: http://stackoverflow.com/comment/88132116
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88158542
has comment: http://stackoverflow.com/comment/88159898
has comment: http://stackoverflow.com/comment/88160030
type: Answer
accepted answer of: http://stackoverflow.com/q/50556059
has comment: http://stackoverflow.com/comment/88159691
answers question: http://stackoverflow.com/q/50556059
has comment: http://stackoverflow.com/comment/88164440
has comment: http://stackoverflow.com/comment/88159377
has comment: http://stackoverflow.com/comment/88129555

http://stackoverflow.com/q/50606059
tagged with: python
tagged with: correlation
has answer: http://stackoverflow.com/a/51651041
has comment: http://stackoverflow.com/comment/88221639
type: Question
has title: AttributeError: 'NoneType' object has no attribute 'setCallSite'
has comment: http://stackoverflow.com/comment/88222437
tagged with: apache-spark-sql
tagged with: pyspark
has answer: http://stackoverflow.com/a/63129856
score: 4
has answer: http://stackoverflow.com/a/56105513
upvote count: 4
has comment: http://stackoverflow.com/comment/88221872
has comment: http://stackoverflow.com/comment/124798814
answer count: 3
linked to: http://stackoverflow.com/q/8949252
has body: In PySpark, I want to calculate the correlation between two dataframe vectors, using the following code (I do not have any problem in importing pyspark or createDataFrame): from pyspark.ml.linalg import Vectors from pyspark.ml.stat import Correlation import pyspark spark = pyspark.sql.SparkSession.builder.master("local[*]").getOrCreate() data = [(Vectors.sparse(4, [(0, 1.0), (3, -2.0)]),), (Vectors.dense([4.0, 5.0, 0.0, 3.0]),)] df = spark.createDataFrame(data, ["features"]) r1 = Correlation.corr(df, "features").head() print("Pearson correlation matrix:\n" + str(r1[0])) But, I got the AttributeError (AttributeError: 'NoneType' object has no attribute 'setCallSite') as: AttributeError Traceback (most recent call last) &lt;ipython-input-136-d553c1ade793&gt; in &lt;module&gt;() 6 df = spark.createDataFrame(data, ["features"]) 7 ----&gt; 8 r1 = Correlation.corr(df, "features").head() 9 print("Pearson correlation matrix:\n" + str(r1[0])) /usr/local/lib/python3.6/dist-packages/pyspark/sql/dataframe.py in head(self, n) 1130 """ 1131 if n is None: -&gt; 1132 rs = self.head(1) 1133 return rs[0] if rs else None 1134 return self.take(n) /usr/local/lib/python3.6/dist-packages/pyspark/sql/dataframe.py in head(self, n) 1132 rs = self.head(1) 1133 return rs[0] if rs else None -&gt; 1134 return self.take(n) 1135 1136 @ignore_unicode_prefix /usr/local/lib/python3.6/dist-packages/pyspark/sql/dataframe.py in take(self, num) 502 [Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')] 503 """ --&gt; 504 return self.limit(num).collect() 505 506 @since(1.3) /usr/local/lib/python3.6/dist-packages/pyspark/sql/dataframe.py in collect(self) 463 [Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')] 464 """ --&gt; 465 with SCCallSiteSync(self._sc) as css: 466 port = self._jdf.collectToPython() 467 return list(_load_from_socket(port, BatchedSerializer(PickleSerializer()))) /usr/local/lib/python3.6/dist-packages/pyspark/traceback_utils.py in __enter__(self) 70 def __enter__(self): 71 if SCCallSiteSyn…
downvote count: 0
favorite count: 0
tagged with: statistics
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88222341

http://stackoverflow.com/a/50551837
downvote count: 0
answers question: http://stackoverflow.com/q/50551733
type: Answer
has comment: http://stackoverflow.com/comment/88155141
score: 1
has body: Easy, quicker and more performant, using list comprehension: def particle(): return [ran() for _ in range(20)] Usage: xj = particle()
upvote count: 1
has comment: http://stackoverflow.com/comment/88156785
has comment: http://stackoverflow.com/comment/88155227

http://stackoverflow.com/comment/88298240
has text: Can you demonstrate *any* effort at solving this yourself?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50643953

http://stackoverflow.com/comment/88101813
comment on: http://stackoverflow.com/q/50545192
score: 0
has text: Exactly, sorry I might have been wording it weirdly
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88247589
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50617036
has text: @DebanjanB : locator of new page after redirection means the type of locator and value means its value , anyway I have changed it.

http://stackoverflow.com/a/50579262
type: Answer
score: 2
has body: I would do the following: html = ( ' HEY! ' ' ' 'How are' ' you? ' ' END ' ' ' 'Some other text' ) soup = BeautifulSoup(html, 'lxml') >>> soup.select_one('#end_content').find_all_previous(string=True)[::-1] ['HEY!', 'How are', 'you?']
downvote count: 0
answers question: http://stackoverflow.com/q/50578090
upvote count: 2

http://stackoverflow.com/comment/88108849
comment on: http://stackoverflow.com/a/50548940
score: 0
type: AnswerComment
has text: File "<stdin>", line 33, in test_string_scramble AssertionError: <function string_scramble at 0x7f96dc63ec80> is not an instance of (<class 'list'>, <class 'tuple'>)
type: Comment

http://stackoverflow.com/q/50686936
has comment: http://stackoverflow.com/comment/88384155
upvote count: 1
tagged with: keras
favorite count: 0
has title: Keras Conv2d Transpose
type: UnansweredQuestion
tagged with: convolution
tagged with: python
answer count: 0
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88384620
has comment: http://stackoverflow.com/comment/88386076
tagged with: image-processing
has comment: http://stackoverflow.com/comment/88392351
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/88384852
type: Question
has comment: http://stackoverflow.com/comment/88386167
has body: I am trying to use Keras to create a Fully Convolutional network for image processing. My initial grid is (10x25) and I pass that through couple of convolutional layers and then try to use Conv2d Transpose to try and resize the image back to original dimensions, however my deconvolutional layer has no output or is coming as none rather. You can look at the code to see what is being done. inputs = Input(shape = (input_shape)) conv1 = Conv2D(32, kernel_size=(2, 2), activation='relu', padding ='same')(inputs) conv1 = Conv2D(32, (2, 2), strides = 1, activation='relu', padding ='same')(conv1) pool1 = MaxPooling2D(pool_size=(2,2), padding = 'same')(conv1) conv2 = Conv2D(64, (2, 2), strides = 1, activation='relu', padding ='same')(pool1) conv2 = Conv2D(64, (2, 2), strides = 1, activation='relu', padding ='same')(conv2) pool2 = MaxPooling2D(pool_size=(2,2), padding = 'same')(conv2) conv3 = Conv2D(128, (2, 2), strides = 1, activation='relu', padding ='same')(pool2) conv3 = Conv2D(128, (2, 2), strides = 1, activation='relu', padding ='same') (conv3) pool3 = MaxPooling2D(pool_size=(2,2), padding = 'same')(conv3) deconv1 = Conv2DTranspose(64, kernel_size = (pool3.get_shape().as_list()[1:3]), strides = (2,2), data_format='channels_last')(conv3) conv4 = Conv2D(64, (2, 2), strides = 1, activation='relu', padding ='same')(deconv1) deconv2 = Conv2DTranspose(32, kernel_size = (conv1.get_shape().as_list()[1:3]), strides = (2,2), data_format='channels_last')(conv4) conv5 = Conv2D(32, (2, 2),strides = 1, activation='relu', padding ='same')(deconv2) deconv3 = Conv2DTranspose(1, kernel_size = (input_shape[0:2]), data_format='channels_last')(conv5) conv6 = Conv2D(1, (1, 1), strides = 1, activation=act_identity)(deconv3)
has comment: http://stackoverflow.com/comment/88387491

http://stackoverflow.com/comment/88252616
has text: And why is your question tagged python-3.x but your code has a Python 2 `print` statement?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50621281

http://stackoverflow.com/comment/88349651
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50669897
has text: Just start from `1` in the `range()` and you can avoid the extra `sum(c) > 0` condition.
score: 1

http://stackoverflow.com/q/50563235
type: Question
tagged with: javascript
has body: I would like to use this javascript API in a Django based web page. Is it possible to use this code below in a Django web framework? https://github.com/Esri/html5-geolocation-tool-js I plan to create a web page where users can sign up and log in to the Django webpage and subsequently upload their photos and post their live user location from their mobile phone into their own web account. I need to use this API as it has an accuracy of up to 10 meters outdoors which is ideal for my application. I only really need the latitude and longitude data from the GPS to be saved in Django. I have only around 6 months of Python and Django experience and none for javascript. Any advice on how to integrate this API into Django?
score: 0
tagged with: api
has comment: http://stackoverflow.com/comment/88138171
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88137029
has comment: http://stackoverflow.com/comment/88136906
tagged with: python
has title: django and javascript API
answer count: 0
tagged with: geolocation
tagged with: django

http://stackoverflow.com/q/50617343
has body: I have 3 tables: Account, User and Organization. Account consists of id, name and organization_id. User consists of email and organization_id. Organization consists of id and name. Each Account is registered to an Organization(through organization_id) and each User is registered to an Organization. The challenge is to display all the emails (from User) to the Account corresponding to the name whose organization_id matches the organization_id of User. Here's my code till now: class Account(db.Model): __tablename__ = "account" id = Column(Integer, primary_key=True) name = Column(String(50), index=True, unique=True) organization = Column(Integer, ForeignKey("organization.id"),nullable=False, index=True) class User(UserMixin, db.Model, RBACUserMixin): __tablename__ = "user" id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255), unique=True) organization = Column(Integer, ForeignKey("organization.id"), nullable=False, index=True) class Organization(db.Model): __tablename__ = "organization" id = Column(Integer, primary_key=True) name = Column(String(512)) users = relationship("User", backref="organizations") accounts = relationship("Account", backref="organizations")
answer count: 1
tagged with: flask-sqlalchemy
favorite count: 0
upvote count: 12
tagged with: postgresql
type: UnansweredQuestion
tagged with: python
score: 11
has answer: http://stackoverflow.com/a/50617869
has title: How to join data from two tables in SQLAlchemy?
downvote count: 1
tagged with: sqlalchemy
type: Question

sunburst-diagram
tags question: http://stackoverflow.com/q/50567516
tag name: sunburst-diagram
type: Tag

http://stackoverflow.com/q/50670812
favorite count: 0
has comment: http://stackoverflow.com/comment/88351495
type: UnansweredQuestion
tagged with: encryption
tagged with: python
has comment: http://stackoverflow.com/comment/88351420
has comment: http://stackoverflow.com/comment/88384505
answer count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88351491
type: Question
has comment: http://stackoverflow.com/comment/88384647
has title: Python encrypt email address
tagged with: algorithm
has comment: http://stackoverflow.com/comment/88351658
downvote count: 0
has body: I need to encrypt some email address and after I need to put them in a databases. The database column is a varchar(60). I try to use something like this: from Crypto.Cipher import AES import base64 msg_text = 'mypersonalmail@gmail.com'.rjust(32) secret_key = '1234567890123456' # create new &amp; store somewhere safe cipher = AES.new(secret_key,AES.MODE_ECB) # never use ECB in strong systems obviously encoded = base64.b64encode(cipher.encrypt(msg_text)) print encoded.strip() But if the msg_text is so long I received this error: ValueError: Input strings must be a multiple of 16 in length and if the msg_text is so long and a multiple of 16 i exceed the 60 characters
has comment: http://stackoverflow.com/comment/88351502

http://stackoverflow.com/comment/88585695
comment on: http://stackoverflow.com/q/50613173
score: 0
has text: Hi Andrew, updated my question with sample scenario, created using AWS Glue context. Is it possible to run/execute mysql upsert scripts from with Glue->pyspark environment. Thanks
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50548341
has body: Using numpy's zeros_like and related functions, there is an option subok: bool, optional. numpy.zeros_like(a, dtype=None, order='K', subok=True) If True, then the newly created array will use the sub-class type of ‘a’, otherwise it will be a base-class array. Defaults to True. I assumed all numpy arrays were of class ndarray and I've never had a need to look in detail at an array's subclass. Under what situations might I want to opt out of using the same subclass, specify the use of the base class?
tagged with: python
favorite count: 0
score: 6
type: AnsweredQuestion
has title: What is the purpose and utility of the subok option in numpy.zeros_like()?
downvote count: 0
has comment: http://stackoverflow.com/comment/88107894
accepted answer: http://stackoverflow.com/a/50548543
type: Question
tagged with: numpy
answer count: 1
upvote count: 6
has comment: http://stackoverflow.com/comment/88107867
has answer: http://stackoverflow.com/a/50548543
tagged with: class
tagged with: subclass

http://stackoverflow.com/comment/88213574
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50601927
has text: You can easily find pos.txt and neg.txt from: https://pythonprogramming.net/using-our-own-data-tensorflow-deep-learning-tutorial/. Please download.

http://stackoverflow.com/comment/88410882
has text: It's `ctx.send` but thanks for your help dude! Discord.py is now working and my project is up and running!
comment on: http://stackoverflow.com/a/50667631
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50581325
downvote count: 0
score: 7
has body: Well, CELERY_BROKER_URL made this error, I have deleted that line and made the settings as: CELERY_BROKER_BACKEND = "db+sqlite:///celery.sqlite" CELERY_CACHE_BACKEND = "db+sqlite:///celery.sqlite" CELERY_RESULT_BACKEND = "db+sqlite:///celery.sqlite" Now it works.
accepted answer of: http://stackoverflow.com/q/50580183
answers question: http://stackoverflow.com/q/50580183
upvote count: 7
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/50669774
score: 0
type: Question
has answer: http://stackoverflow.com/a/50669926
has title: django query - show new players count grouped monthwise
tagged with: django-queryset
answer count: 1
accepted answer: http://stackoverflow.com/a/50669926
tagged with: django
tagged with: python
type: AnsweredQuestion
has body: I am trying to create a dashboard in django for a gaming site. I need to show a monthly "new players who joined game" graph. I am already getting total players, and players joined in current month and last 7 days using the following code: queryset = Players.object.all() current_year = datetime.now().year current_month = datetime.now().month one_week_ago = datetime.today() - timedelta(days=7) count['players_all'] = queryset.count count['players_current_month'] = queryset.filter(joined__month=current_month, created_at__year=current_year).count count['players_last_seven_days'] = queryset.filter(joined__gte=last_seven_days).count Now I want to add a new dict which will show me count of players who joined last 12 months, grouped by month. Something like: count['players_last_twelve_months'] = get_players_last_twelve_months() Then I want to define this function get_players_last_twelve_months() such that it will return something like: { Jul:12 Aug:15 Sept:9 Oct:22 Nov:11 Dec:7 Jan:14 Feb:19 Mar:20 Apr:12 May:25 Jun:8 } I am very new to python and django. Using my minimal knowledge I know I can use variations of the queryset.filter I used above like. queryset.filter(joined__month=11, current_year = 2017) queryset.filter(joined__month=12, current_year = 2017) queryset.filter(joined__month=1, current_year = 2018) queryset.filter(joined__month=2, current_year = 2018) However I dont want to hardcode month numbers etc. Can anyone provide me some pointers on the proper way to try to achieve this?

http://stackoverflow.com/q/50638104
has comment: http://stackoverflow.com/comment/88287025
favorite count: 0
has answer: http://stackoverflow.com/a/50639480
tagged with: python
tagged with: magic-methods
tagged with: dictionary
type: AnsweredQuestion
has body: I need a method in a composite class to return the mapping of the instance. class Component: def __init___(self, a, b): self.a = a self.b = b class Entity: def __init__(self, component, c, d): self.component= component self.c = c self.d = d def as_dict(self): mapping_dict = self.__dict__ mapping_dict['component'] = self.component.__dict__ return mapping_dict This solution will only work once when as_dict() method is called for the first time. When it's called for the second time, this would not work since self.entity will now refer to a dictionary and calling __dict__ on it will raise AttributeError. So I came up with a not so efficient solution; def as_dict(self): temp_1 = temp_2 = deepcopy(self) mapping_dict = temp_1.__dict__ mapping_dict['component'] = temp_2.component.__dict__ return mapping_dict This works but not so efficient because I am making a deepcopy of the instance every time I call the function. My question is, why when I call self.entity.__dict__, entity becomes type dict instead of type Entity? What is the mechanism behind this? And also whats the most efficient implementation to obtain a mapping of a composite object?
score: 0
upvote count: 1
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50639480
has title: Generating mapping dictionary of composite object in python
answer count: 1
has comment: http://stackoverflow.com/comment/88286255

http://stackoverflow.com/q/50563745
downvote count: 0
has body: Given a symbolic multivariate polynomial P, I need to extract both its coefficients and corresponding monomials as lists: def poly_decomp(P): .... return coeffs, monoms such that P is the dot product of coefficients and monomials, e.g., if P(x,y) = ax**2 + bxy + cy**2 then we should get coeffs = [a, b, c] and monoms = [x**2, x*y, y**2]. Getting the coefficients is easy since the function is built in coeffs = P.coeffs(). However, I'm having trouble getting the monomials. Here the build in function returns a list of exponents, e.g., in the example above we would get P.monoms() = [(2,0),(1,1),(0,2)]. Obviously the idea would be, provided a list of the variables var=[x,y], to do something like powers = P.monoms() monoms = [sympy.prod(x**k for x,k in zip(var, mon)) for mon in powers ] However the polynomial class doesn't seem to offer a function that returns a list of variables. All I could find were the methods free_symbols and free_symbols_in_domain which return the sets {a, b, c, x, y} and {a, b, c}. So by taking their difference one could get the set {x, y}. However then we are faced with the issue that the sets are unordered, hence converting it into a list might mess up the order in different ways depending on the number of variables. I am kind of at a loss here. Any tips?
type: Question
score: 5
has answer: http://stackoverflow.com/a/72035181
has answer: http://stackoverflow.com/a/50565805
accepted answer: http://stackoverflow.com/a/50565805
possible better answer: http://stackoverflow.com/a/72035181
answer count: 2
tagged with: sympy
tagged with: polynomials
favorite count: 0
tagged with: python-3.x
has title: Extract coefficients and corresponding monomials from a given polynomial in SymPy
upvote count: 5
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/88388499
comment on: http://stackoverflow.com/a/50689263
has text: and could you tell me how to change background color? As I cange the `cmap` both contour and BG are changed.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50553201
tagged with: python-2.7
score: 0
tagged with: importerror
accepted answer: http://stackoverflow.com/a/50588407
tagged with: spyder
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88157965
has comment: http://stackoverflow.com/comment/88148679
upvote count: 1
tagged with: python
has body: I'm still new to Python. I'm having issues when importing spaCy in python (v2.7) which doesn't appear when using it in ipython (v5.4.1). I used to have spaCy 2.0.11 then I reinstalled 2.0.7 and the issue remains. Some useful info about the spaCy model and python version I have : Python version 2.7.14 Platform Darwin-15.5.0-x86_64-i386-64bit spaCy version 2.0.7 Location /Users/AMAL/anaconda2/lib/python2.7/site-packages/spacy Models en_core_web_sm, en_default Thinc version: Name: thinc Version: 6.10.2 Doing import spacy and other imports using ipython doesnt cause any problems, and when using python interpreter in terminal: python Python 2.7.14 |Anaconda custom (64-bit)| (default, Oct 5 2017, 02:28:52) [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import spacy &gt;&gt;&gt; import thinc &gt;&gt;&gt; import thinc.neural &gt;&gt;&gt; from thinc.neural.util import copy_array &gt;&gt;&gt; exit() This is my code: import re import string import math from itertools import chain from spacy.en import English '''Error triggered here''' However, using Spyder IDE first throws this error: File "/Users/AMAL/anaconda2/lib/python2.7/distutils/command/build_ext.py", line 499, in build_extension depends=ext.depends) File "/Users/AMAL/anaconda2/lib/python2.7/distutils/ccompiler.py", line 574, in compile self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) File "/Users/AMAL/anaconda2/lib/python2.7/distutils/unixccompiler.py", line 124, in _compile raise CompileError, msg ImportError: Building module thinc.neural.optimizers failed: ['ImportError: Building module thinc.neural.ops failed: ["CompileError: command \'gcc\' failed with exit status 1\\n"]\n'] Then in the second compile the error is changed and remains the same: Traceback (most recent call last): File "&lt;ipython-input-3-3743c1a24668&gt;", line 1, in &lt;module&gt; runfile('/Users/AMAL/p1', wdir='/Users/AMAL') Fil…
has comment: http://stackoverflow.com/comment/88176103
type: AnsweredQuestion
tagged with: spacy
has comment: http://stackoverflow.com/comment/88117357
linked to: http://stackoverflow.com/q/50584217
has comment: http://stackoverflow.com/comment/88158040
has comment: http://stackoverflow.com/comment/88117474
has answer: http://stackoverflow.com/a/50588407
has comment: http://stackoverflow.com/comment/88119218
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88177614
has comment: http://stackoverflow.com/comment/88117251
has title: ImportError when importing spaCy using Spyder

http://stackoverflow.com/q/50642290
score: 1
has answer: http://stackoverflow.com/a/50642337
has comment: http://stackoverflow.com/comment/88294615
type: Question
upvote count: 1
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/1653970
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50642337
has body: I'm a bit puzzled about the behavior of DataFrame For example: df = pd.DataFrame(data=np.random.random(size=(5,3)), columns={'a', 'b', 'c'}) why the default output is: df = c a b 0 0.325172 0.831253 0.151912 1 0.558476 0.177249 0.906136 2 0.516089 0.069013 0.370251 3 0.440246 0.154116 0.494690 4 0.793981 0.409526 0.885879 and not the ordered list of columns ('a', 'b', 'c') (Python 3.6, Pandas 0.23)
tagged with: python
has title: ordering of column names in Pandas
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/a/50603926
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50603794
type: Answer
has comment: http://stackoverflow.com/comment/88217565
has body: With pandas, avoid combining NaN with integers Unless you have an extremely good reason, avoid this practice. The reason is pandas only allows vectorised computations with arrays in contiguous memory blocks. This is only possible with data of the same type, e.g. a series of type int, float, datetime, but not object. NaN is considered float. Therefore, combining integers with NaN forces pandas to, by default, upcast the entire series to float. This increases memory usage, but for most use cases is not an issue. If you wish to combine NaN with integers, you need to create a series with dtype=object, and have pandas work with a series of pointers. This is expensive computationally and memory-intensive. Do not do it unless you absolutely must. But if you simply must... You can convert a series to object before converting non-NaN elements to integers: df['B'] = df['B'].astype(object) As explained above, you are asking pandas / numpy to work with a pointer for each item in your series. You might as well start working with lists instead.
upvote count: 4
has comment: http://stackoverflow.com/comment/88217854
has comment: http://stackoverflow.com/comment/88289836
downvote count: 0
has comment: http://stackoverflow.com/comment/88289728
score: 4
answers question: http://stackoverflow.com/q/50603794

http://stackoverflow.com/comment/88239586
comment on: http://stackoverflow.com/q/50614844
type: QuestionComment
type: Comment
score: 2
has text: As a side note, dynamically creating a bunch of variables like this is almost always a very bad idea, and doing it with `exec` instead of `globals` or `setattr` is an even worse idea. It's usually be much better to store everything in, e.g., a dict.

http://stackoverflow.com/a/51246476
answers question: http://stackoverflow.com/q/50681800
has body: Shouldn't it be fab -f fabfile.py deploy Anyway, you probably have a messed up install, try: which python Does that match: /Library/Frameworks/Python.framework/Versions/3.6/bin/python
downvote count: 0
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/comment/88166103
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50577552
has text: Possible duplicate of [In TensorFlow, what is the difference between Session.run() and Tensor.eval()?](https://stackoverflow.com/questions/33610685/in-tensorflow-what-is-the-difference-between-session-run-and-tensor-eval)
score: 0

http://stackoverflow.com/q/50696370
has answer: http://stackoverflow.com/a/50696428
answer count: 4
has comment: http://stackoverflow.com/comment/88402092
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88402114
has comment: http://stackoverflow.com/comment/88401997
favorite count: 0
has answer: http://stackoverflow.com/a/50696641
has comment: http://stackoverflow.com/comment/88402314
type: Question
accepted answer: http://stackoverflow.com/a/50696691
tagged with: python
has title: select specific elements of second dimention of a 2D array
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50696671
has comment: http://stackoverflow.com/comment/88402014
has answer: http://stackoverflow.com/a/50696671
score: 0
upvote count: 1
downvote count: 1
has body: I have a list like this in python: a = [[5, -4, 6], [9, 0, 6], [20, -1, 9], [6, 5, -7]] and I have a b array such as this one: b = [0, 1, 2, 0] how can I get this list? [ a[0][b[0]], a[1][b[1]], a[2][b[2]], a[3][b[3]] ] I should mention that the lengths of b and a are both variables n. I know that I can make a list with a loop with these values, but I'm looking for a syntax (something like map) for this. Thanks for any help.
tagged with: list
has comment: http://stackoverflow.com/comment/88432152
has answer: http://stackoverflow.com/a/50696691

http://stackoverflow.com/q/50579236
linked to: http://stackoverflow.com/q/45130837
has title: High precision countdown in python
score: -1
has comment: http://stackoverflow.com/comment/88169666
type: Question
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88170671
has comment: http://stackoverflow.com/comment/88167730
favorite count: 0
has comment: http://stackoverflow.com/comment/88167725
tagged with: python
has comment: http://stackoverflow.com/comment/88169270
linked to: http://stackoverflow.com/q/41777880
has body: I need to implement a countdown timer in python. I tried this, but the program get stuck and I have to do a forced quit. For the same reason, I can't have an infinitive loop into the run() method. How can I do? class th(Thread): def __init__(self): Thread.__init__(self) def run(self): printer() def printer(): print(time.time()*1000.0) time.sleep(1) printer() thread1 = th() thread1.start()
has comment: http://stackoverflow.com/comment/88169425
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50581693
has comment: http://stackoverflow.com/comment/88167734
has comment: http://stackoverflow.com/comment/88167782
has comment: http://stackoverflow.com/comment/88169255
has comment: http://stackoverflow.com/comment/88168040
downvote count: 1
linked to: http://stackoverflow.com/q/44372046

http://stackoverflow.com/q/50587445
has comment: http://stackoverflow.com/comment/88184664
answer count: 1
has comment: http://stackoverflow.com/comment/88184654
favorite count: 0
has comment: http://stackoverflow.com/comment/88184957
type: UnansweredQuestion
tagged with: python
has title: Best practice for creating a complex dict with many formulas
has comment: http://stackoverflow.com/comment/88184796
downvote count: 0
has body: I'm working on a requirement that needs to take several dicts as input arguments and transform/merge them into a single dict as the output, there will be some formulas applied to the input dicts. The output is something like below: (with 50+ fields) output = { 'pnl': 100, 'pnl_usd': 400, 'pnl_eur': 500, 'ytd': 200, 'ytd_usd': 2000, 'ytd_eur': 3000, 'mtd': 300, 'mtd_eur': 300, 'cost': [ {'prod_1': {'labour': 1000, 'material': 2000}}, {'prod_2': {'labour': 2000, 'material': 3000}} ] # many more fields } I wonder what is the best practice of implementing this. Right now our developers defined many local variables first, and then calculate the numbers and then populate the dict and return it. def produce_dict(cost_dict, revenue_dict, date): pnl = revenue_dict.get('revenue') - cost_dict.get('cost') pnl_in_usd = pnl * get_fx_rate(date) pnl_in_usd_prev = pnl * get_fx_rate(date - 1) pnl_mtd = revenue_dict.get('revenue_mtd') - cost_dict.get('cost_mtd') pnl_mtd_in_usd = pnl_mtd * get_fx_rate(date) pnl_mtd_in_usd_prev = pnl_mtd * get_fx_rate(date - 1) daily_pnl_gain = pnl_mtd_in_usd - pnl_mtd_in_usd_prev # many more local variables here return {'pnl': pnl, 'pnl_in_usd': pnl_in_usd, etc.etc...} Is there a cleaner way of doing this, separate the calculation logic out of building the dict? Thanks.
tagged with: design-patterns
has comment: http://stackoverflow.com/comment/88184622
type: Question
has comment: http://stackoverflow.com/comment/88184825
has comment: http://stackoverflow.com/comment/88184528
score: 1
has comment: http://stackoverflow.com/comment/88184490
has answer: http://stackoverflow.com/a/50587731
has comment: http://stackoverflow.com/comment/88184338
upvote count: 1

http://stackoverflow.com/comment/88240948
comment on: http://stackoverflow.com/q/50615396
type: Comment
type: QuestionComment
has text: How do you expect to get help if we don't know what you did?
score: 0

http://stackoverflow.com/a/50542728
accepted answer of: http://stackoverflow.com/q/50542683
upvote count: 15
has body: The code in the blog post is aimed at Python 2, where writing to and reading from a file works with bytestrings. In Python 3, you need to open the file in binary mode, both for writing and then reading again: np.save( open('bottleneck_features_train.npy', 'wb'), bottleneck_features_train) And when reading: train_data = np.load(open('bottleneck_features_train.npy', 'rb')) Note the b character in the mode arguments there. I'd use the file as a context manager to ensure it is cleanly closed: with open('bottleneck_features_train.npy', 'wb') as features_train_file np.save(features_train_file, bottleneck_features_train) and with open('bottleneck_features_train.npy', 'wb') as features_train_file: train_data = np.load(features_train_file) The code in the blog post should use both of these changes anyway, because in Python 2, without the b flag in the mode text files have platform-specific newline conventions translated, and on Windows certain characters in the stream will have specific meaning (including causing the file to appear shorter than it really is if a EOF characte appears). With binary data that could be a real problem.
type: AcceptedAnswer
downvote count: 0
score: 15
type: Answer
answers question: http://stackoverflow.com/q/50542683

http://stackoverflow.com/comment/88108066
type: Comment
comment on: http://stackoverflow.com/a/50548458
score: 0
type: AnswerComment
has text: @wwii Yes, although I realized that it needed to be a separate condition in the regex.

http://stackoverflow.com/q/50694774
has title: View that calls endpoint?
tagged with: django
upvote count: 1
accepted answer: http://stackoverflow.com/a/50694894
has body: I am using the REST framework package for Django. I am trying to create a way to handle a POST request when a follow button is pressed. So far on the API View side I have this: class FollowToggle(APIView): def post(self, id=None): target = get_object_or_404(User, id=id) follower = self.request.user if follower.is_authenticated(): if follower in target.followers.all(): target.followers.delete(follower) else: target.followers.create(follower) data = { "success": 1 } return Response(data) Now what I'd like to do is using my ProfileView, I'd like to handle POST requests by executing the APIView I created with the specific parameters. How do I do this? class ProfileView(DetailView): model = User slug_field = 'username' template_name = 'accounts/profile.html' if request.method == 'POST': //Call the API with the parameters
type: Question
answer count: 1
downvote count: 0
tagged with: django-rest-framework
favorite count: 0
has answer: http://stackoverflow.com/a/50694894
tagged with: python
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/50604948
type: Question
score: 8
has answer: http://stackoverflow.com/a/55326428
answer count: 6
has answer: http://stackoverflow.com/a/50605227
possible better answer: http://stackoverflow.com/a/55326428
tagged with: mysql-python
downvote count: 0
has answer: http://stackoverflow.com/a/59423531
has answer: http://stackoverflow.com/a/53044225
favorite count: 0
upvote count: 8
has body: Trying to install from pipenv with: pipenv install mysqlclient will reseult in: Installing mysqlclient… Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/6f/86/bad31f1c1bb0cc99e88ca2adb7cb5c71f7a6540c1bb001480513de76a931/mysqlclient-1.3.12.tar.gz Complete output from command python setup.py egg_info: /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "", line 1, in File "/tmp/pip-install-5vhtqgve/mysqlclient/setup.py", line 17, in metadata, options = get_config() File "/tmp/pip-install-5vhtqgve/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/tmp/pip-install-5vhtqgve/mysqlclient/setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found ---------------------------------------- Error: An error occurred while installing mysqlclient! Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-5vhtqgve/mysqlclient/ This is likely caused by a bug in mysqlclient. Report this to its maintainers. I'm using a Debian and with another virtualenv it get the system package python-mysqldb/testing,now 1.3.10-1 amd64 Pipenv won't use this one and won't install the other. How can I solve this? Thanks,BR
has answer: http://stackoverflow.com/a/54663428
tagged with: python
accepted answer: http://stackoverflow.com/a/50605227
type: AnsweredQuestion
has title: Python3 - Pipenv install mysqlclient?
has answer: http://stackoverflow.com/a/51235071

http://stackoverflow.com/q/50641588
has title: How to create a tensorflow dataset from a DataFrame with vector columns?
type: AnsweredQuestion
upvote count: 5
tagged with: dataframe
has answer: http://stackoverflow.com/a/50647478
type: Question
answer count: 2
score: 5
tagged with: pandas
has body: So I have some train data in a csv file train.csv with the following format: x;y;type [1,2,3];[2,3,4];A [2,7,9];[0,1,2];B This file is parsed as a pd.DataFrame with the following: CSV_COLUMN_NAMES = ['x', 'y', 'type'] train = pd.read_csv("train.csv", names=CSV_COLUMN_NAMES, header=0, delimiter=";") train['x'] = train['x'].apply(literal_eval) train['y'] = train['y'].apply(literal_eval) So far so good. The literal_eval function is applied so x and y are treated as array. The next step is to create a DataSet with the following: features, labels = train, train.pop('type') dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels)) And here is where it breaks :( It spills the following errors: TypeError: Expected binary or unicode string, got [1, 2, 3] Why is binary or unicode string expected? Are vector feature columns not allowed? Or am I doing something wrong? Please shed me some light
downvote count: 0
has answer: http://stackoverflow.com/a/50672278
favorite count: 0
linked to: http://stackoverflow.com/q/19459017
possible better answer: http://stackoverflow.com/a/50672278
accepted answer: http://stackoverflow.com/a/50647478
tagged with: python
tagged with: tensorflow

http://stackoverflow.com/comment/88333876
comment on: http://stackoverflow.com/q/50661871
type: QuestionComment
type: Comment
has text: Then don't use a dictionary, use a list.
score: 1

http://stackoverflow.com/q/50694360
score: -1
tagged with: file-io
answer count: 1
accepted answer: http://stackoverflow.com/a/50694383
favorite count: 0
tagged with: python-3.x
downvote count: 2
tagged with: python
type: AnsweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/50694383
type: Question
linked to: http://stackoverflow.com/q/2545532
has title: Reading files in directory in sorted order Python
has body: I have a folder in which I have files like 1.jpg, 2.jpg, ... 40.jpg; root_dir = r'C:\Users\ab\pythonfiles\Compressed_images' for root, dirs, files in os.walk(root_dir): for file in files: print(file, '\n') It prints this 1.jpg 10.jpg 11.jpg ... 19.jpg 2.jpg 20.jpg ... I want it to read in the order 1.jpg, 2.jpg, 3.jpg, ... ; how can I achieve this?
duplicate of: http://stackoverflow.com/q/2545532

http://stackoverflow.com/comment/88228891
has text: Please fix the indentation in the code you posted. In the future, to post code, paste it in, select it, and click the `{}` widget. That will shift every line over 4 spaces, causing it to be rendered as code. Best to avoid tabs in the original code, especially with Python.
comment on: http://stackoverflow.com/q/50609491
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50623713
answers question: http://stackoverflow.com/q/50621933
type: Answer
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50621933
has body: Solved it myself. In-case anyone needs to reuse the code - orig_list = ['Married-spouse-absent', 'Married-AF-spouse', 'Separated', 'Married-civ-spouse', 'Widowed', 'Divorced', 'Never-married'] k_folds = 3 cols = df.columns # ['fnlwgt_bucketed', 'Married-spouse-absent_fold_0', 'Married-AF-spouse_fold_0', 'Separated_fold_0', 'Married-civ-spouse_fold_0', 'Widowed_fold_0', 'Divorced_fold_0', 'Never-married_fold_0', 'Married-spouse-absent_fold_1', 'Married-AF-spouse_fold_1', 'Separated_fold_1', 'Married-civ-spouse_fold_1', 'Widowed_fold_1', 'Divorced_fold_1', 'Never-married_fold_1', 'Married-spouse-absent_fold_2', 'Married-AF-spouse_fold_2', 'Separated_fold_2', 'Married-civ-spouse_fold_2', 'Widowed_fold_2', 'Divorced_fold_2', 'Never-married_fold_2'] for folds in range(k_folds): for column in orig_list: col_namer = [] for fold in range(k_folds): if fold != folds: col_namer.append(column+'_fold_'+str(fold)) df = df.withColumn(column+'_fold_'+str(folds)+'_mean', (sum(df[col] for col in col_namer)/(k_folds-1))) print(col_namer) df.show(1)

http://stackoverflow.com/comment/88344740
score: 1
has text: I edited my reply after realizing that the '"' character is not actually escaped by the `text` method (but that's ok and that's still the method that you should use).
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50660214

http://stackoverflow.com/a/50656487
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50656472
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50656472
type: Answer
score: 4
has body: Use a list-comprehension: lst = ['michelle rodriguez', 'dexter king', 'gurukavari'] print([x.split()[0] for x in lst]) # ['michelle', 'dexter', 'gurukavari']

http://stackoverflow.com/comment/88190033
type: Comment
type: QuestionComment
has text: I don't want to change my input data, it's very important to keep them unchanged. @sascha Exactly, but the scipy.optimize.nnls library is a black box and I don't know how to change it to get multiple solutions.
comment on: http://stackoverflow.com/q/50587012
score: 0

http://stackoverflow.com/q/50653986
favorite count: 0
has comment: http://stackoverflow.com/comment/88318400
tagged with: imgkit
tagged with: python
has answer: http://stackoverflow.com/a/50654062
accepted answer: http://stackoverflow.com/a/50654062
tagged with: wkhtmltopdf
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/52082123
downvote count: 0
has comment: http://stackoverflow.com/comment/88318398
score: 1
has comment: http://stackoverflow.com/comment/88318436
has comment: http://stackoverflow.com/comment/91128530
has title: Why I am getting these two errors? [wkhtmltoimage]
type: Question
has body: Environment I am currently working: Windows 10 Python27 wkhtmltoimage 0.12.4 imgkit module This is my example.py import os import imgkit imgkit.from_url('http://google.com', 'C:\out.jpg') As this code clearly shows that I am trying to take the screenshot of the google website. But when I run this code in Windows 10 platform what I got, this errors. INFO: Could not find files for the given pattern(s). Traceback (most recent call last): File "C:\testdns.py", line 3, in &lt;module&gt; imgkit.from_url('http://google.com', 'C:\out.jpg') File "C:\Python27\lib\site-packages\imgkit\api.py", line 32, in from_url return rtn.to_img(output_path) File "C:\Python27\lib\site-packages\imgkit\imgkit.py", line 240, in to_img raise IOError('wkhtmltoimage reported an error:\n' + stderr) IOError: wkhtmltoimage reported an error: Loading page (1/2) Rendering (2/2) Error: Could not write to output file Error: Could not save image Done Exit with code 1, due to unknown error. Now I don't know how to proceed
tagged with: python-2.7
upvote count: 1
answer count: 1

http://stackoverflow.com/q/50684429
possible better answer: http://stackoverflow.com/a/50684680
has answer: http://stackoverflow.com/a/50684680
has title: Count occurrences of string in lines with boolean AND
has body: I'm very new to Python but have a need to read the lines of a text file and count the occurrences of multiple strings using boolean AND. For instance, if a particular line contains 'blue' AND 'green' I need to count the number of lines this is true for. This is what I have so far. import re file = open("text.txt") lines = file.readlines() print(lines.count('blue') file.close() Your assistance is appreciated.
has comment: http://stackoverflow.com/comment/88378816
tagged with: string
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: text
score: 2
has answer: http://stackoverflow.com/a/50684608
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/88378837
accepted answer: http://stackoverflow.com/a/50684608
downvote count: 1
type: Question
answer count: 2

http://stackoverflow.com/a/55304529
type: Answer
upvote count: 0
has body: Use os.walk to access all the files in sub-directories recursively and append to the dataset.
score: -1
answers question: http://stackoverflow.com/q/50664485
downvote count: 1

http://stackoverflow.com/a/50653167
has body: Combined use of itertools.cycle and itertools.islice. Code: from itertools import cycle, islice def pivot_sort(lst, pivot): sorted_lst = sorted(lst) return list(islice(cycle(sorted_lst), sorted_lst.index(pivot), 2*len(sorted_lst)-lst.index(pivot))) lst = [25, 35, 54, 70, 68, 158, 78, 11, 18, 12] pivot = 70 print(pivot_sort(lst, pivot)) # [70, 78, 158, 11, 12, 18, 25, 35, 54, 68]
score: 0
answers question: http://stackoverflow.com/q/50652847
type: Answer

http://stackoverflow.com/q/50632386
upvote count: 2
tagged with: fabric
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/50807250
score: 2
tagged with: environment-variables
downvote count: 0
type: UnansweredQuestion
favorite count: 0
has title: Fabric 2.0.1 What is the replacement for env?
type: Question
has body: I have an old fabfile.py (Fabric 1.8.3) which has the following line: env.key_filename = '/etc/appliance/fabric/id_rsa' How do I do the same in Fabric 2.0.1? I tried using fab with -i option. But it doesn't seem to be working.
tagged with: ssh
tagged with: python-3.x

http://stackoverflow.com/comment/88395963
type: Comment
comment on: http://stackoverflow.com/a/50692884
score: 2
has text: This has the same problem as the first: Since the reader defaults to comma delimiter, each row is read as one column and the hack is to split that with tabs. The real solution is to change the delimiter.
type: AnswerComment

http://stackoverflow.com/comment/88294146
type: Comment
comment on: http://stackoverflow.com/q/50642064
score: 0
type: QuestionComment
has text: Your shell doesn't interpret `\n` as a line break. Is that bash you're using?

http://stackoverflow.com/a/50581013
accepted answer of: http://stackoverflow.com/q/50579184
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: To get a valid matplotlib RGB color array from a tuple of RGB values in the range between 0 and 255 you may simply divide by 255. color = np.array((R,G,B)) / 255. To get a figure without axes that clip the artist you may pin the axes to the edge of the figure fig, ax = plt.subplots() fig.subplots_adjust(0,0,1,1) ax.axis("off") To read in a file you may use open with open("filename", "rb") as f content = f.readlines() depending on the format of the file you may use numpy instead to directly get the numbers into an array, arr = np.loadtxt("filename")
answers question: http://stackoverflow.com/q/50579184
type: Answer

http://stackoverflow.com/a/50577679
has body: PyX uses the postscript path model, which can contain several subpaths within a path. (Think of using a path element moveto within a path.) When filling such paths, things like you observe happen. Note that the arc contains an implicit moveto at the beginning, which for filling is taken like a lineto, but not for stroking. This is why it makes a difference to use the add operator + and the join operator &lt;&lt;. Switching to join resolves your problem. (You can use print(p.normpath().normsubpaths) to see, that you have several normsubpaths when adding the paths, even though the arclen does not alter, as the moveto commands from one normsubpath to the next are not part of the arc length.)
accepted answer of: http://stackoverflow.com/q/50570100
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50570100
has comment: http://stackoverflow.com/comment/88219600
type: Answer
has comment: http://stackoverflow.com/comment/88202792
has comment: http://stackoverflow.com/comment/88179397
score: 1
upvote count: 1

http://stackoverflow.com/q/50621541
has body: Firstly, I created a dataframe like this: df = pd.read_csv('d:\etc\quotes.csv', sep=';', parse_dates = [[0,1]], header = None, names = ['date', 'time', 'open', 'high', 'low', 'close', 'vol'], index_col = "date_time") After that, I tried to use .loc to access values: df.loc[:'open'] and get an error: Traceback (most recent call last): File "pandas_libs\tslibs\parsing.pyx", line 173, in pandas._libs.tslibs.parsing.parse_datetime_string_with_reso File "pandas_libs\tslibs\parsing.pyx", line 325, in pandas._libs.tslibs.parsing.dateutil_parse ValueError: Unknown datetime string format, unable to parse: open Why? I'm a novice in pandas.
has comment: http://stackoverflow.com/comment/88253259
has comment: http://stackoverflow.com/comment/88254042
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88253885
tagged with: dataframe
type: Question
has comment: http://stackoverflow.com/comment/88253029
score: 0
tagged with: pandas
has title: ValueError: Unknown datetime string format, unable to parse
answer count: 1
has comment: http://stackoverflow.com/comment/88253131
has answer: http://stackoverflow.com/a/50621828

http://stackoverflow.com/comment/88349525
has text: @khepu I know this won't get exact but atleast i can adjust range to get it close, so total_count/range gives me a whole number how do I go about turning this into a percentage
comment on: http://stackoverflow.com/a/50669835
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50649794
answer count: 1
tagged with: keras
has body: Is it possible in keras add external input to Merge layer? I have simple embedding which I would like to combine with external values, but every time I try to do I always get error. Is there way to add external input to Keras layers? models = [] inputs =Input(shape=(10,)) models.append(inputs) for i in range(2): model_s = Sequential() model_s.add(Embedding(1115, 10, input_length=1, name='Hb_{}'.format(i))) model_s.add(Reshape(target_shape=(10,))) models.append(model_s) model = Sequential() model.add(Merge(models, mode='concat')) model.add(Dense(1000, kernel_initializer='uniform')) model.add(Activation('relu')) model.add(Dense(500, kernel_initializer='uniform')) model.add(Activation('relu')) model.add(Dense(1)) model.add(Activation('sigmoid')) model.summary() Error Tensor' object has no attribute 'get_output_shape_at' This is the small code for testing. model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy']) m={'Hb_0_input': np.array([0,1, 2, 3, 4, 5, 6, 7, 8, 9]),'Hb_1_input': np.array([0,1, 2, 3, 4, 5, 6, 7, 8, 9]), 'x': np.array([0,1, 2, 3, 4, 5, 6, 7, 8, 9])} y=np.array([0, 1, 0, 1, 0, 1, 0, 0, 0, 0]) model.fit(m, y)
accepted answer: http://stackoverflow.com/a/50650039
tagged with: python
type: AnsweredQuestion
has title: Combine Layers with Input
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/50650039
has comment: http://stackoverflow.com/comment/88310512
score: 0

http://stackoverflow.com/comment/88325914
type: QuestionComment
has text: @StephenRauch You miss quoted me. "no one `seams` to want to point it out ". Is not the same thing. When you are quoting someone and you remove or add words you are altering the meaning. I didn't say you didn't try to help. In fact I appreciate all the input. I always do. Lastly I always ask for a reason for a downvote if I get them. I cannot improve my questions if I don't know why the downvote exist.
comment on: http://stackoverflow.com/q/50652766
score: 0
type: Comment

http://stackoverflow.com/comment/88321555
type: AnswerComment
comment on: http://stackoverflow.com/a/50645807
type: Comment
has text: The project worked fine yesterday. But now when I have restarted my machine, the project has again started giving the old error. Do I need to do anything on machine reboot?
score: 0

http://stackoverflow.com/q/50555817
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
has title: Django annotate queryset with intersection count
type: Question
has answer: http://stackoverflow.com/a/50556734
tagged with: django-models
linked to: http://stackoverflow.com/q/51504634
tagged with: django-queryset
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50556734
has body: Djangonauts, I need to tap your brains. In a nutshell, I have the following three models: class Location(models.Model): name = models.CharField(max_length=100) class Profile(models.Model): locations_of_interest = models.ManyToManyField(Location) class Question(models.Model): locations = models.ManyToManyField(Location) I want to find all Profiles which locations of interest intersect with the locations specified for a certain question. That’s easy: question = Question.objects.first() matching_profiles = Profile.objects.filter( locations_of_interest__in=question.locations.all() ) But in addition, I would also like to know to what extend the locations overlap. In plain python, I could do something like this: question_location_names = [l['name'] for l in question.locations.all()] for profile in matching_profiles: profile_location_names = [l['name'] for l in profile.locations_of_interest.all()] intersection = set(question_location_names).intersection(profile_location_names) intersection_count = len(list(intersection)) # then proceed with this number However, it seems to me favourable to do the operation directly in the database if possible. TL;DR So my question is: Is there a way to annotate the profile queryset with this intersection count and that way do the operation in the database? I have tried several things, but I don’t think they are helpful for those who read this and might know an answer.
favorite count: 0
tagged with: django

http://stackoverflow.com/a/50642832
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You have defined a custom method, partList, but it is not being called from anywhere. The method is pointless and you should delete it. If you want to add data to the template context in a class-based view, you need to define get_context_data. However there is no reason to do that here as it would just do what ListView does for you anyway. You should use the variable that the view automatically populates, which is object_list. {% for object in object_list %} {{ object.Party_number }} {% endfor %}
score: 2
answers question: http://stackoverflow.com/q/50642728
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50642728

http://stackoverflow.com/q/50576457
has body: can someone explain this, I understand that some sort of lazy initialization is taking place, but unable to find any documentation/support for the same. a = [[0]*3]*3 a[0][0] = 1 print(a) output: [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
has title: Python 3.6.2 lazy initialization of two dimensional list
type: Question
score: 0
has comment: http://stackoverflow.com/comment/88162058
linked to: http://stackoverflow.com/q/240178
has comment: http://stackoverflow.com/comment/88162065
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/240178
answer count: 0
has comment: http://stackoverflow.com/comment/88162511
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/66301115
answers question: http://stackoverflow.com/q/50619294
score: 0
has body: There is two possible way to do that: Either you can write the content to the file or you can create a link (either redirected to the browser or just get a downloadable link ) First way: metadata, response = dbx.files_download(file_path+filename) with open(metadata.name, "wb") as f: f.write(response.content) Second way: link = dbx.sharing_create_shared_link(file_path+filename) print(link.url) if you want link to be downloadable then replace 0 with 1: path = link.url.replace("0", "1")
type: Answer

http://stackoverflow.com/comment/88388037
has text: First, it's not finding all the values, it's finding just the first one, and then treating the others as subtags within that tag. For example, you can `print(price_box['content'])` and you're going to get `274.9`, just as you'd hope.
type: QuestionComment
comment on: http://stackoverflow.com/q/50689088
type: Comment
score: 1

http://stackoverflow.com/q/50580481
linked to: http://stackoverflow.com/q/2136556
upvote count: 2
type: AnsweredQuestion
has body: I am trying to split a string, but keep all separators bundled together in a separate list. s = "This is a test for \n a string" should results in a = ["This", "is", "a", "test", "for", "a", "string"] b = [" ", " ", " ", " ", " \n ", " "] Any idea on how to handle that?
downvote count: 3
score: -1
has comment: http://stackoverflow.com/comment/88170277
has answer: http://stackoverflow.com/a/50580519
type: Question
tagged with: split
answer count: 1
has title: Split string while retaining whitespace separators
accepted answer: http://stackoverflow.com/a/50580519
tagged with: string
has comment: http://stackoverflow.com/comment/88170348
has comment: http://stackoverflow.com/comment/88170397
tagged with: python
tagged with: regex
favorite count: 0

http://stackoverflow.com/a/75909942
type: Answer
answers question: http://stackoverflow.com/q/50656471
has body: selector = GeneticSelectionCV(estimator=None,//check this scoring=evaluate, cv=5, verbose=1, n_population=50, crossover_proba=0.5, mutation_proba=0.2, n_generations=40, crossover_independent_proba=0.5, mutation_independent_proba=0.05, tournament_size=3, caching=True, n_jobs=-1) I was also troubled by this today, but I later discovered that the reason is that the estimator needs to pass in a variable.
score: 0

http://stackoverflow.com/comment/88227183
score: 3
comment on: http://stackoverflow.com/a/50608296
type: AnswerComment
type: Comment
has text: Yes, you almost never use cells directly if you already have sequences. Because even though cells are subclasses of Layer they have a slightly different call signature to take into account states etc.

http://stackoverflow.com/comment/88354484
type: Comment
has text: Thank you @David. This is a great suggestion! Instead of using the words from 'brown' corpus, do you think I could use a list of legitimate names I already have to train the model?
type: AnswerComment
comment on: http://stackoverflow.com/a/50661395
score: 0

http://stackoverflow.com/a/50657097
type: Answer
score: 1
upvote count: 1
has body: One way is to perform your two sorts separately and then combine. Given a list A of OrderedDict objects: from operator import itemgetter # retrieve threshold threshold = A[1]['Totalsecs'] # sort above threshold sort1 = sorted((i for i in A if i['Totalsecs'] &gt;= threshold), key=itemgetter('Totalsecs')) # sort below threshold sort2 = sorted((i for i in A if i['Totalsecs'] &lt; threshold), key=itemgetter('Totalsecs')) # combine into one list res = sort1 + sort2 print(res) [OrderedDict([('song', 'Goses'), ('lyric', 'recrea'), ('Music', 'reutser'), ('BGM', 'DJS'), ('Totalsecs', 158.514553868968)]), OrderedDict([('song', 'Hoses'), ('lyric', 'crea'), ('Music', 'reut'), ('BGM', 'DJU'), ('Totalsecs', 223.457894215)]), OrderedDict([('song', 'reoses'), ('lyric', 'arecrea'), ('Music', 'hiureut'), ('BGM', 'VJU'), ('Totalsecs', 11.879461215421)]), OrderedDict([('song', 'reteoses'), ('lyric', 'makuri'), ('Music', 'reut'), ('BGM', 'DJU'), ('Totalsecs', 123.513353868968)])]
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50656958
answers question: http://stackoverflow.com/q/50656958

http://stackoverflow.com/q/50549439
tagged with: pyqt5
upvote count: 1
has body: I want to get data from 2 plot at the same time, so I need to sync 2 plot x-axis. However, it was a low tolerance between 2 plot x-axis. I try to use setLimits and setXRange to improve, but it seems no help on it. Am I use it right? Since the code is too long, the following is a part of code: class CandlestickItem(pg.GraphicsObject): def __init__(self, data): pg.GraphicsObject.__init__(self) self.data = data ## data must have fields: time, open, close, min, max self.generatePicture() def generatePicture(self): ## pre-computing a QPicture object allows paint() to run much more quickly, ## rather than re-drawing the shapes every time. self.picture = QtGui.QPicture() p = QtGui.QPainter(self.picture) p.setPen(pg.mkPen('k')) # w = (self.data[1][0] - self.data[0][0]) / 3. w = 1 / 3. index = 0 for (t, close, max, min, open) in self.data: if open &gt; close: p.setBrush(pg.mkBrush('r')) p.setPen(pg.mkPen('r')) else: p.setBrush(pg.mkBrush('g')) p.setPen(pg.mkPen('g')) p.drawLine(QtCore.QPointF(index, min), QtCore.QPointF(index, max)) p.drawRect(QtCore.QRectF(index-w, open, w*2, close-open)) index = index + 1 p.end() def paint(self, p, *args): p.drawPicture(0, 0, self.picture) def boundingRect(self): ## boundingRect _must_ indicate the entire area that will be drawn on ## or else we will get artifacts and possibly crashing. ## (in this case, QPicture does all the work of computing the bouning rect for us) return QtCore.QRectF(self.picture.boundingRect()) Time string axis: class TimeAxisItem(pg.AxisItem): def __init__(self, xdict, *args, **kwargs): pg.AxisItem.__init__(self, *args, **kwargs) # self.x_values = np.asarray(xdict.keys()) self.x_values = list(xdict.keys()) self.x_strings = list(xdict.values()) def tickStrings(self, values, scale, spacing): strings = [] for v in values: # vs is the original tick value vs = int(v * scale) # if we have vs in our values, show the string # otherwise show nothing if vs in self.x_values: vstr = datetime.fromtimestamp(self.x_strings[vs]).st…
type: Question
linked to: http://stackoverflow.com/q/44612914
has comment: http://stackoverflow.com/comment/88113098
tagged with: pyqt
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: pyqtgraph
has title: How to sync x-axis in 2 plot in pqytgraph
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/88109753

http://stackoverflow.com/comment/88128525
comment on: http://stackoverflow.com/a/50558891
score: 0
type: AnswerComment
has text: My File_B doesn't use that idiom. Also, I think with just the import statement the stdin args would be preserved?
type: Comment

http://stackoverflow.com/q/50584182
has title: how to solve IndexError: list assignment index out of range error?
tagged with: python
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/88177981
type: Question
accepted answer: http://stackoverflow.com/a/50584472
score: 1
has comment: http://stackoverflow.com/comment/88177662
tagged with: python-2.7
has answer: http://stackoverflow.com/a/50584472
upvote count: 1
answer count: 1
favorite count: 0
has body: I wrote a code for solving ode using rk4 method. Here is the code: from __future__ import division import math import numpy as np from math import exp def f(t,y): return 5*t**2-y/math.e**(t+y) def rk4(t,y,h,i): p=[0]*i p[0] = y for n in range(0,i): g=11 k1=round(h*f((t+n*h),y),g) k2=round(h*f((t+n*h)+(h/2),y+k1/2),g) k3=round(h*f((t+n*h)+h/2,y+k2/2),g) k4=round(h*f((t+n*h)+h,y+k3),g) p[n+1]=p[n]+(1/6)*(k1+2*k2+2*k3+k4) print(k1,k2,k3,k4) a=rk4(0,1,0.1,3) print(a) When I try to print the k's coefficient,it shows list assignment index out of range error and when I try to print the value of p,output is [1, 0.9666652135433333, 0] I don't understand why the third item is 0. How do I solve these problems?

http://stackoverflow.com/comment/88227886
comment on: http://stackoverflow.com/a/50608890
type: Comment
has text: Using pandas for year, never head of `.query'. Is there a way to name to indices s.t. these names can be used instead of 'ilevel_0', 'ilevel_1' etc.?
score: 1
type: AnswerComment

http://stackoverflow.com/comment/88243168
type: Comment
comment on: http://stackoverflow.com/q/50616680
type: QuestionComment
has text: Can you provide some code? and, do you mean `Dropout` by "kill"?
score: 1

http://stackoverflow.com/comment/88239953
type: QuestionComment
comment on: http://stackoverflow.com/q/50614980
has text: At this point, I am thinking that "apple" in "appler" should not return true. So it should only return true if "apple"+some other stuff (like "apple SDGSD"). But either way is fine.
score: 0
type: Comment

http://stackoverflow.com/comment/88402014
score: 4
has text: `[ai[bi] for ai, bi in zip(a, b)]`
type: Comment
comment on: http://stackoverflow.com/q/50696370
type: QuestionComment

http://stackoverflow.com/comment/88394238
type: AnswerComment
has text: Made it work, I completely forget the % thingy, thanks!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50692359

http://stackoverflow.com/a/50684963
has comment: http://stackoverflow.com/comment/88382221
has comment: http://stackoverflow.com/comment/88536640
has body: You can use re.findall: import re s = 'via I-405/I-65/I-5258 min. 46 sec.' [timestamp] = re.findall('\d{1}\smin\.\s\d+\ssec', s) final_result = '.'.join(re.findall('\d+', timestamp)) Output: '8.46' Edit: you can use BeautifulSoup to find the destination, and then use str.replace: from bs4 import BeautifulSoup as soup import re s = """ via I-405/I-65/I-525 58 min. 8 sec. """ destination = soup(s, 'html.parser').find('b').text timestamp = '.'.join(re.findall('\d+', soup(s, 'html.parser').find('div').text.replace(destination, ''))) Output: 'via I-405/I-65/I-525' '58.8' Edit: instead of iterating over BWLinkNames[key], simple utilize BWLinkNames[key]: for i, key in enumerate(BWLinkNames): worksheet.write(i, col, key) worksheet.write(i, col + 1, BWLinkNames[key]) workbook.close()
has comment: http://stackoverflow.com/comment/88379828
has comment: http://stackoverflow.com/comment/88542915
has comment: http://stackoverflow.com/comment/88383928
has comment: http://stackoverflow.com/comment/88548050
has comment: http://stackoverflow.com/comment/88381836
type: Answer
has comment: http://stackoverflow.com/comment/88387508
has comment: http://stackoverflow.com/comment/88387567
upvote count: 1
has comment: http://stackoverflow.com/comment/88548045
has comment: http://stackoverflow.com/comment/88547522
has comment: http://stackoverflow.com/comment/88387791
has comment: http://stackoverflow.com/comment/88547491
accepted answer of: http://stackoverflow.com/q/50684882
score: 1
has comment: http://stackoverflow.com/comment/88387671
has comment: http://stackoverflow.com/comment/88547625
answers question: http://stackoverflow.com/q/50684882
has comment: http://stackoverflow.com/comment/88541006
has comment: http://stackoverflow.com/comment/88379793
has comment: http://stackoverflow.com/comment/88536939
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50669566
has comment: http://stackoverflow.com/comment/88382689
answer count: 0
type: UnansweredQuestion
has title: Illegal Instruction (core dumped) when starting eager execution
upvote count: 1
tagged with: tensorflow
has body: On a fresh instance of Ubuntu 18.04 LTS, I've installed tensor flow (version 1.8.0) with pip install tensorflow sudo apt install python-tk pip install matplotlib My main.py file: from __future__ import absolute_import, division, print_function import os import matplotlib.pyplot as plt import tensorflow as tf import tensorflow.contrib.eager as tfe tf.enable_eager_execution() print("TensorFlow version: {}".format(tf.VERSION)) print("Eager execution: {}".format(tf.executing_eagerly())) However, when running "python main.py" I get Illegal instruction (core dumped) Any tips on what I might have done wrong, or what I can try to fix this? I've already tried downgrading to 1.7.0 (and 1.5.0, but that didn't have eager execution). Source: https://www.tensorflow.org/get_started/eager Edit: Moved pip/install commands to code block for clarity
type: Question
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88392409
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/88340725
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50665379
type: QuestionComment
has text: Wouldn't you **want** to get an error if you are trying to remove and element that doesn't exist? I mean... you thought it was there - but it's not - I would think this is an error that you would want to know about.

http://stackoverflow.com/a/50557530
answers question: http://stackoverflow.com/q/50554068
type: AcceptedAnswer
type: Answer
upvote count: 1
score: 1
has body: It seems like you want to perform symbolic differentiation or automatic differentiation which np.gradient does not do. sympy is a package for symbolic math and autograd is a package for automatic differentiation for numpy. For example, to do this with autograd: import autograd.numpy as np from autograd import grad def function(x): return 0.5 * np.dot(np.dot(np.transpose(x), A), x) + np.dot(np.transpose(b), x) A = A = np.zeros((2, 2)) n = A.shape[0] A[range(n), range(n)] = 1 b = np.ones(2) x = np.ones(2) grad(function)(x) Outputs: array([2., 2.])
accepted answer of: http://stackoverflow.com/q/50554068
downvote count: 0

http://stackoverflow.com/q/50623552
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/50623608
has answer: http://stackoverflow.com/a/50623772
favorite count: 0
tagged with: python-3.x
has title: How to get all possible combinations from a list in python allowing repetition
tagged with: python
type: AnsweredQuestion
tagged with: list
score: 1
accepted answer: http://stackoverflow.com/a/50623772
has comment: http://stackoverflow.com/comment/88256868
upvote count: 1
type: Question
tagged with: combinations
tagged with: python-itertools
has body: I have a list like [1,2,3] and I want to get the following result: 1 1,1 1,1,1 1,2 1,2,1 1,2,2 1,2,3 1,2 1,3 1,3,3 2,1,2 2,2,1 3,1,1 etc I've tried using itertools, but I only get the combinations without repetition. Does anyone know how could I get a list with the desired result?
has answer: http://stackoverflow.com/a/50623608

http://stackoverflow.com/a/51810785
downvote count: 0
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/50690999
has body: The issue here is that your training batch size (--train_batch_size=4) is too small. You need to have a larger batch size. See Tradeoff batch size vs. number of iterations to train a neural network to get a better idea on choosing a more accurate value.
score: 2

http://stackoverflow.com/comment/88394332
has text: A little confused by what you mean through `hashtag.locations.all()`. Is that not a text field? Did you perhaps want the hashtag.locations to be a ManyToMany field to a `Locations` model?
comment on: http://stackoverflow.com/q/50692214
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50575056
upvote count: 1
downvote count: 1
has body: I have the following dateframe. I would like to groupby mean every hour but still preserv the hours datetime info. date A I r z 0 2017-08-01 00:00:00 3 56 4 6. 1 2017-08-01 00:00:01 3 57 1 6 2 2017-08-01 00:00:03 3 58 9 6 3 2017-08-01 00:00:05 3 52 10 2. 4 2017-08-01 00:00:06 3 50 1 1 df.groupby(df['date'].dt.hour).mean() date A I r z 0 3 56 4 6. 1 3 57 1 6 2 3 58 9 6 3 3 52 10 2. 4 3 50 1 1 I would like to have as an index the same date before such as 2017-08-01 00:00:00 datetime64[ns] How can I achieve this output in Python? Output desired: date A I r z 0 2017-08-01 00:00:00 3 56 4 6. 1 2017-08-01 01:00:00 3 57 1 6 2 2017-08-01 02:00:00 3 58 9 6 3 2017-08-01 03:00:00 3 52 10 2. 4 2017-08-01 04:00:00 3 50 1 1
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50575123
tagged with: dataframe
score: 0
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
favorite count: 0
tagged with: datetime
has title: Grouping by preserving hours in pandas
tagged with: python
has answer: http://stackoverflow.com/a/50575123

http://stackoverflow.com/comment/88165571
has text: i guess you need [monkey-patching](https://stackoverflow.com/questions/5626193/what-is-monkey-patching)
comment on: http://stackoverflow.com/q/50578078
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/88351785
has text: Spent hours looking at this...thanks!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50670930

http://stackoverflow.com/comment/88381965
comment on: http://stackoverflow.com/a/50686042
has text: @chrisz also with fillna(0) : -)
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/q/50544761
tagged with: python
tagged with: selenium-webdriver
has answer: http://stackoverflow.com/a/50544856
score: 2
tagged with: selenium-chromedriver
tagged with: selenium
has body: What I want to do is follow one Instagram account in Chrome, incognito mode. The problem is that after I log in successfully, the driver gets the account's link(when the follow function is called) and I am no longer logged in. I did the same operations without the automated driver and there is no problem. Here are my 2 functions: def login(driver): # Auto log in to instagram driver.get('https://www.instagram.com/accounts/login/') # Wait until the screen has loaded try: element = WebDriverWait(driver, 15).until( EC.presence_of_all_elements_located((By.CLASS_NAME, "_ph6vk")) ) except Exception: print("Accounts page timed out") input_elem = driver.find_elements_by_class_name("_ph6vk") input_elem[0].send_keys("username") input_elem[1].send_keys("password") login_button = driver.find_element_by_class_name("_qv64e") login_button.click() def follow(driver, account_to_follow_link): driver.get(account_to_follow_link) #driver.close() And here is my driver instantiation and its options: chrome_options = Options() chrome_options.add_argument("--incognito") #chrome_options.add_argument("--headless") #chrome_options.add_argument("--window-size=1920x1080") # Path of current driver &amp; instantiation of driver object os.chdir(r'C:\ig_automation') driver = os.getcwd() +"\\chromedriver.exe" driver = webdriver.Chrome(chrome_options=chrome_options, executable_path=driver)
has answer: http://stackoverflow.com/a/50549733
type: Question
has answer: http://stackoverflow.com/a/63821606
downvote count: 0
answer count: 3
has title: Selenium navigate without getting logged out
favorite count: 0
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/50685409
type: Question
has answer: http://stackoverflow.com/a/50685810
tagged with: numpy
score: 31
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/88380722
has comment: http://stackoverflow.com/comment/88380562
has comment: http://stackoverflow.com/comment/88380732
possible better answer: http://stackoverflow.com/a/50685708
favorite count: 0
has answer: http://stackoverflow.com/a/50685708
has answer: http://stackoverflow.com/a/50685454
tagged with: python
answer count: 4
type: AnsweredQuestion
upvote count: 31
has body: I have an array of arbitrary length, and I want to select N elements of it, evenly spaced out (approximately, as N may be even, array length may be prime, etc) that includes the very first arr[0] element and the very last arr[len-1] element. Example: &gt;&gt;&gt; arr = np.arange(17) &gt;&gt;&gt; arr array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) Then I want to make a function like the following to grab numElems evenly spaced out within the array, which must include the first and last element: GetSpacedElements(numElems = 4) &gt;&gt;&gt; returns 0, 5, 11, 16 Does this make sense? I've tried arr[0:len:numElems] (i.e. using the array start:stop:skip notation) and some slight variations, but I'm not getting what I'm looking for here: &gt;&gt;&gt; arr[0:len:numElems] array([ 0, 4, 8, 12, 16]) or &gt;&gt;&gt; arr[0:len:numElems+1] array([ 0, 5, 10, 15]) I don't care exactly what the middle elements are, as long as they're spaced evenly apart, off by an index of 1 let's say. But getting the right number of elements, including the index zero and last index, are critical.
has answer: http://stackoverflow.com/a/73926974
has title: Select N evenly spaced out elements in array, including first and last
accepted answer: http://stackoverflow.com/a/50685454

http://stackoverflow.com/comment/88472760
score: 0
comment on: http://stackoverflow.com/a/50662062
has text: I don't think it is about that. When I run my original functions and your updated functions for a random dataframe of 100 elements, the length of resulting lists are: 25, 42 vs. 27, 50 for single and multi cases. As mentioned, your functions include events such as [3,4] and [3,4,5] in the list at the same time, instead of only including [3,4,5].
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88158226
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50574034
has text: @coldspeed, Reopening since OP has now provided some relevant code.
type: Comment

http://stackoverflow.com/comment/88401046
comment on: http://stackoverflow.com/a/50694079
type: AnswerComment
score: 0
type: Comment
has text: thanks for your answer, I tried. I get `(1054, "Unknown column 'api_switchesport.name' in 'field list'")` error. But your answer let me know the issue is caused by the sort. if I do not use the `'length'` for sort I will not get the error.

http://stackoverflow.com/q/50653270
upvote count: 1
duplicate of: http://stackoverflow.com/q/19885821
type: Question
downvote count: 0
has title: How to fix error "ImportError: No module named 'selenium'" on Windows?
has comment: http://stackoverflow.com/comment/88324290
has comment: http://stackoverflow.com/comment/88317086
favorite count: 0
tagged with: pycharm
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88324086
tagged with: python
tagged with: selenium-webdriver
linked to: http://stackoverflow.com/q/19885821
has body: I am using Pycharm with anaconda to work in Python. I need to use selenium webdriver. Line in code from selenium import webdriver triggers error ImportError: No module named 'selenium'. I tried command conda install -c conda-forge selenium, but error still appears.
tagged with: anaconda
answer count: 0
score: 1

http://stackoverflow.com/comment/88362989
score: 0
has text: That doesn't even compile...
type: QuestionComment
comment on: http://stackoverflow.com/q/50675943
type: Comment

http://stackoverflow.com/comment/88141590
score: 0
type: AnswerComment
has text: Thank you so much for quick reply. May I ask how can I get all the value display as standard output? Any mistake of my code?
type: Comment
comment on: http://stackoverflow.com/a/50565488

http://stackoverflow.com/comment/88225716
type: Comment
has text: There's [Windows.Management.Deployment.PackageManager](https://learn.microsoft.com/en-us/uwp/api/Windows.Management.Deployment.PackageManager), and it looks like you can use [WinAppDeployCmd locally](https://stackoverflow.com/q/45894261/243245) if you change a setting too, but it doesn't look like either can download from the store.
comment on: http://stackoverflow.com/q/50607851
score: 0
type: QuestionComment

http://stackoverflow.com/a/50644275
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88322735
type: AcceptedAnswer
downvote count: 0
has body: BcK's previous answer is fine, except it doesn't generate lists with random size (both have size = 30). The code should be a = [random.randint(0, 100) for i in range(random.randint(0, 30))] b = [random.randint(0, 100) for i in range(random.randint(0, 30))] common = set(a) &amp; set(b) if common: print(*common) else: print("No match")
accepted answer of: http://stackoverflow.com/q/50643780
answers question: http://stackoverflow.com/q/50643780
type: Answer
has comment: http://stackoverflow.com/comment/88299828

http://stackoverflow.com/q/50667057
type: Question
has answer: http://stackoverflow.com/a/50667087
tagged with: python
has title: What is the difference between the following two python methods?
score: 0
has comment: http://stackoverflow.com/comment/88344016
answer count: 1
accepted answer: http://stackoverflow.com/a/50667087
has body: What is the difference between these 2 fragments of python codes? I want to check whether an array contains the integers 1,2,3 in sequence as its elements? def arrayCheck(nums): for i in nums: if(i &lt;= (len(nums)-3)): if (nums[i] == 1 and nums[i+1] == 2 and nums[i+2] == 3): return(True) return(False) def arrayCheck(nums): for i in range(0,len(nums)-2): if (nums[i] == 1 and nums[i+1] == 2 and nums[i+2] == 3): return(True) return(False) The first one gives wrong answer for the array: arrayCheck([1,1,2,1,1,1,1,2,3]) but the second one is correct.
duplicate of: http://stackoverflow.com/q/522563
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/47665984
has comment: http://stackoverflow.com/comment/88345980
duplicate of: http://stackoverflow.com/q/47665984

http://stackoverflow.com/comment/88336469
comment on: http://stackoverflow.com/q/50663198
type: Comment
has text: See here: https://stackoverflow.com/a/5829377/365102
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88261655
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50625720
has text: Multiple ways to cause this: `abc(1, a=1)`, `kw = {'a': 1}; abc(a=1, **kw)`, etc. Somehow what you're ultimately passing in defines a param twice and it can't resolve it.
type: Comment

http://stackoverflow.com/q/50547036
has body: Trying to input text file (text #1) and output to another text file (text#2) in the following format. Running into an error. I am new to Python and any help would be appreciated. Text #1 $1120.47 $944.42 $72.29 $588.23 $371.21 $2183.84 Text #2 $ 1120.47 $ 944.42 $ 2064.89 $ 72.29 $ 588.23 $ 660.52 $ 371.21 $ 2183.84 $ 2555.05 What I have so far: inputfilename= input('Enter sales file name: ') outputfilename=input('Enter name for total sales file: ') with open(inputfilename, 'r') as i, open(outputfilename, 'w') as o: for line in i: fst_sale, lst_sale = line.split(' ') fst_sale = float(fst_sale[1:]) lst_sale = float(lst_sale[1:]) tot_sale = fst_sale + lst_sale new_line = ''.join( ['$' + str(x).rjust(10) for x in [fst_sale, lst_sale, tot_sale]] ) o.write(new_line + '\n') I get this error when I hit run: fst_sale, lst_sale = line.split(' ') ValueError: not enough values to unpack (expected 2, got 1)
linked to: http://stackoverflow.com/q/50544511
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88104781
has answer: http://stackoverflow.com/a/50547063
has comment: http://stackoverflow.com/comment/88104824
tagged with: python
type: UnansweredQuestion
has title: Trying to Output to another file in a different format
type: Question

http://stackoverflow.com/comment/88168374
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50579001
type: AnswerComment
has text: @Maxibon - Try `df'Numx','Numy'.mask(df['Code_new'].duplicated() & ~(m1).fillna(False))`

http://stackoverflow.com/comment/88155924
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50548263
type: QuestionComment
has text: Good tip. I removed the other thread and added `get_token` back to the main thread via `create_task`. Previously, I failed to understand that `create_task` would execute immediately and thought that it still required calling `run_until_complete` (which would have prevented the event loop from returning until it completed). However, now I understand that `create_task` will execute and return immediately as long as you await the task. Then, I can run other loop-blocking tasks with `run_until_complete`. Your comments have been very helpful and I appreciate your time and patience! I learned a lot!

http://stackoverflow.com/comment/88358745
type: QuestionComment
has text: Debugger clearly shows error, read it and find it. Indentation Error: expected an indented block
comment on: http://stackoverflow.com/q/50674381
type: Comment
score: 0

http://stackoverflow.com/q/50546946
has answer: http://stackoverflow.com/a/50547061
tagged with: python
has title: BeautifulSoup how to index tag object
has body: I have this html code: &lt;tr class="even"&gt; &lt;td style="background: #8FB9B0; color: #8FB9B0;"&gt;0&amp;#160;&lt;/td&gt; &lt;td&gt;Plupp&lt;/td&gt; &lt;td class="right"&gt;RIFLEMAN&lt;/td&gt; &lt;td class="right"&gt;139&lt;/td&gt; &lt;td class="right"&gt;6&lt;/td&gt; &lt;td class="right"&gt;30&lt;/td&gt; &lt;td class="right" title="Packet loss: "&gt;64&lt;/td&gt; &lt;td class="center"&gt;No&lt;/td&gt; &lt;td class="center"&gt;No&lt;/td&gt; &lt;td class="center"&gt;Yes&lt;/td&gt; which is the second tr with class 'even'. I want to extract from here the second td aka Plupp, and the 3rd aka RIFLEMAN Please help me understand what I am doing wrong, here is my code: tr = soup.find_all('tr', class_='even')[1] a = tr[2].find('td') I get this error: File "test.py", line 45, in &lt;module&gt; a = tr[2].find('td') File "C:\Python27\lib\site-packages\bs4\element.py", line 1011, in __getitem__ return self.attrs[key] KeyError: 2
accepted answer: http://stackoverflow.com/a/50547033
type: Question
tagged with: indexing
tagged with: object
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50547033
tagged with: tags
answer count: 2
possible better answer: http://stackoverflow.com/a/50547061
tagged with: beautifulsoup
score: 0

http://stackoverflow.com/q/50669278
favorite count: 0
has title: TypeError: user_followers() takes exactly 3 arguments (2 given)
tagged with: python
has comment: http://stackoverflow.com/comment/88348300
has comment: http://stackoverflow.com/comment/88348296
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88348339
downvote count: 3
has body: I get this error: TypeError: user_followers() takes exactly 3 arguments (2 given) in my python script, running this lines of code: origin = api.username_info('edelfilm') user_id = origin['user']['pk'] followers = [] results = api.user_followers(user_id) The function is defined in another script like this: def user_followers(self, user_id, rank_token, **kwargs): """ Get user followers :param user_id: :param rank_token: Required for paging through a single feed and can be generated with :meth:`generate_uuid`. You should use the same rank_token for paging through a single user followers. :param kwargs: - **query**: Search within the user followers - **max_id**: For pagination :return: """ raise_if_invalid_rank_token(rank_token) endpoint = 'friendships/{user_id!s}/followers/'.format(**{'user_id': user_id}) query_params = { 'rank_token': rank_token, } query_params.update(kwargs) res = self._call_api(endpoint, query=query_params) if self.auto_patch: [ClientCompatPatch.list_user(u, drop_incompat_keys=self.drop_incompat_keys) for u in res.get('users', [])] return res What am I doing wrong?
score: -1
type: Question
has answer: http://stackoverflow.com/a/50671956
has comment: http://stackoverflow.com/comment/88348315
answer count: 1

http://stackoverflow.com/comment/88391070
score: 0
type: Comment
type: QuestionComment
has text: @Julien Sorry I forgot to delete the error, the code works properly right now. However, there are multiple indexes that have the value that I am searching for, so I am trying to create a binary search that is able to return the location of all items that match the search value.
comment on: http://stackoverflow.com/q/50690549

http://stackoverflow.com/a/50580114
has body: If you want to stick to plain python, you can use dictionaries: file = open("input.txt", "r") dct = {} headers = file.readline() for line in file: lst = line.split(",") if lst[1] not in dct: dct[lst[1]] = lst continue if dct[lst[1]][3] &lt; lst[3]: dct[lst[1]] = lst print headers for row in dct.values(): print ','.join(row) Update: Since this may not be clear, making the dictionary key be your ROLLNO value enforces the unique constraint: for each ROLLNO value that occurs, your dictionary dct will story the row with the largest value in the fourth column (COUNT)
score: 0
answers question: http://stackoverflow.com/q/50579925
type: Answer

http://stackoverflow.com/q/50571515
has comment: http://stackoverflow.com/comment/88154190
score: 0
has comment: http://stackoverflow.com/comment/88156210
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88154309
has title: Unable to call variable inside function in different script
has comment: http://stackoverflow.com/comment/88153911
tagged with: oop
has body: Hey I am trying to make this work as, Once the GUI loads up I want to take a file input and say I store it in "X" which is also inside a function, Now I want to access this file value in another python script I have tried inhertiance,importing function,script,objects. Here's the Driver code:- from tkinter import * import tkinter import subprocess global x x="" global e1 e1="" window = tkinter.Tk() class Driver: window.minsize(300,300) window.title("Extractor") e1 = None global showx def showx(): x=e1.get() print x # def __init__(self): # self.x = x global callback def callback(): global e1 Label(window,text="File").pack() e1 = Entry(window) e1.insert(10,"Please input") e1.pack() process = tkinter.Button(window,text="GO",command=showx) process.pack() toplabel=tkinter.Label(window,text="Enumeration tool for PCAP") enum = tkinter.Button(window,text ="Enumerate",command=callback) enum.pack(side=TOP) def quit(): window.destroy() quit=Button(window,text="Exit",command=quit) quit.pack(side=BOTTOM) window.mainloop() My Attempts: root@karma:~/Desktop/IITK/Filter/GUI?# python Python 2.7.15rc1 (default, Apr 15 2018, 21:51:34) [GCC 7.3.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import GUI as obj &gt;&gt;&gt; obj.showx() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "GUI.py", line 13, in showx x=e1.get() NameError: global name 'e1' is not defined &gt;&gt;&gt; obj.x() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'module' object has no attribute 'x' &gt;&gt;&gt; obj.showx() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "GUI.py", line 13, in showx NameError: global name 'e1' is not defined &gt;&gt;&gt; root@karma:~/Desktop/IITK/Filter/GUI?# root@karma:~/Desktop/IITK/Filter/GUI?# python Python 2.7.15rc1 (default, Apr 15 2018, 21:51:34) [GCC 7.3.0] on linux2 Type "help", "copyright", "credits" o…
has comment: http://stackoverflow.com/comment/131012650
has comment: http://stackoverflow.com/comment/88152789
type: Question
has comment: http://stackoverflow.com/comment/88154779

http://stackoverflow.com/a/51030075
answers question: http://stackoverflow.com/q/50643873
type: Answer
has body: Here is the Beginner's guide to creating Chatbots using Dialogflow. Follow the guide and you will be able to create a bot like repofinder. source code is available on github.
score: 0

http://stackoverflow.com/q/50596029
downvote count: 0
has answer: http://stackoverflow.com/a/50596116
accepted answer: http://stackoverflow.com/a/50596116
tagged with: python
tagged with: dictionary
favorite count: 0
has comment: http://stackoverflow.com/comment/88201211
upvote count: 1
has body: I want to change one value in the dict of list, but the values with the same index of lists in the dictionary all change. I played around with it in terminal, and you can see two different displays with the same assigning way. https://ibb.co/fjWCCd Sorry, I am not allowed to embed images yet. Or you can have a look down here dict = {1:[0.0,0.0],2:[0.0,0.0]} dict[1] [0.0, 0.0] dict[1][0] 0.0 dict[1][0]+=1 dict {1: [1.0, 0.0], 2: [0.0, 0.0]} dict[2][0] = 7 dict {1: [1.0, 0.0], 2: [7, 0.0]} dict[2][1] = 3 dict {1: [1.0, 0.0], 2: [7, 3]} std_log = [0.0,0.0] thedict = {} for i in range(8): thedict[i+1] = std_log thedict {1: [0.0, 0.0], 2: [0.0, 0.0], 3: [0.0, 0.0], 4: [0.0, 0.0], 5: [0.0, 0.0], 6: [0.0, 0.0], 7: [0.0, 0.0], 8: [0.0, 0.0]} thedict[2][1] = 6 thedict {1: [0.0, 6], 2: [0.0, 6], 3: [0.0, 6], 4: [0.0, 6], 5: [0.0, 6], 6: [0.0, 6], 7: [0.0, 6], 8: [0.0, 6]} newvalue = thedict[2] newvalue [0.0, 6] newvalue[1] 6 newvalue[1] +=1 newvalue [0.0, 7] thedict[2] = newvalue thedict {1: [0.0, 7], 2: [0.0, 7], 3: [0.0, 7], 4: [0.0, 7], 5: [0.0, 7], 6: [0.0, 7], 7: [0.0, 7], 8: [0.0, 7]}
type: AnsweredQuestion
has title: Assign value to an item of the list in dictionary in Python
score: 1
has comment: http://stackoverflow.com/comment/88201465
has comment: http://stackoverflow.com/comment/88201352
type: Question
has comment: http://stackoverflow.com/comment/88201267
answer count: 1

http://stackoverflow.com/a/78011864
has body: In case you want to convert a scipy.sparse.csr_matrix to a torch.sparse_coo_tensor, you can do it the following way: import torch from scipy.sparse import csr_matrix csr = csr_matrix([[1, 2, 0], [0, 0, 3], [4, 0, 5]]) # Convert to PyTorch sparse tensor pt_tensor = torch.sparse_coo_tensor(csr.nonzero(), csr.data, csr.shape) Output: tensor(indices=tensor([[0, 0, 1, 2, 2], [0, 1, 2, 0, 2]]), values=tensor([1, 2, 3, 4, 5]), size=(3, 3), nnz=5, layout=torch.sparse_coo)
downvote count: 0
answers question: http://stackoverflow.com/q/50665141
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/140199736

http://stackoverflow.com/comment/123160120
type: Comment
comment on: http://stackoverflow.com/a/56514632
type: AnswerComment
score: 0
has text: Above suggestions didnt work for me either. Neither adding the auth_plugin in the connect request, nor switching to the different connector library. what worked for me was switching to native password by setting it through alter user like you suggest. then check in your settings which ones you have set using select Host,User,plugin from mysql.user; after that it will start working.

http://stackoverflow.com/comment/88311243
type: Comment
type: QuestionComment
has text: Welcome to Stackoverflow.com! Please make your question a Minimal, Complete, and Verifiable example [MVCE](https://stackoverflow.com/help/mcve). Also check [how to ask question](https://stackoverflow.com/help/how-to-ask) to make your post answerable.
score: 0
comment on: http://stackoverflow.com/q/50649827

http://stackoverflow.com/comment/88296113
comment on: http://stackoverflow.com/q/50642012
type: Comment
type: QuestionComment
has text: @brunodesthuilliers I expected question to disappear after seeing that video, but may be replaced with different one that would be more appropriate for explanatory answer
score: 0

http://stackoverflow.com/a/50557319
accepted answer of: http://stackoverflow.com/q/50556752
upvote count: 1
type: AcceptedAnswer
has body: Change your function to return the following: return JsonResponse(bicykels, safe=False)
type: Answer
has comment: http://stackoverflow.com/comment/88137707
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50556752

http://stackoverflow.com/comment/88309392
comment on: http://stackoverflow.com/q/50648853
score: 0
type: Comment
type: QuestionComment
has text: @AlexHall so how do I convert `md` to make it have the same `vars(md)`?

http://stackoverflow.com/q/50601568
has comment: http://stackoverflow.com/comment/88212388
favorite count: 0
has comment: http://stackoverflow.com/comment/88212709
tagged with: beautifulsoup
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88512353
upvote count: 1
tagged with: python
score: 1
tagged with: webdriver
has answer: http://stackoverflow.com/a/50604479
type: Question
has comment: http://stackoverflow.com/comment/88476559
has comment: http://stackoverflow.com/comment/88212385
has title: cannot search the tags from python but can view it at chrome
downvote count: 0
linked to: http://stackoverflow.com/q/15866426
has body: cannot search the following tags inside this URL class="iw_component" id="c1417094965155" i can view it from my desktop chrome browser, but cannot read it when execute the following python script import time from selenium import webdriver from pyvirtualdisplay import Display display=Display(visible=0,size=(800,800)) display.start() driver=webdriver.Firefox() driver.get('url') time.sleep(5) title=driver.page_source print title driver.close() display.stop()
answer count: 1

http://stackoverflow.com/comment/88234730
has text: The button itself is positionned correctly. Everything else is probably incorrectly placed, but since you don't show it here, it's hard to tell what exactly goes wrong.
comment on: http://stackoverflow.com/q/50612059
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88102768
comment on: http://stackoverflow.com/q/50545927
score: 1
has text: Along with [Using global variables in a function](//stackoverflow.com/q/423379)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88629774
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50581883
has text: I used the answer from this question (it's even you who answered it haha): https://stackoverflow.com/questions/50646958/how-to-know-tensorflow-lite-models-input-output-feature-info
score: 0

http://stackoverflow.com/comment/88157781
type: Comment
comment on: http://stackoverflow.com/a/50571315
score: 1
has text: The for loop approach is the slowest: **75.2 µs ± 2.47 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)**
type: AnswerComment

http://stackoverflow.com/comment/88163187
type: QuestionComment
comment on: http://stackoverflow.com/q/50576540
score: 0
has text: Launch angle... wrt the imperial battlecruiser azimuth? Poor choices of coordinate systems and/or confusion of sin with cos and vice versa have a cost!
type: Comment

http://stackoverflow.com/q/50613528
has comment: http://stackoverflow.com/comment/88237613
type: Question
has comment: http://stackoverflow.com/comment/88237696
has comment: http://stackoverflow.com/comment/88239216
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/88237486
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/88237376
answer count: 1
has comment: http://stackoverflow.com/comment/88237025
favorite count: 0
has title: Matplotlib plot pmf from list of 2D numpy arrays
has answer: http://stackoverflow.com/a/50617634
tagged with: python
has body: I have a dataset from my simulations where I combine the results from each simulation seed into a bigger list using bl.extend(df['column'].tolist()). I'm also running several simulation scenarios, so I append each scenario to a list of lists. Finally, I'm computing the Probability Mass Function (PMF) of each list as follows (from How to plot a PMF of a sample?) for idx,sublist in enumerate(pmf_list): val, cnt = np.unique(sublist, return_counts=True) pmf = cnt / float(len(sublist)) plot_pmf.append(np.column_stack((val, pmf))) The issue is that I end up with a list of numpy arrays which I don't know how to plot. The minimum code to reproduce the problem is the following: import numpy as np list1 = np.empty([2, 2]) list2 = np.empty([2, 2]) list3 = np.empty([2, 2]) bl = [] # big list bl.append(list1) bl.append(list2) bl.append(list3) print bl I can plot using plt.hist(bl[0]) but it doesn't give me the right results. See plot attached for the following list. &lt;type 'numpy.ndarray'&gt; [[0.00000000e+00 1.91734780e-01] [1.00000000e+00 2.94277080e-02] [2.00000000e+00 3.28276369e-01] [3.00000000e+00 4.43357154e-01] [4.00000000e+00 3.54294582e-03] [5.00000000e+00 1.57306794e-03] [6.00000000e+00 2.00530733e-03] [7.00000000e+00 2.95245485e-05] [8.00000000e+00 2.24386568e-05] [9.00000000e+00 2.83435665e-05] [1.00000000e+01 1.18098194e-06] [1.20000000e+01 1.18098194e-06]] Formatting the y-values I get: 0.1944084241 0.0415880165 0.3480178394 0.4031723062 0.0050902199 0.0033411939 0.0040175705 0.0001480127 0.0001031961 0.0001008373 0.0000058969 0.0000011794 0.0000047175 0.0000005897 very different from the y-values on the histogram plot
linked to: http://stackoverflow.com/q/25273415
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88237488
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/88150183
type: Comment
type: QuestionComment
has text: `np.concatenate([array[:, None], array2[:, None]], axis=1)` assuming array and array2 are actually arrays.
comment on: http://stackoverflow.com/q/50570067
score: 0

http://stackoverflow.com/a/50591904
score: 0
answers question: http://stackoverflow.com/q/50591699
type: Answer
has body: The problem is here : listc = lista You're copying the reference, not the content : so listc is lista. When you remove element from lista, listc is going to lose this element, too. If you want to copy the content of the lista in listc, you need to use : import copy listc = copy.copy(lista) You can get more informations here : How to clone or copy a list?

http://stackoverflow.com/q/50686388
has answer: http://stackoverflow.com/a/53300148
has answer: http://stackoverflow.com/a/65130681
upvote count: 15
possible better answer: http://stackoverflow.com/a/53300148
answer count: 17
has answer: http://stackoverflow.com/a/68446599
has answer: http://stackoverflow.com/a/65578898
favorite count: 0
has answer: http://stackoverflow.com/a/67759391
has answer: http://stackoverflow.com/a/56053192
has answer: http://stackoverflow.com/a/50687729
tagged with: python
has answer: http://stackoverflow.com/a/66987170
tagged with: discord
has answer: http://stackoverflow.com/a/62177276
has answer: http://stackoverflow.com/a/64667946
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/64515264
has answer: http://stackoverflow.com/a/62136173
has answer: http://stackoverflow.com/a/63185412
has answer: http://stackoverflow.com/a/64704987
has body: I ran python3 -m pip install -U discord.py but it only installed discord.py v0.16.x. How do I install the new discord.py rewrite v1.0? I uninstalled the old discord.py using pip uninstall discord.py and re-ran pip to install discord.py, only to get version v0.16.x again instead of the new v1.0 version.
downvote count: 1
type: Question
score: 14
accepted answer: http://stackoverflow.com/a/50687729
tagged with: discord.py
has answer: http://stackoverflow.com/a/65622492
tagged with: anaconda
has title: How to install discord.py rewrite?
has answer: http://stackoverflow.com/a/63932305
has answer: http://stackoverflow.com/a/66193120

http://stackoverflow.com/comment/88120284
has text: Can you work with `argparser`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50554698
score: 1

http://stackoverflow.com/comment/88308295
score: 0
type: QuestionComment
has text: I am actually a bit curious if you could stack profilers and run a cpu time profile to see what part of `memory_profiler.profile` takes more time with the generator function (you'd see how many times it was called, and how long it took to return on average)
type: Comment
comment on: http://stackoverflow.com/q/50627267

http://stackoverflow.com/q/50686866
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88383974
type: Question
has comment: http://stackoverflow.com/comment/88384249
has answer: http://stackoverflow.com/a/50687453
has comment: http://stackoverflow.com/comment/88383674
answer count: 1
has title: Django: Can the value of a DOM Element be passed to a TemplateTag?
score: 0
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has body: Being new to the framework, I am faced with the problem of creating a view (index.html) which allows the user to select a certain value from an input element and show it.This value needs to be processed and the output of this process will be shown in the template. Currently, I am getting a .txt file from an input element and storing its content inside a p element by means of a small js script. The content of this p element (text contained inside the file selected) is what I would need to pass to the template in order to process it with an external python library that I created. I am trying to use a TemplateTag with the following structure: def foo(value): ret = doOperations(value) return ret; However, I am not sure if TemplateTags can receive the value of a dom element since the examples in django's documentation only show TemplateTags used with variables passed from the view. The ideal scenario would be somehow passing the value (a text element) directly to the template: where valueOfDomElement would be the content of my p element (text contained inside the file selected) I would like to know if my approach to this problem is viable or how I should proceed in order to communicate correctly between templatetag (if needed) and view.
accepted answer: http://stackoverflow.com/a/50687453
tagged with: django-templates
has comment: http://stackoverflow.com/comment/88383857
has comment: http://stackoverflow.com/comment/88383638
tagged with: django

azure-cosmosdb-sqlapi
tags question: http://stackoverflow.com/q/50607467
type: Tag
tag name: azure-cosmosdb-sqlapi

http://stackoverflow.com/comment/88216475
has text: @YakymPirozhenko thanks for finding mistakes, please take a look and let me know how I can improve it.
type: Comment
comment on: http://stackoverflow.com/a/50603255
score: 1
type: AnswerComment

http://stackoverflow.com/comment/88113748
has text: @Vinny .. i have edited the actual code tried, but while doing it it does not write the actual `OutStr ` data into file
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50550235

http://stackoverflow.com/q/50551410
has answer: http://stackoverflow.com/a/50551587
upvote count: 1
type: Question
tagged with: opencv
score: 1
has answer: http://stackoverflow.com/a/50555548
answer count: 2
has body: Am trying to put a timelapse on my OpenCV code but it seems i am doing something that is not right and i don't know why i have the error. The erorr i got is for this line: filename = f"{timelapse_img_dir}/{i}.jpg" What should i do in order not to have an error? This is the error i have from my IDE: File "/Users/Dropbox/OpenCV/src/timelapse.py", line 34 filename = f"{timelapse}/{i}.jpg" ^ SyntaxError: invalid syntax [Finished in 0.1s with exit code 1] [shell_cmd: python -u "/Users/Dropbox/OpenCV/src/timelapse.py"] [dir: /Users/Dropbox/OpenCV/src] [path: /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin] My code: import os import numpy as np import cv2 import time import datetime from utils import CFEVideoConf, image_resize import glob cap = cv2.VideoCapture(0) frames_per_seconds = 20 save_path='saved-media/timelapse.mp4' config = CFEVideoConf(cap, filepath=save_path, res='720p') out = cv2.VideoWriter(save_path, config.video_type, frames_per_seconds, config.dims) timelapse_img_dir = '/Users/Dropbox/OpenCV/src/images/timelapse/' seconds_duration = 20 seconds_between_shots = .25 if not os.path.exists(timelapse_img_dir): os.mkdir(timelapse_img_dir) now = datetime.datetime.now() finish_time = now + datetime.timedelta(seconds=seconds_duration) i = 0 while datetime.datetime.now() &lt; finish_time: ''' Ensure that the current time is still less than the preset finish time ''' ret, frame = cap.read() # filename = f"{timelapse_img_dir}/{i}.jpg" filename = f"{timelapse_img_dir}/{i}.jpg" i += 1 cv2.imwrite(filename, frame) time.sleep(seconds_between_shots) if cv2.waitKey(20) &amp; 0xFF == ord('q'): break def images_to_video(out, image_dir, clear_images=True): image_list = glob.glob(f"{image_dir}/*.jpg") sorted_images = sorted(image_list, key=os.path.getmtime) for file in sorted_images: image_frame = cv2.imread(file) out.write(image_frame) if clear_images: ''' Remove stored timelapse images ''' for file in image_list: os.remove(file) images_to_video(out, timelapse_img_dir…
downvote count: 0
favorite count: 0
tagged with: python
has title: Python-OpenCV --F Function error--not finding right dir
type: UnansweredQuestion

http://stackoverflow.com/comment/88372843
has text: `d` does not have the same number of dates as `c` (that is to say, `len(d) != len(c)` - if you want them to move together then what do you want to happen when one of the lists has run out of unprocessed dates but the other still has unprocessed dates?
score: 0
comment on: http://stackoverflow.com/q/50681101
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50653550
answers question: http://stackoverflow.com/q/50653432
score: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88335737
type: Answer
has body: You may need sort_values before groupby head df.sort_values(['area','other']).groupby('area').head(2)
accepted answer of: http://stackoverflow.com/q/50653432
upvote count: 3

http://stackoverflow.com/comment/88308846
type: AnswerComment
has text: Since you're setting `default_factory` to `None` when you're done with it, maybe just use `setdefault` and a regular dict? `positions = {}; ... positions.setdefault(name, []).append(position)`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50648810

http://stackoverflow.com/q/50562192
favorite count: 0
tagged with: python
upvote count: 6
tagged with: fasttext
has comment: http://stackoverflow.com/comment/139161072
tagged with: pycharm
type: UnansweredQuestion
has body: I am trying to use fastText with PyCharm. Whenever I run below code: import fastText model=fastText.train_unsupervised("data_parsed.txt") model.save_model("model") The process exits with this error: Process finished with exit code -1073740791 (0xC0000409) What causes this error and what can be done to avoid it?
has answer: http://stackoverflow.com/a/50576241
type: Question
score: 6
has title: Process finished with exit code -1073740791 (0xC0000409) pycharm error
linked to: http://stackoverflow.com/q/71789994
answer count: 1
downvote count: 0

http://stackoverflow.com/q/50545979
answer count: 0
has title: GLException: No GL context; create a Window first
type: Question
score: 5
tagged with: pyglet
upvote count: 5
downvote count: 0
tagged with: trimesh
has body: I am trying to read and display a .ply file with Trimesh in Python. I have installed Trimesh using pip install trimesh as well as pyglet to display the file. import trimesh mesh = trimesh.load("file.ply") mesh.show() However, I keep getting the following error when running this code: GLException: No GL context; create a Window first Could someone please help me resolve this?
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/88420960
type: QuestionComment
has text: Man, that's embarrassing! Thanks for all of the feedback! I like your last idea the best, abarnet, I think I might go with that
comment on: http://stackoverflow.com/q/50690606
score: 0
type: Comment

http://stackoverflow.com/a/50689506
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50630943
has body: Nevermind, this pulled the trick: if len(bestanden) &gt; 1: vh = dialog.select('Selecteer bestand om te downloaden', bestanden) if vh == -1: return else: vh = 0

http://stackoverflow.com/comment/88104528
type: Comment
comment on: http://stackoverflow.com/a/50546749
type: AnswerComment
has text: No, because I was using the lambda layer as a workaround. Sorry, I was referring to this thread: http://forums.fast.ai/t/keras-lesson1-jpegimagefile-object-is-not-subscriptable/13904
score: 0

http://stackoverflow.com/comment/88167548
comment on: http://stackoverflow.com/q/50578948
has text: @coldspeed I have tried that option, and I get `AttributeError: ("'unicode' object has no attribute 'apply'", u'occurred at index 0')`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50645371
has comment: http://stackoverflow.com/comment/88362488
has body: Note that your current solution: def my_fancy_update(self, **kwargs): self.name = kwargs.get('name') self.house = kwargs.get('house') self.salary = kwargs.get('salary') self.save() is very brittle as it can possibly set any of name, house and salary to None. A first clean solution would be to use a for loop and settattr: def my_fancy_update(self, **kwargs): for name, value in kwargs.items(): setattr(self, name, value) self.save() but this is still brittle in that it doesn't check that the names passed are actually model field names. A safer implementation would use self._meta.get_fields() to check this: def my_fancy_update(self, **kwargs): fieldnames = set(f.name for f in self._meta.get_fields()) for name, value in kwargs.items(): if name not in fieldnames: raise ValueError("%s is not a field of %s" % (name, type(self).__name__)) setattr(self, name, value) self.save() and finally, you may want to avoid calling save() if nothing was updated, and only commit what was actually updated: def my_fancy_update(self, **kwargs): if not kwargs: return fieldnames = set(f.name for f in self._meta.get_fields()) updated = [] for name, value in kwargs.items(): if name not in fieldnames: raise ValueError("%s is not a field of %s" % (name, type(self).__name__)) setattr(self, name, value) updated.append(name) self.save(update_fields=updated)
type: Answer
has comment: http://stackoverflow.com/comment/88360429
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50645301
has comment: http://stackoverflow.com/comment/88367710
has comment: http://stackoverflow.com/comment/88360476
downvote count: 0

http://stackoverflow.com/comment/88168947
comment on: http://stackoverflow.com/q/50579874
score: 0
type: Comment
type: QuestionComment
has text: It's not that clear to me what you're starting off with - any chance you could write a minimal working example?

http://stackoverflow.com/comment/88111261
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50549831
score: 0
has text: [edit] your question to include that! :)

http://stackoverflow.com/q/50562433
tagged with: pyqt5
type: Question
has comment: http://stackoverflow.com/comment/88136320
has title: PyQt progress bar with QProgressDialog unable to reset
has comment: http://stackoverflow.com/comment/88136841
has comment: http://stackoverflow.com/comment/88135520
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50563336
has comment: http://stackoverflow.com/comment/88136222
type: UnansweredQuestion
tagged with: python
tagged with: qt
has body: I have a simple progress bar that I want to pop up inside loops, like in the example below. I have to instantiate it outside of the app, then adjust values for the loop. Why? I would've thought it'd be more ideal to instantiate a new progress bar class inside the MainWindow, but that doesn't show up. I assume it has to do with the app.exec. However, if I add a self.exec for the progress bar, it doesn't update, so what's the correct way of implementing it? from PyQt5.Qt import * import sys class Ui_MainWindow(object): def setupUi(self, MainWindow): self.centralwidget = QWidget(MainWindow) self.pushButton = QPushButton(self.centralwidget) self.pushButton.setText("CLICK ME") MainWindow.setCentralWidget(self.centralwidget) self.pushButton.clicked.connect(self.testloop) def testloop(self): n = 200 print(progressbar.wasCanceled()) progressbar.setMinimum(0) progressbar.setValue(0) progressbar.setMaximum(n) progressbar.show() for i in range(n): progressbar.setValue(i) if progressbar.wasCanceled(): # How can I un-cancel and reset the progress bar again? break class ProgressBar(QProgressDialog): def __init__(self): super().__init__() self.setValue(0) self.setModal(True) def step(self, i): self.setValue(i) if __name__ == "__main__": app = QApplication(sys.argv) mainwindow = QMainWindow() ui = Ui_MainWindow() ui.setupUi(mainwindow) mainwindow.show() progressbar = ProgressBar() # Do I need to instantiate a progressbar here, # or can I instantiate and kill it inside the app code? sys.exit(app.exec_())

mini-batch
tags question: http://stackoverflow.com/q/50663803
tag name: mini-batch
type: Tag

http://stackoverflow.com/comment/88301871
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50645548
has text: I suggest to create virtual env using python3 `virtualenv -p python3 venv` , activate it `source venv/bin/activate` and then install all requirements inside it `pip install -r requirments.txt`
score: 0

http://stackoverflow.com/q/50633442
answer count: 3
downvote count: 0
has title: Scraping a custom ebay search with BeautifulSoup. How to handle pagination?
has answer: http://stackoverflow.com/a/50633977
favorite count: 0
tagged with: beautifulsoup
type: UnansweredQuestion
tagged with: python
tagged with: ebay-api
has answer: http://stackoverflow.com/a/74389484
score: 1
tagged with: web-scraping
upvote count: 1
has body: I am trying to scrape a custom eBay search that shows 200 items on a single page. I need to get the title of the item, the price and the link to the said item. So far so good. But I also would like the code to follow the link to the next page with 200 or less items and extract them as well. This is the code, I am using: from urllib.request import urlopen as Req from bs4 import BeautifulSoup as souce start_url='https://www.ebay.de/sch/i.html?_fosrp=1&amp;_from=R40&amp;_nkw=iphone&amp;_in_kw=1&amp;_ex_kw=&amp;_sacat=0&amp;_mPrRngCbx=1&amp;_udlo=600&amp;_udhi=4.800&amp;LH_BIN=1&amp;LH_ItemCondition=4&amp;_ftrt=901&amp;_ftrv=1&amp;_sabdlo=&amp;_sabdhi=&amp;_samilow=&amp;_samihi=&amp;_sadis=10&amp;_fpos=&amp;LH_SubLocation=1&amp;_sargn=-1%26saslc%3D0&amp;_fsradio2=%26LH_LocatedIn%3D1&amp;_salic=77&amp;_saact=77&amp;LH_SALE_CURRENCY=0&amp;_sop=2&amp;_dmd=1&amp;_ipg=200' Client=Req(start_url) page_html=Client.read() Client.close() page_soup=souce(page_html, "html.parser") containers_listings = page_soup.findAll("li",{"class":"sresult lvresult clearfix li"}) container_next=page_soup.find("td",{"class":"pagn-next"}) next_url=container_next.a["href"] filename="scrape_ebay.csv" f=open(filename,"w") headers="item_title,item_link,item_price\n" f.write(headers) for container in containers_listings: item_title=container.h3.text.strip() item_link=container.h3.a["href"].strip() item_price=container.span.text.strip() f.write(item_title + "," + item_link + "," + item_price.replace(",",".") + "\n") f.close() I am running into a problem with the eBay pagination. I have managed to isolate and extract the next link but I have no idea how to implement it into a loop that would visit the next pages and extract the information. Any help would be greatly appreciated! Thanks in advance.
type: Question
has answer: http://stackoverflow.com/a/50633767

http://stackoverflow.com/comment/88377612
type: QuestionComment
comment on: http://stackoverflow.com/q/50683945
score: 0
type: Comment
has text: Where does `namy_names` come from?

http://stackoverflow.com/comment/88431301
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50580580
has text: @Lior, you should have provided this information in the question itself. In other words, tell us what you did and what was wrong with it. Matrix multiplication is a relative strong point for `csr`. In fact row and column sums are done with it, as is some indexing.
score: 0

http://stackoverflow.com/comment/88397433
has text: From the readme: _Unfortunately pytest-repeat is not able to work with unittest.TestCase test classes. These tests will simply always run once, regardless of --count, and show a warning._
comment on: http://stackoverflow.com/q/50691692
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/50597925
has body: I have three matrices A B and C. I want to find which matrice (B &amp; C) have the best cross-correlation coefficient with the matrices A. A=np.array([[1, 2, 4],[3, 4, 5],[1, 4, 5]]) B=np.array([[1, 1, 1], [1, 2, 4],[1, 4, 5]]) C=np.array([[1, 2, 4], [1, 1, 1],[1, 4, 5]]) scipy.correlate2d and numpy.corrcoef are giving matrice as output. I just need single correlation coefficient value so that I can find the more similar matrices to A. Thank you for your answers in advance.
tagged with: python-2.7
score: 0
answer count: 2
has title: How to calculate a single cross correlation coefficient of matrices A with other matrices B python?
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50609955
tagged with: python
accepted answer: http://stackoverflow.com/a/50609955
type: AnsweredQuestion
upvote count: 1
downvote count: 1
tagged with: scipy
type: Question
possible better answer: http://stackoverflow.com/a/50598254
tagged with: numpy
has answer: http://stackoverflow.com/a/50598254

trimesh
tag name: trimesh
tags question: http://stackoverflow.com/q/50545979
type: Tag

http://stackoverflow.com/comment/88132964
type: QuestionComment
comment on: http://stackoverflow.com/q/50560993
has text: `df = pd.read_excel( "C:\\Users\\Desktop\\test.xlsx", sheet_name = 'Feuil1', index_col = [0], header = [0] ) `?
score: 0
type: Comment

http://stackoverflow.com/comment/88148696
score: 0
type: Comment
type: QuestionComment
has text: @wwii its not just that i must get the average of the grades.
comment on: http://stackoverflow.com/q/50567281

http://stackoverflow.com/q/50664483
has title: filter rows based on multiple strings with Pandas
has comment: http://stackoverflow.com/comment/88339484
score: 0
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/88339338
linked to: http://stackoverflow.com/q/47937697
answer count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/47937697
type: Question
has comment: http://stackoverflow.com/comment/88339046
has comment: http://stackoverflow.com/comment/88339030
has body: If I have a Pandas DataFrame like this : id fruits 01 Apple, Apricot 02 Apple, Banana, Clementine, Pear 03 Orange, Pineapple, Pear 04 How can i filter rows which contains Apricot, Orange and Pineapple and get following dataframe? Thanks. id fruits 01 Apple, Apricot 03 Orange, Pineapple, Pear
has comment: http://stackoverflow.com/comment/88339194
tagged with: numpy
has comment: http://stackoverflow.com/comment/88339048

http://stackoverflow.com/q/50610967
has comment: http://stackoverflow.com/comment/88231844
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88232018
score: 0
has answer: http://stackoverflow.com/a/50611825
tagged with: http://stackoverflow.com/tag/csv
has title: How to read CSV with column with more than one element in Python
type: UnansweredQuestion
tagged with: python
has body: I have the following CSV file: id;name;duration;predecessors; 10;A;7;; 20;B;10;10; 25;B2;3;10; 30;C;5;10; 40;D;5;20,30, 25; That is, the last row, in the fourth column I have three elements (20,30,25) separated by comma. I have the following code: csv_file = open(path_to_csv, 'r') csv_file_reader = csv.reader(csv_file, delimiter=',') first_row = True for row in csv_file_reader : if not first_row: print(row) else : first_row = False but I get a weird output: ['10;A;7;;'] ['20;B;10;10;'] ['25;B2;3;10;'] ['30;C;5;10;'] ['40;D;5;20', '30', ' 25;'] Any ideas? Thanks in advance
has answer: http://stackoverflow.com/a/50610983

http://stackoverflow.com/a/50653262
has comment: http://stackoverflow.com/comment/88317121
accepted answer of: http://stackoverflow.com/q/50653173
answers question: http://stackoverflow.com/q/50653173
score: 2
has body: You should read this section of the documentation. Basically, in both versions the scope of the nested block allows it to interact with the namespace of the encompassing block. The difference is that you are not reassigning state in the first example, you're mutating it. In the second example, Python knows that you are going to assign a value to that reference later in the function, so it is treated as a name from the local nested namespace, rather than the outer tester namespace. You can use the nonlocal keyword to circumvent this and use the other reference from the other namespace def tester(start): def nested(label): nonlocal state print(label,state) state += 1 print("after:",state) state = start return nested
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88317072
type: Answer
upvote count: 2

http://stackoverflow.com/q/50622856
has comment: http://stackoverflow.com/comment/88255857
has comment: http://stackoverflow.com/comment/88256664
has comment: http://stackoverflow.com/comment/88261015
linked to: http://stackoverflow.com/q/8049520
has comment: http://stackoverflow.com/comment/88255661
score: 0
has body: I'm trying to get the text from the following html code: &lt;span id="numrefs"&gt;(0)&lt;/span&gt; My code is as follows: container = soup.findAll("span", {"id":"numrefs"}) print(cotainer) print(cotainer[0].text) I think I should be able to get the text, which is (0), using the second print. But the result of my code is as follows: [&lt;span id="numrefs"&gt;&lt;/span&gt;] I could not get any text in the span tag. The second print function returned nothing here. What is happening here?
has title: text missing in span tag when doing web scraping using beautiful soup4
tagged with: beautifulsoup
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88262721
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88255792
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/88257853
answer count: 0
tagged with: web-scraping
type: Question

http://stackoverflow.com/q/50675341
answer count: 0
has title: AttributeError in Tkinter while working with control variables in radiobuttons
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88369909
downvote count: 0
tagged with: variables
favorite count: 0
has comment: http://stackoverflow.com/comment/88428982
type: UnansweredQuestion
tagged with: python
has body: I'm trying to get the value of the radiobutton selcted and storing this int into a varable. It's my first tkinter project, so I'm sorry for my probably stupid mistakes... from tkinter import * from tkinter import ttk select = "A" def begin(): grand = Tk() grand.title("Converter") window.destroy() frame = Frame(grand) option = IntVar() -> AttributeError: 'NoneType' object has no attribute '_root' grandlabel = Label(frame, text="Choose the grand").grid(row=0, sticky=N, padx=5) grand1 = Radiobutton(frame, text="Speed", variable=option, value=1, command=sel).grid(row=1, sticky=W) grand2 = Radiobutton(frame, text="etc", variable=option, value=2, command=sel).grid(row=2, sticky=W) submitgrand = Button(frame, text="Ok", command=unit).grid(row=3, sticky=W) frame.pack() grand.mainloop() def sel(): global option global select select = option.get() option = StringVar() def unit(): unit = Tk() global select select = grandchosen if (grandchosen == "Speed"): Label(unit, text="Test").pack() else: Label(unit, text="Test2").pack() unit.mainloop() root = Tk() frame = Frame(root) welcome = ttk.Label(frame, text="Welcome!").grid(row=0, sticky=N, padx=10, pady=3) okbutton = Button(frame, text="Ok", width=15, command=begin).grid(row=1, sticky=S, padx=20, pady=30) frame.pack() style = ttk.Style() style.configure("TLabel", foreground="midnight blue", font="Times 19") root.mainloop() Would be great to get some help, thank you!
tagged with: tkinter

timer
tag name: timer
tags question: http://stackoverflow.com/q/50616958
type: Tag
tags question: http://stackoverflow.com/q/50613187
tags question: http://stackoverflow.com/q/50663034

http://stackoverflow.com/q/50609329
has comment: http://stackoverflow.com/comment/88228877
has comment: http://stackoverflow.com/comment/88228450
favorite count: 0
has answer: http://stackoverflow.com/a/50609797
has answer: http://stackoverflow.com/a/50611456
has comment: http://stackoverflow.com/comment/88228554
type: UnansweredQuestion
tagged with: python
score: 3
has comment: http://stackoverflow.com/comment/88229193
has answer: http://stackoverflow.com/a/50611724
has title: Numpy safe programming
has comment: http://stackoverflow.com/comment/88228552
downvote count: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88228611
has comment: http://stackoverflow.com/comment/88228914
has body: Are there any sources or guidelines for safe, bug-free numerical programming with numpy? I'm asking because I've painfully learned that numpy does many things that seem to really ask for bugs to happen, such as... Adding matrices of different sizes ("broadcasting") without complaining: In: np.array([1]) + np.identity(2) Out: array([[ 2., 1.], [ 1., 2.]]) Returning different data types depending on the input: In: scalar1 = 1 In: scalar2 = 1. In: np.array(scalar1).dtype Out: dtype('int32') In: np.array(scalar2).dtype Out: dtype('float64') Or simply not performing a desired operation (again, depending on the data type) without raising any warnings: In: np.squeeze(np.array([[1, 1]])).ndim Out: 1 In: np.squeeze(np.matrix([[1, 1]])).ndim Out: 2 These are all very hard to discover bugs, since they do not raise any exceptions or warnings and often return results of the valid data types / shapes. Therefore my question: Are there any general guidelines for improving the safety and preventing bugs in mathematical programming with numpy? [Note that I don't believe that this answer will attract "opinionated answers and discussions" since it is not about personal recommendations, but rather asking whether there are any existing guidelines or sources on the subject at all - of which I could not find any.]
has comment: http://stackoverflow.com/comment/88229673
upvote count: 4
answer count: 3
has comment: http://stackoverflow.com/comment/88228695
has comment: http://stackoverflow.com/comment/88229015

http://stackoverflow.com/a/50542692
type: Answer
has body: Try: pip3 install regex --user
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50542645
upvote count: 1

http://stackoverflow.com/a/50589378
upvote count: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/50589034
has body: Something like this isn't too difficult to create yourself, and it'd give you the flexibility you need. There are fancy ways like tracking the start and completion time of each and checking if you've sent 10 in the second. The system probably also limits it to 10 active requests going (i.e., you can't spin up 100 requests, 10 each second, and let them all process). If you assume this, I'd say launch 10 all at once, then let them complete, then launch the next batch. You could also launch 10, then start 1 additional each time one finishes. You could think of this like a "thread pool". You can easily track this with a simple variable tracking how many calls are going. Then, just check how many calls are going once a second (to avoid the 1 second limit) and if you have available "threads", fire off that many more new requests. It could look something like this: const threadLimit = 10; const rateLimit = 1000; // ms let activeThreads = 0; const calls = new Array(100).fill(1).map((_, index) =&gt; index); // create an array 0 through 99 just for an example function run() { if (calls.length == 0) { console.log('complete'); return; } // threadLimit - activeThreads is how many new threads we can start for (let i = 0; i &lt; threadLimit - activeThreads &amp;&amp; calls.length &gt; 0; i++) { activeThreads++; // add a thread call(calls.shift()) .then(done); } setInterval(run, rateLimit); } function done(val) { console.log(`Done ${val}`); activeThreads--; // remove a thread } function call(val) { console.log(`Starting ${val}`); return new Promise(resolve =&gt; waitToFinish(resolve, val)); } // random function to simulate a network call function waitToFinish(resolve, val) { const done = Math.random() &lt; .1; // 10% chance to finish done &amp;&amp; resolve(val) if (!done) setInterval(() =&gt; waitToFinish(resolve, val), 10); return done; } run(); Basically, run() just starts up however many new threads it can, based on the limit and how many are done. Then, it just repeats the pro…
score: 1

http://stackoverflow.com/comment/88324216
type: Comment
type: QuestionComment
has text: If the API limit was the issue you could loop through your origin destination pairs with each API request having only one origin and one destination. This would be slower than the batch method though.
score: 1
comment on: http://stackoverflow.com/q/50656955

http://stackoverflow.com/q/50626360
has comment: http://stackoverflow.com/comment/88262908
answer count: 2
has comment: http://stackoverflow.com/comment/88263071
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50626506
has comment: http://stackoverflow.com/comment/88263163
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88263010
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50627443
tagged with: python
has comment: http://stackoverflow.com/comment/88262863
has body: I do have a nice piece of software code here (written in Python) which translates a given English number – e.g., two thousand three hundred forty five – into the Arabic number – 2345 – and then in its German equal – zweitausenddreihundertfünfundvierzig. One speciality of the German language is that it “twists” the tens and the singles, i.e., word-by-word translated, the number 2345 reads in German: two-thousand three-hundred five and forty. The code does that perfectly for any number I entered. Back and forth, from English to German, from German to English. Yet: How to test systematically that it works correctly for any number? If the code processes a finite set of values, this would be easy, as I could simply could test all values against a table of the correct (= expected) answers/results. How to test – at least, partly, – the code? Any idea will be appreciated :-)
has title: How to verify a number translator?
upvote count: 2

http://stackoverflow.com/comment/88315960
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50652620
has text: This code does not limit the maximum number of repeated items among all possible lists. (Maximum 9)

http://stackoverflow.com/a/64803742
type: Answer
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/50655738
score: 0
has body: Just run these command if you are using linux, sudo apt update sudo apt install tesseract-ocr sudo apt install libtesseract-dev then run this, python -m pip install tesseract tesseract-ocr pytesseract

http://stackoverflow.com/comment/88234360
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50612208
has text: It's not super clear what you mean here: "*I want to be able to print the list out all as strings, However keeping the Integers at the end of the entrys as Integers in the list*". Hopefully your mechanism for printing doesn't involve modifying the original list?
type: Comment

http://stackoverflow.com/a/50649383
score: 1
has comment: http://stackoverflow.com/comment/88311245
answers question: http://stackoverflow.com/q/50649147
has comment: http://stackoverflow.com/comment/88355437
has body: self.l is only created when self.submit is called (which itself is only called by the callback of your button), so if retranslateUi is called before submit is, self.l won't exist yet. You should include anything that is expected to exist from the creation of the object in it's __init__ method even if the value is just a placeholder such as [].
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/a/50644769
answers question: http://stackoverflow.com/q/50644215
has body: Okay, you're on the right track. The div should be reloading correctly, if not try wrapping it in adding body and head tags, that helped me one time. It is now up to you to return any data you want to the webpage. Say you want to display time: In python import the datetime module using : import datetime and make it the index function with: def index(): return render_template('index.html', title='Estat', time = str(datetime.datetime.now())) then modify your div to be: &lt;div id="display"&gt;&lt;h1&gt;{{ time}}&lt;/h1&gt;&lt;/div&gt; now your webpage should be returning the time, and refreshing every second
accepted answer of: http://stackoverflow.com/q/50644215
has comment: http://stackoverflow.com/comment/88303583
has comment: http://stackoverflow.com/comment/88310868
type: Answer
has comment: http://stackoverflow.com/comment/88307902
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/88300057

http://stackoverflow.com/comment/88379775
score: 0
comment on: http://stackoverflow.com/a/50684970
has text: Sure, you can easily reverse the logic; e.g. reverse the filter by removing the `not`; and rename as `good_items`. Really depends on how you want to use this filter.
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50682184
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50682352
possible better answer: http://stackoverflow.com/a/50682576
favorite count: 0
tagged with: python
has body: I want to compare a dataframe with two other data frames and add new column if the entry is present. EG. Base_df- | Key | A | B | | key1 | a1 | b1 | | key1 | a1 | b1 | | key1 | a1 | b2 | | key2 | a2 | b2 | df_2- | Key | A | B | | key1 | a1 | b1 | | key1 | a1 | b1 | | key1 | a1 | b1 | | key1 | a1 | b1 | | key1 | a1 | b1 | df_3- | Key | A | B | | key1 | a1 | b1 | | key1 | a1 | b2 | | key2 | a2 | b2 | Output should be- OutputBase_df- | Key | A | B | df2 | df3 | | key1 | a1 | b1 | 1 | 1 | | key1 | a1 | b1 | 1 | 0 | | key1 | a1 | b2 | 0 | 1 | | key2 | a2 | b2 | 0 | 1 |
type: AnsweredQuestion
downvote count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/50682352
type: Question
score: -1
has answer: http://stackoverflow.com/a/50682576
has title: Compare three dataframes in Python pandas with duplicate entries

http://stackoverflow.com/comment/88386456
type: QuestionComment
comment on: http://stackoverflow.com/q/50688288
type: Comment
has text: The real question is why you want to do this. To run a terminal command, you don't need to run it in `gnome-terminal`. You only do that if you specifically want to display the output in `gnome-terminal`, and I'm not sure why you'd want to do that (why not just, e.g., pipe it to… whatever replaced `gtkless` back in the 2.0 era?).
score: 0

http://stackoverflow.com/q/50671528
has comment: http://stackoverflow.com/comment/88352911
has body: I have the below Python program to draw a square design using colors listed below. The program is applying only the pink for all boxes, how do I make the syntax to repeat the colors in sequence listed below? import turtle def main(): t = turtle.Turtle() t.hideturtle() t.speed(500) color = ["pink", "navy blue","red","forest green","cyan","magenta"] squaredesign(t,color) def squaredesign(t,color): x = 100 y = 100 z = 1 c = 0 for i in range(10): t.up() t.goto(x,y) t.down() t.goto(x-x-x,y) t.goto(x-x-x,y-y-y) t.goto(x,y-y-y) t.goto(x,y) x+=-10 y+=-10 t.pencolor(color[c]) main()
tagged with: turtle-graphics
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88353119
type: Question
has comment: http://stackoverflow.com/comment/88353342
has comment: http://stackoverflow.com/comment/88353339
has comment: http://stackoverflow.com/comment/88352806
score: 2
answer count: 1
downvote count: 0
has title: How to choose colors in sequence while using Python turtle?
has answer: http://stackoverflow.com/a/50673330
tagged with: colors
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/88182719
comment on: http://stackoverflow.com/a/50582200
score: 0
type: AnswerComment
has text: I am going to leave it open for some time because I would like to find a solution using the googletrans library, since the google cloud client has another troubles, like requests rate limit. Thanks!
type: Comment

http://stackoverflow.com/q/50555087
upvote count: 1
type: Question
tagged with: pdb
tagged with: debugging
has body: Need help, I am trying to add a change the functionality of c command to quit command, these changes are needed for further creation of new commands. I don't what I am doing wrong, how these two things are different first one is working fine but second one is not , I am just changing the behaviour db = pdb.Pdb() db.do_c = db.do_quit no = 3 db.runcall(fun,no) But this is not working , in this case self.do_quit is not getting even called. class dbg(pdb.Pdb): def custom_quit(self,arg): self.do_quit db = dbg() no = 3 db.do_c = db.custom_quit db.runcall(fun,no) I am just running on simple function fun def fun(no): print("a") print("b") for i in range(0,no): print(i) return 'abc' on command c it does nothing.
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88122193
tagged with: cpython
tagged with: python
has title: Converting one pdb command to another, but it's not working
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50555700

python-2to3
tags question: http://stackoverflow.com/q/50572313
tag name: python-2to3
type: Tag
tags question: http://stackoverflow.com/q/50656074

http://stackoverflow.com/a/50614784
has comment: http://stackoverflow.com/comment/88239658
has body: It seems that the first two rows of your CSV file are headers, but the default behavior of pd.read_csv thinks that only the first row is header. Also, the beginning and trailing quotes make pd.read_csv think the text in between is a single field/column. You could try the following: Remove the beginning and trailing quotes, and bbal = pd.read_csv('some_file.csv', header=[0, 1], delimiter=',') Following is how you could use Python to remove the beginning and trailing quotes: # open 'quotes.csv' in read mode with variable in_file as handle # open 'no_quotes.csv' in write mode with variable out_file as handle with open('quotes.csv') as in_file, open('no_quotes.csv', 'w') as out_file: # read in_file line by line # the variable line stores each line as string for line in in_file: # line[1:-1] slices the string to omit the first and last character # append a newline character '\n' to the sliced line # write the string with newline to out_file out_file.write(line[1:-1] + '\n') # read_csv on 'no_quotes.csv' bbal = pd.read_csv('no_quotes.csv', header=[0, 1], delimiter=',') bbal.head()
type: Answer
answers question: http://stackoverflow.com/q/50614545
has comment: http://stackoverflow.com/comment/88240286
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88239398
has comment: http://stackoverflow.com/comment/88239746
has comment: http://stackoverflow.com/comment/88240218
has comment: http://stackoverflow.com/comment/88239482
has comment: http://stackoverflow.com/comment/88240121
has comment: http://stackoverflow.com/comment/88239833
downvote count: 0

http://stackoverflow.com/comment/88287869
type: Comment
type: QuestionComment
has text: I haven't used Qt (and you don't mention it specifically) but I suspect that you are bumping into the old Gui Loop issue. You pass control to vlc with no way of getting back to the Gui's main loop until it finishes. I suggest having a look at a `Timer` function. http://www.rkblog.rk.edu.pl/w/p/qtimer-making-timers-pyqt4/
comment on: http://stackoverflow.com/q/50626583
score: 0

http://stackoverflow.com/comment/88311954
has text: @thatotherguy Okay, that's a bad news, but cheers :) Do I remove the post, or will it help python guys more specifically?
score: 0
comment on: http://stackoverflow.com/q/50650491
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50588745
type: Question
has comment: http://stackoverflow.com/comment/88469091
has comment: http://stackoverflow.com/comment/89380847
downvote count: 0
tagged with: amazon-web-services
has body: I'm using chalice for an application with a lot of endpoints. I don't want to separate it in several lambdas, because they share the same code (which is in chalicelib), but I want to separate somehow my app.py (e.g. I want it to be like app_user.py, app_sessions.py etc.) I'm not very good about Python core, but I think it should be possible to do it somehow using __init__.py to say the Chalice to glue my files together on the deployment. tl;dr Is it possible to have something like #include from C in Python? Thanks.
has comment: http://stackoverflow.com/comment/89003799
favorite count: 0
answer count: 0
type: UnansweredQuestion
has title: AWS Chalice - split the app.py in several files
upvote count: 1
tagged with: python
score: 1
tagged with: chalice

http://stackoverflow.com/a/50592497
type: Answer
answers question: http://stackoverflow.com/q/50592370
score: 2
accepted answer of: http://stackoverflow.com/q/50592370
upvote count: 2
has comment: http://stackoverflow.com/comment/88194575
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88194842
has comment: http://stackoverflow.com/comment/88194400
has body: Yes, you are trying to "force a square peg into a round hole". Your translate method works on the whole scores list, full stop. This can not be changed with some trickery, which is simply not supported in Python. When you want to do subslices, I would recommend doing it explicitly. Examples: # Using args/kwargs: scores = john.translate(10, 15) # translate subslice 10:15 # Using a new static method: scores = Person.translate_scores(john.scores[10:15]) Looks not that elegant, but works. (BTW: Since you changed your question, my classes might be a little of, but I will not change my answer with every edit you make) Your trickery simply does not work, because "scores" is not some part of your main class, but simply an attribute of it, which has its own type. So, when you do "d.scores.translate()" translate is not called on d, but on a list or whatever type scores is. You can not change that, because it is core Python.
has comment: http://stackoverflow.com/comment/88194556

http://stackoverflow.com/q/50601782
type: UnansweredQuestion
upvote count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/88212911
tagged with: python
has title: Django: Change value in request.POST to 0 if empty
has comment: http://stackoverflow.com/comment/88213283
has answer: http://stackoverflow.com/a/50602026
has comment: http://stackoverflow.com/comment/88213032
has body: I have the following form: When one of the tickets is empty, my form sends me an error with that every field is required, now I am trying to check if the form value is empty, if it's empty I want to change it to 0, so form.is_valid() can be true. The attached code doesn't work. It says string index out of range. def reserve_ticket(request): if request.method == 'POST': quantities = request.POST.getlist('quantity') for i in range(len(quantities)): if not request.POST['quantity'][i]: request.POST['quantity'][i] = 0 form = ReserveForm(request.POST) if form.is_valid(): print("Hello world") return HttpResponse("Hello world") else: return HttpResponse("Back to homepage")
tagged with: django-forms
has comment: http://stackoverflow.com/comment/88212746
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/88213473
answer count: 1
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88213151

http://stackoverflow.com/a/51518762
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50555668
has body: from flask_ckeditor import * csrf = CSRFProtect(app) csrf.init_app(app) ckeditor = CKEditor(app) app.config['CKEDITOR_SERVE_LOCAL'] = False app.config['CKEDITOR_HEIGHT'] = 400 app.config['CKEDITOR_FILE_UPLOADER'] = 'upload' app.config['UPLOADED_PATH'] = os.path.join(basedir, 'uploads') @app.route('/files/&lt;filename&gt;') @csrf.exempt def uploaded_files(filename): path = app.config['UPLOADED_PATH'] return send_from_directory(path, filename) import uuid @app.route('/upload', methods=['POST']) @csrf.exempt def upload(): f = request.files.get('upload') extension = f.filename.split('.')[1].lower() if extension not in ['jpg', 'gif', 'png', 'jpeg']: return upload_fail(message='Image only!') unique_filename = str(uuid.uuid4()) f.filename = unique_filename + '.' + extension f.save(os.path.join(app.config['UPLOADED_PATH'], f.filename)) url = url_for('uploaded_files', filename=f.filename) return upload_success(url=url) in edit.html in flask admin &lt;script&gt; CKEDITOR.plugins.addExternal( 'filebrowser', '/static/ckeditor/filebrowser/', 'plugin.js' ); CKEDITOR.config.extraPlugins = 'filebrowser'; CKEDITOR.config.filebrowserBrowseUrl = '/upload'; &lt;script&gt; This works for flask admin to upload images https://github.com/greyli/flask-ckeditor I used this
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50555668

http://stackoverflow.com/comment/88265002
has text: Any time you add a profiler (memory or execution) you add overhead. A memory specific profiler will likely have been coded without execution speed in mind, but rather to focus on counting the memory usage most accurately. You cannot take speed into account while using anything but a low overhead profiler that specifically is designed to measure computational speed. Even with a low-overhead profiler, your program will never run as fast as without it, because you are still asking the processor to execute more instructions.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50627267

http://stackoverflow.com/q/50611018
has body: I have a created a Open Street Map plot using cartopy: from __future__ import division import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.io.img_tiles as cimgt request = cimgt.OSM() extent = [-89, -88, 41, 42] ax = plt.axes(projection=request.crs) ax.set_extent(extent) ax.add_image(request, 8) plt.show() Now I also have a list of longitude and latitude points. How can I overlay a heatmap of these longitude and latitude points over the streetmap? I've tried using hist2d, but this doesn't work. lons = (-88 --89)*np.random.random(100)+-89 lats = (41 - 42)*np.random.random(100)+42 ax.hist2d(lons,lats) plt.show() But this doesn't work. I'm guessing I have to throw a transform argument in the plotting command somewhere? But I'm unsure how to go about it. Thanks!
score: 6
tagged with: python
upvote count: 6
tagged with: heatmap
type: AnsweredQuestion
type: Question
tagged with: cartopy
accepted answer: http://stackoverflow.com/a/50638691
answer count: 1
downvote count: 0
has title: Cartopy Heatmap over OpenStreetMap Background
favorite count: 0
has answer: http://stackoverflow.com/a/50638691

http://stackoverflow.com/comment/88296998
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50643386
score: 0
has text: Can you please tell, is that A and B are values or column names ? Seems confusing

http://stackoverflow.com/q/50601819
has body: I have a table like this: Movies: Title Rank a 5 b 6 b 6.5 c 7 lets say thats my table.I want to find if an input(title of a movie) a user gives from his keyboard exists in my database and if the movie that he selected exists only once in the table.
has answer: http://stackoverflow.com/a/50602078
has comment: http://stackoverflow.com/comment/88212831
accepted answer: http://stackoverflow.com/a/50602078
tagged with: pymysql
score: -1
has comment: http://stackoverflow.com/comment/88212858
answer count: 1
downvote count: 1
has title: PyMysql-Python:How to check if an input a user gives exists in my database
favorite count: 0
has comment: http://stackoverflow.com/comment/88213215
tagged with: python
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/88212880
has comment: http://stackoverflow.com/comment/88212985
has comment: http://stackoverflow.com/comment/88213282
has comment: http://stackoverflow.com/comment/88213137
type: Question
has comment: http://stackoverflow.com/comment/88213242

http://stackoverflow.com/a/50643489
score: 2
has body: You need to first convert to dataframe : X = pd.concat([X,pd.DataFrame([[data['first occurrence of \'AB\''],data['similarity to \'AB\'']]],columns=['first occurrence of \'AB\'','similarity to \'AB\''])], ignore_index=True) y = pd.concat([y,pd.DataFrame([data['Class']], columns=['Class'])], ignore_index=True) EDIT : add ignore_index=True
upvote count: 2
has comment: http://stackoverflow.com/comment/88299651
has comment: http://stackoverflow.com/comment/88300041
answers question: http://stackoverflow.com/q/50643118
has comment: http://stackoverflow.com/comment/88299079
has comment: http://stackoverflow.com/comment/88299830
has comment: http://stackoverflow.com/comment/88299448
has comment: http://stackoverflow.com/comment/88299585
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88299853
accepted answer of: http://stackoverflow.com/q/50643118
type: Answer

http://stackoverflow.com/comment/88357991
has text: Should be `elems = footer.find_elements_by_xpath(".//a[@href]")`, Missed a dot at beginning of xpath.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50673188
type: AnswerComment

http://stackoverflow.com/comment/88171209
score: 0
comment on: http://stackoverflow.com/q/50580918
type: Comment
has text: It works thank you very much.
type: QuestionComment

http://stackoverflow.com/comment/88465159
has text: Okay I've deleted all boost versions and managed to install it again so now i'm back to other related problems but i'll post that in a new post. thanks.
score: 0
comment on: http://stackoverflow.com/q/50685538
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88303933
has text: @jdehesa FYI it's now possible to pass `data` dicts directly as the `source` arg. If you don't to share a `ColumnDataSource`, then that makes the code a little shorter. I've updated your example.
type: AnswerComment
comment on: http://stackoverflow.com/a/50642536
type: Comment
score: 1

system-calls
type: Tag
tags question: http://stackoverflow.com/q/50663153
tag name: system-calls

http://stackoverflow.com/comment/88384067
has text: @MustacheMoses What is the advantage of a tuple?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50687133
type: AnswerComment

http://stackoverflow.com/comment/88533868
comment on: http://stackoverflow.com/a/50680979
type: Comment
has text: Hi Sagar, thank you for your help! I still have an error. It seems like I can open the folder, but then it still won't read my images. This is the error: FileNotFoundError: [Errno 2] No such file or directory: 'BrigitteBardot1-Copy1.jpg' I changed line 5 to the following: for i in os.listdir('Folder'):
score: 0
type: AnswerComment

http://stackoverflow.com/a/50579198
answers question: http://stackoverflow.com/q/50578524
has comment: http://stackoverflow.com/comment/88174776
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88175937
has comment: http://stackoverflow.com/comment/88171180
has comment: http://stackoverflow.com/comment/88175664
type: Answer
has body: You cannot send it as a parameter. You can set it as a normal setter though in the following way. mail.template_id = "13b8f94f-bcae-4ec6-b752-70d6cb59f932" You can find the same implementation in the mail_example.py file in the sendgrid package Using Substitution/Personalization: #add this code to your method where you have initialized Mail() object personalization = get_mock_personalization_dict() mail.add_personalization(build_personalization(personalization)) mail.add_personalization(build_personalization(personalization)) #Example of a Personalization Object def get_mock_personalization_dict(): mock_pers = dict() mock_pers['substitutions'] = [Substitution("%name%", "Example User"), Substitution("%city%", "Denver")] #Updates the mail object with personalization variable def build_personalization(personalization): for substitution in personalization['substitutions']: personalization.add_substitution(substitution)
has comment: http://stackoverflow.com/comment/88171933
downvote count: 0
has comment: http://stackoverflow.com/comment/88176132
accepted answer of: http://stackoverflow.com/q/50578524
has comment: http://stackoverflow.com/comment/88176358
score: 1

http://stackoverflow.com/comment/88180207
has text: A simpler way to do that, without using `try... except`, is to give `next` an appropriate default arg.
comment on: http://stackoverflow.com/a/50585385
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/q/50610593
duplicate of: http://stackoverflow.com/q/35845768
score: 0
has body: While installing I faced syntax error: &gt;&gt;&gt; pip3 install numpy File "", line 1 pip3 install numpy ^ SyntaxError: invalid syntax &gt;&gt;&gt; pip install -U scikit-learn File "", line 1 pip install -U scikit-learn ^ SyntaxError: invalid syntax Please tell me how to install the packages required and if I am missing any pre-requisites.
answer count: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/88383635
accepted answer: http://stackoverflow.com/a/50610634
tagged with: python
type: AnsweredQuestion
tagged with: installation
type: Question
has comment: http://stackoverflow.com/comment/88231037
linked to: http://stackoverflow.com/q/8663046
linked to: http://stackoverflow.com/q/35845768
has title: How to install Python packages for Python 3.6.5 for Windows 10
has answer: http://stackoverflow.com/a/50610634
has comment: http://stackoverflow.com/comment/88231102

http://stackoverflow.com/a/50603732
answers question: http://stackoverflow.com/q/50603619
has comment: http://stackoverflow.com/comment/88219800
accepted answer of: http://stackoverflow.com/q/50603619
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88217019
type: Answer
has body: If you specify auto_now=True, or auto_now_add=True, then you make the field editable=False at the same time. Hence it means it will not show up in the form. Probably a minimal change would be to specify a default value by using a function, instead of using the auto_now_add=True property, like: from django.utils import timezone as tz class TestRule(models.Model): code = models.CharField(_('Code'), max_length=56, null=False, blank=False, db_column='code') name = models.CharField(_('Name'), max_length=128, null=False, db_index=True, db_column='name', blank=False) created_at = models.DateTimeField(_('Created At'), null=False, db_column='created_at', blank=False, default=tz.now) Note that we do not call the now(..) function. If we would do that, then we would set the created_at column to the timestamp when we constructed the models (not the instances of the model). By passing a reference to the now(..) function, the function will be called when a new model instance is added.
has comment: http://stackoverflow.com/comment/88219729
has comment: http://stackoverflow.com/comment/88220271
score: 5
upvote count: 5

http://stackoverflow.com/comment/88411156
type: Comment
comment on: http://stackoverflow.com/a/50692152
has text: Having 1 huge table versus 100 large tables does not inherently change the performance of a `SELECT` against that much data. I see your data as being "modestly challenging", not "panic, get out the heavy artillery". There are many different approaches possible; we need to see what type of data before being more specific about tactics.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88098299
comment on: http://stackoverflow.com/q/50543573
score: 0
has text: Try https://stackoverflow.com/questions/6027558/flatten-nested-python-dictionaries-compressing-keys
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88377045
type: Comment
type: QuestionComment
has text: Concur with coldspeed this works for me with `0.23.0` what does `print(pd.__version__)` show? You've either upgraded the incorrect location or you need to restart the kernel
score: 0
comment on: http://stackoverflow.com/q/50683616

http://stackoverflow.com/comment/88256280
type: Comment
comment on: http://stackoverflow.com/a/50623076
type: AnswerComment
has text: You are welcome :)
score: 0

strava
type: Tag
tags question: http://stackoverflow.com/q/50661037
tags question: http://stackoverflow.com/q/50597854
tag name: strava

http://stackoverflow.com/q/50573089
has body: I am trying to install tensorflow for python on a Mac, and I am following the instructions provided on the website. I decided to use virtualenv because pip has been giving me issues lately, and the website recommended virtualenv as well. Although I apparently have downloaded tensorflow for Python 3, I also want to have it available in Python 2 (which I use more anyway). Here is what I have done so far: $virtualenv --system-site-packages ~/tensorflow $ cd ~/tensorflow tensorflow$ pip install --upgrade tensorflow I get the following message to show up: Requirement already up-to-date: tensorflow in /usr/local/lib/python3.6/site-packages (1.8.0) If you have any suggestions or commands to run, that would be greatly appreciated.
tagged with: virtualenv
has answer: http://stackoverflow.com/a/50573131
tagged with: python
type: AnsweredQuestion
tagged with: installation
tagged with: pip
tagged with: tensorflow
type: Question
has title: Issues with installing tensorflow for python using virtualenv
accepted answer: http://stackoverflow.com/a/50573131
score: 0
answer count: 1

http://stackoverflow.com/comment/88273602
comment on: http://stackoverflow.com/a/50631650
score: 0
type: AnswerComment
has text: sounds promising but it says: Object of type 'QuerySet' is not JSON serializable
type: Comment

http://stackoverflow.com/comment/88293586
score: 0
type: Comment
type: QuestionComment
has text: @Dan I added a snapshot of the files being read as dataframes.It seems as if the first line is being ignored by the pd.read_csv as index
comment on: http://stackoverflow.com/q/50640070

http://stackoverflow.com/comment/123653192
type: Comment
score: 1
comment on: http://stackoverflow.com/a/58514954
type: AnswerComment
has text: If matches occur near the edge of the image in the optimized function, max_loc[1]-h//2 and max_loc[0]-w//2 could be negative, which overwrites the wrong portion of the image and probably causes an infinite loop. Using max(..., 0) seems to fix the issue.

http://stackoverflow.com/q/50660343
tagged with: django-annotate
answer count: 0
tagged with: django-orm
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/88359935
has title: Django ORM queryset takes integer filed as string
has body: results = UmUrl.objects \ .filter(created_at__gte=sdate, created_at__lte=edate) \ .annotate(timeValue=self.get_date_format(param)) \ .values('timeValue') \ .order_by('timeValue') \ .annotate(blocked=Sum(Case(When(operation=0, then=1), default=0, output_field=models.IntegerField()))) \ .annotate(unBlocked=Sum(Case(When(operation=1, then=1), default=0, output_field=models.IntegerField()))) 'operation' filed is Integer type. This code creates an sql query, but in the sql reult 'when' parameters is shown as string type. So that it does not work. sql output like that. How can I solve this problem? {"query": "SELECT DISTINCT CONCAT(EXTRACT('year' FROM \"um_url\".\"created_at\" AT TIME ZONE 'Europe/Istanbul'), CONCAT('-', EXTRACT('month' FROM \"um_url\".\"created_at\" AT TIME ZONE 'Europe/Istanbul'))) AS \"timeValue\", SUM(CASE WHEN \"um_url\".\"operation\" = '0' THEN '1' ELSE '0' END) AS \"blocked\", SUM(CASE WHEN \"um_url\".\"operation\" = '1' THEN '1' ELSE '0' END) AS \"unBlocked\" FROM \"um_url\" WHERE (\"um_url\".\"created_at\" &lt;= '2018-06-02 15:47:51.857000+00:00' AND \"um_url\".\"created_at\" &gt;= '2018-06-01 15:47:51.857000+00:00') GROUP BY CONCAT(EXTRACT('year' FROM \"um_url\".\"created_at\" AT TIME ZONE 'Europe/Istanbul'), CONCAT('-', EXTRACT('month' FROM \"um_url\".\"created_at\" AT TIME ZONE 'Europe/Istanbul'))) ORDER BY \"timeValue\" ASC", "empty_check": "true"}
has comment: http://stackoverflow.com/comment/88358493
type: Question
tagged with: django-queryset
has comment: http://stackoverflow.com/comment/88359912
score: 0
tagged with: python

http://stackoverflow.com/a/50547199
answers question: http://stackoverflow.com/q/50547145
has comment: http://stackoverflow.com/comment/88105266
has body: Sample code:- line = f.readlines() option = int(input('Select line number to edit or remove:')) selectedline = line[option-1] print(selectedline,'[Selected]') action = int(input('''What you want to do [1] Edit Quantity [2] Remove ''')) edit = selectedline.split() if action == 1: qty = int(input('Enter new quanity')) edit[-1] = str(float(edit[3])/float(edit[-1])) edit[3] = str(qty) edit[-1] = str(qty) print(edit) line = ' '.join(edit) # use line as per your needs
has comment: http://stackoverflow.com/comment/88105203
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50547145
type: Answer

http://stackoverflow.com/a/50560806
answers question: http://stackoverflow.com/q/50560652
has comment: http://stackoverflow.com/comment/88132182
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50560652
has comment: http://stackoverflow.com/comment/88132057
type: Answer
has body: I believe need if lenght of testdata is same as predictions: Test it: print (len(testdata)) print (len(predictions)) df = pd.DataFrame({'id':testdata['id'], 'predictions':predictions})
has comment: http://stackoverflow.com/comment/88132218
score: 2
has comment: http://stackoverflow.com/comment/88132097
upvote count: 2
has comment: http://stackoverflow.com/comment/88132138

http://stackoverflow.com/comment/88267049
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50628422
score: 2
has text: Why are your columns a list of lists?

http://stackoverflow.com/q/50547341
answer count: 1
tagged with: flask-sqlalchemy
favorite count: 0
has comment: http://stackoverflow.com/comment/88105479
has answer: http://stackoverflow.com/a/50547428
tagged with: python
type: AnsweredQuestion
upvote count: 1
downvote count: 1
has body: I am learning the book flask web development, I want to prepare objects to be written to the database (add them to the session), but when I run db.session.add(admin_role), an error occurs. Could anyone help me solve this issue? This is the code: class Role(db.Model): __tablename__ = 'roles' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True) users = db.relationship('User', backref='role') def __repr__(self): return '&lt;Role %r&gt;' % self.name class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), unique=True, index=True) role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) def __repr__(self): return '&lt;User %r&gt;' % self.username Inserting Rows &gt;&gt;&gt; from hello import Role, User &gt;&gt;&gt; admin_role = Role(name='Admin') &gt;&gt;&gt; mod_role = Role(name='Moderator') &gt;&gt;&gt; user_role = Role(name='User') &gt;&gt;&gt; user_john = User(username='john', role=admin_role) &gt;&gt;&gt; user_susan = User(username='susan', role=user_role) &gt;&gt;&gt; user_david = User(username='david', role=user_role) &gt;&gt;&gt; db.session.add(admin_role) Traceback (most recent call last): File "/Users/cool/PycharmProjects/website/venv/lib/python3.6/site-packages/sqlalchemy/util/_collections.py", line 999, in __call__ return self.registry[key] KeyError: 4321375104 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "/Users/cool/PycharmProjects/website/venv/lib/python3.6/site-packages/sqlalchemy/orm/scoping.py", line 153, in do return getattr(self.registry(), name)(*args, **kwargs) File "/Users/cool/PycharmProjects/website/venv/lib/python3.6/site-packages/sqlalchemy/util/_collections.py", line 1001, in __call__ return self.registry.setdefault(key, self.createfunc()) File "/Users/cool/PycharmProjects/website/venv/lib/python3.6/site-packages/sqlalchemy/orm…
type: Question
accepted answer: http://stackoverflow.com/a/50547428
tagged with: flask
score: 0
has title: Flask cannot add objects to the session
has comment: http://stackoverflow.com/comment/88105412

http://stackoverflow.com/q/50558784
upvote count: 2
has answer: http://stackoverflow.com/a/70128475
type: Question
has body: I am using pathlib module to check whether an specific directory exists or not. If not, then the directory has been created. file_or_directory=Path(path+"/"+mobile_no+"/"+ "CV") if file_or_directory.exists(): print(mobile_no+"/"+"CV" + " directory exits---") else: print(mobile_no+"/"CV" --directory does not exit. --So Create it") file_or_directory.mkdir(parents=True, exist_ok=True) But, the problem is that normally in windows file system (Both NTFS and FAT) directory works in case insensitive mode. According the the example, if a directory called "CV" has been created but I might want to create another directory named "cv" uniquely to be treated completely different from "CV" in terms of sub-directories. Is there any way to create directories in case sensitive ? I am using windows 10 and x64 machine.
has title: How to make the Path Class of pathlib module work in case sensitive mode ?
score: 2
answer count: 1
downvote count: 0
tagged with: directory
has comment: http://stackoverflow.com/comment/123062714
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/88359308
comment on: http://stackoverflow.com/q/50674067
score: 0
type: Comment
type: QuestionComment
has text: @mshsayem Thanks a lot! This resolves my issue. I just need to use `python3`.

http://stackoverflow.com/q/50697579
tagged with: python
has comment: http://stackoverflow.com/comment/88405739
answer count: 0
has title: Using libsvm's predict function. Argument support expected ndarray, int found error
has comment: http://stackoverflow.com/comment/88406097
has comment: http://stackoverflow.com/comment/88405445
has comment: http://stackoverflow.com/comment/88406026
type: Question
has body: I'm trying to use libsvm to predict probability, and I'm using following command: print(svm.libsvm.predict(x, 3, 'rbf', 3, 0.05, 0.0)) It follows from the documentation, args are: X: array-like, svm_type: {0, 1, 2, 3, 4}, kernel: {'linear', 'rbf' ...} degree: int, gamma: float, coef0: float But it gives me the following error: Argument 'support' has incorrect type (expected numpy.ndarray, got int) I went through the source code for the wrapper here: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/libsvm.pyx And there is no such documentation on what support etc. params are. Can anyone help me with the usage of this predict function and/or about this error?
tagged with: scikit-learn
score: 0
tagged with: libsvm
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88405615
has comment: http://stackoverflow.com/comment/88405538

http://stackoverflow.com/q/50599042
type: AnsweredQuestion
has body: I have written a naive bayes classifier for text messages and it's script is as follows: tester.py import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import train_test_split from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import accuracy_score df = pd.read_table('a.txt', sep='\t', header=None, names=['label', 'text']) ... On testing, it worked correctly. Now I have created a django project where this script and the a.txt file are placed alongside views.py and urls.py. When user enters a comment, it is processed in views file as: views.py from .tester import predictor def result(request): content = request.POST['content'] res = predictor(content) status = '' if res == 0: status = 'not spam' else: status = 'spam' return render(request, 'spammer/result.html', {'status':status,}) Where predictor is a function I have added to tester.py: def predictor(comment): tester = [comment] contest = count_vector.transform(tester) #count_vector=CountVectorizer() a = naive_bayes.predict(contest) #naive_bayes=MultinomialNB() return a[0] However on running the server, there is an error: File "pandas/_libs/parsers.pyx", line 384, in pandas._libs.parsers.TextReader.__cinit__ File "pandas/_libs/parsers.pyx", line 695, in pandas._libs.parsers.TextReader._setup_parser_source FileNotFoundError: File b'a.txt' does not exist which is not the case. Where am I going wrong? I have installed pandas,scipy,sklearn in virtual environment using pip and tester.py as well as a.txt are in the same directory as views.py,urls.py
has answer: http://stackoverflow.com/a/50599634
has title: File not found error while using pandas in django
type: Question
score: 0
accepted answer: http://stackoverflow.com/a/50599634
tagged with: pandas
answer count: 1
tagged with: django
tagged with: python

http://stackoverflow.com/comment/88395967
comment on: http://stackoverflow.com/q/50692955
has text: This feels like an XY problem. Why don't you just use a session to form a query using the passed field directly?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88126707
has text: Anyone else have an idea how to do this?
comment on: http://stackoverflow.com/q/50556059
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50693886
has comment: http://stackoverflow.com/comment/88397210
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88397350
answer count: 0
has comment: http://stackoverflow.com/comment/88397288
has title: Django- Make python object persist during a session
score: 0
type: Question
has comment: http://stackoverflow.com/comment/88397592
tagged with: session
tagged with: caching
has body: I have a class which has an FSM. I want store variables and transition through the FSM states based on repeated interaction with the user. It's something like a chat interface. So, as per my requirements, I have a object that is not part of the database (not included in models but defined in a custom python file). I want to create an class instance per-user-per-session and have it persist through the session. I thought this could be done via session variables in Django but I read that you can't keep class instances as session variables (may be possible by pickling, but I read in multiple places that its discouraged). It maybe possible using cache system, but I do not know how to go about it. Can someone give me some solid directions on what the best method would be and how to implement it? I have not included any code, because I think the question is more in terms of knowledge than just implementation, but I can provide some example code if required.
tagged with: fsm
has comment: http://stackoverflow.com/comment/88397442

http://stackoverflow.com/comment/136174561
score: 0
comment on: http://stackoverflow.com/q/50585096
type: Comment
type: QuestionComment
has text: I have the opposite problem - i.e. how do I convert SQL Decimal to float? :\

http://stackoverflow.com/q/50542358
type: Question
score: 0
accepted answer: http://stackoverflow.com/a/50542461
has body: have this problem that when i try connecting to an API it keeps sending me wrong signature and I realised that it is because when I read from the file, python 3 has these square brackets on it. When I hard code the API key and secret inside the program it works. import requests import base64 import hmac import hashlib from hashlib import sha384 from io import BytesIO import time import json def connect(): f=open("Test-API.txt", "r") if f.mode == 'r': api_key =f.readline().splitlines() print(repr(api_key)) api_secret =f.readline().splitlines() print(repr(api_secret)) f.close() api_key = 'Your API Key' api_secret = 'Your API Secret' print(repr(api_key)) print(repr(api_secret)) connect() I realised the problem might be because of the square brackets cause when I used REPR i see the square brackets being printed. Is there a way to remove it? ['Your API Key'] ['Your API Secret'] 'Your API Key' 'Your API Secret'
answer count: 1
tagged with: python-3.x
has title: python 3.X shows different input from when i hard code the string in program
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50542461

http://stackoverflow.com/a/67537603
score: 0
answers question: http://stackoverflow.com/q/50554835
type: AcceptedAnswer
has body: As shown in the corresponding bug report for matplotlib (#11375), matplotlib’s PGF backend does not support text clipping, which is causing this issue, which still seems to persist today.
type: Answer
accepted answer of: http://stackoverflow.com/q/50554835

http://stackoverflow.com/comment/88180594
comment on: http://stackoverflow.com/a/50576940
score: 0
type: AnswerComment
type: Comment
has text: Thanks a lot. I was just confused how sets work in python I guess. That clears some of my doubts.

http://stackoverflow.com/comment/88325562
type: QuestionComment
has text: yes How to "partition" the list of images into buckets
comment on: http://stackoverflow.com/q/50657714
score: 0
type: Comment

http://stackoverflow.com/q/50592706
has answer: http://stackoverflow.com/a/50592839
downvote count: 3
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/88194870
has comment: http://stackoverflow.com/comment/88195332
favorite count: 0
has body: I want to merge data that looks something like the following (there are a lot of different files too holding bar data). There are a bunch of different data frames, set up like below. id bar baz 1 10 15 2 12 69 id bar baz 3 96 75 id bar baz 4 45 76 5 75 23 id foo bah 1 0.1 81 2 0.2 59 3 0.1 89 4 0.1 642 5 0.2 51 I want to merge everything into a single file which has columns id, foo, bah, bar, and baz. I tried repeated invocations of df = pd.merge(df, t_df, how='outer', on=key_trans[key]) in a for-loop, but that doesn't work, and instead produces columns bar_x, bar_y, etc. for each original variable. Note on above: key_trans is a key which gives data that needs to be preserved, like id (and other kinds of ids that I've simplified away in asking the question).
upvote count: 0
has comment: http://stackoverflow.com/comment/88194945
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/88195276
has comment: http://stackoverflow.com/comment/88194857
has comment: http://stackoverflow.com/comment/88195157
has comment: http://stackoverflow.com/comment/88194890
has comment: http://stackoverflow.com/comment/88195162
has comment: http://stackoverflow.com/comment/88195234
has title: Pandas merge and concatenate
type: Question
answer count: 1

http://stackoverflow.com/q/50683450
has title: Error compiling Cython file in buildozer
has comment: http://stackoverflow.com/comment/88377383
tagged with: buildozer
tagged with: pyjnius
tagged with: cythonize
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50913947
has body: I have built an android app using kivy and while I was compiling it to build an apk using buildozer, the following error popped up; [INFO]: -&gt; directory context /home/himanshu/helplineapp/.buildozer/android/platform/build/build/other_builds/pyjnius-python2-sdl2/armeabi-v7a/pyjnius [INFO]: -&gt; running python.host -c import sys; print(sys.path) working: ['', '/home/himanshu/helplineapp/.buildozer/android/platform/build/build/python-instal[INFO]: Trying first build of pyjnius to get cython files: this is expected to fail [INFO]: -&gt; running python.host setup.py build_ext -v ('cwd is', '/home/himanshu/helplineapp/.buildozer/android/platform/build/build/other_builds/pyjnius-python2-sdl2/armeabi-v7a/pyjnius') working: #error Do not use this file, it is the result of a failed Cython compilatiException in thread background thread for pid 3379: Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner self.run() File "/usr/lib/python2.7/threading.py", line 754, in run self.__target(*self.__args, **self.__kwargs) File "/home/himanshu/.local/lib/python2.7/site-packages/sh.py", line 1540, in wrap fn(*args, **kwargs) File "/home/himanshu/.local/lib/python2.7/site-packages/sh.py", line 2455, in background_thread handle_exit_code(exit_code) File "/home/himanshu/.local/lib/python2.7/site-packages/sh.py", line 2153, in fn return self.command.handle_command_exit_code(exit_code) File "/home/himanshu/.local/lib/python2.7/site-packages/sh.py", line 815, in handle_command_exit_code raise exc ErrorReturnCode_1: RAN: /home/himanshu/helplineapp/.buildozer/android/platform/build/build/python-installs/myapp/bin/python.host setup.py build_ext -v STDOUT: /home/himanshu/helplineapp/.buildozer/android/platform/build/build/python-installs/myapp/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'install_requires' warnings.warn(msg) running build_ext building 'jnius' extension /usr/bin/ccache arm-linux-androideabi-gc…
type: UnansweredQuestion
tagged with: python
downvote count: 1
score: 2
upvote count: 3
tagged with: cython
type: Question

http://stackoverflow.com/comment/88352197
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50670930
has text: I misread a portion of your code and made some edits and suggestions accordingly

http://stackoverflow.com/comment/88344484
score: 0
type: Comment
has text: Are these articles stored in the database? Since constructing two `Article` instances is *not* enough.
type: QuestionComment
comment on: http://stackoverflow.com/q/50667217

http://stackoverflow.com/a/50662356
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/50548556
type: Answer
downvote count: 1
has body: Also if someone needs: Fancy rectangle with curved corners in C: However I needed this code in python was replied by the community. void draw_border(IplImage* show_img, CvPoint pt1, CvPoint pt2, CvScalar color, int thickness, int r, int d): // Top left cvLine(show_img, cvPoint( pt1.x +r, pt1.y), cvPoint( pt1.x + r + d, pt1.y), color, thickness, 8, 0 ); cvLine(show_img, cvPoint( pt1.x, pt1.y + r), cvPoint( pt1.x, pt1.y + r + d), color, thickness, 8, 0 ); cvEllipse(show_img, cvPoint(pt1.x +r, pt1.y + r), cvSize( r, r ), 180, 0, 90, color, thickness, 8, 0); // Top right cvLine(show_img, cvPoint( pt2.x - r, pt1.y), cvPoint( pt2.x - r - d, pt1.y), color, thickness, 8, 0 ); cvLine(show_img, cvPoint( pt2.x, pt1.y + r), cvPoint( pt2.x, pt1.y + r + d), color, thickness, 8, 0 ); cvEllipse(show_img, cvPoint(pt2.x -r, pt1.y + r), cvSize( r, r ), 270, 0, 90, color, thickness, 8, 0); // Bottom left cvLine(show_img, cvPoint( pt1.x + r, pt2.y), cvPoint( pt1.x + r + d, pt2.y), color, thickness, 8, 0); cvLine(show_img, cvPoint( pt1.x, pt2.y - r), cvPoint( pt1.x, pt2.y - r - d), color, thickness, 8, 0); cvEllipse(show_img, cvPoint(pt1.x + r, pt2.y - r), cvSize( r, r ), 90, 0, 90, color, thickness, 8, 0); // Bottom right cvLine(show_img, cvPoint( pt2.x - r, pt2.y), cvPoint( pt2.x - r - d, pt2.y), color, thickness, 8, 0); cvLine(show_img, cvPoint( pt2.x, pt2.y - r), cvPoint( pt2.x, pt2.y - r - d), color, thickness, 8, 0); cvEllipse(show_img, cvPoint(pt2.x - r, pt2.y - r), cvSize( r, r ), 0, 0, 90, color, thickness, 8, 0);

http://stackoverflow.com/q/50591822
has comment: http://stackoverflow.com/comment/88192975
has title: How to properly connect two functions in python?
type: Question
accepted answer: http://stackoverflow.com/a/50594295
has comment: http://stackoverflow.com/comment/88193080
tagged with: function
score: -1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50594295
downvote count: 2
upvote count: 1
tagged with: python
has body: I have problem with connecting two functions to each other in my small program. I am using PyQt5 and PyPDF2 modules.I would like to link two pdf files into one. In my program I have 3 buttons: btnPlik1 - browse 1st file (connected to function openFile1) btnPlik2 - browse 2nd file (connected to function openFile2) btnPlik3 - 'start' - run program (connected to function laczeniePdf) Functions work separately but when I would like to connect them by clicking 'Start'(btnPlik3) my program crashes. Below is my code: def openFile1(self): pathFileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Wybierz plik', '', 'pdf(*.pdf)') print("PathFileName-'{}', \n_-'{}'".format(pathFileName, _)) if pathFileName: print("Wybrany plik: ", pathFileName) g = open(pathFileName, 'rb') return g def openFile2(self): pathFileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Wybierz plik', '', 'pdf(*.pdf)') print("PathFileName-'{}', \n_-'{}'".format(pathFileName, _)) if pathFileName: print("Wybrany plik: ", pathFileName) h = open(pathFileName, 'rb') return h def laczeniePdf(self,g, h): readerLinkPage1 = PyPDF2.PdfFileReader(open(g, 'rb')) readerLinkPage2 = PyPDF2.PdfFileReader(open(h, 'rb')) writerLinkPage = PyPDF2.PdfFileWriter() OutputFile = open('FinalOutput.pdf', 'wb') writerLinkPage.appendPagesFromReader(readerLinkPage1) writerLinkPage.appendPagesFromReader(readerLinkPage2) writerLinkPage.write(OutputFile) OutputFile.close() I am looking forward for your hints and advises EDIT: Here is code of class we are talking about(it is separate window in my program) class Ui_PolaczPliki(object): def setupUi(self, PolaczPliki): PolaczPliki.setObjectName("PolaczPliki") PolaczPliki.resize(295, 113) self.btnPlik1 = QtWidgets.QPushButton(PolaczPliki) self.btnPlik1.setGeometry(QtCore.QRect(30, 40, 91, 41)) self.btnPlik1.setObjectName("btnPlik1") self.btnPlik1.clicked.connect(self.openFile1) self.btnPlik2 = QtWidgets.QPushButton(PolaczPliki) self.btnPlik2.setGeometry(QtCore.QRect(160, 40, 91, 4…
type: AnsweredQuestion
tagged with: oop
has comment: http://stackoverflow.com/comment/88193685
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/88193117

http://stackoverflow.com/comment/88139224
score: 1
type: AnswerComment
has text: `next` without a second argument is better wrapped in a `try` loop since it can raise an `StopIteration` Exception.
type: Comment
comment on: http://stackoverflow.com/a/50563841

http://stackoverflow.com/q/50570625
tagged with: compare
tagged with: python
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/88151120
accepted answer: http://stackoverflow.com/a/50588978
upvote count: 1
possible better answer: http://stackoverflow.com/a/50584600
type: Question
has answer: http://stackoverflow.com/a/50588978
tagged with: rows
answer count: 2
has comment: http://stackoverflow.com/comment/88153062
downvote count: 0
has answer: http://stackoverflow.com/a/50584600
favorite count: 0
tagged with: iteration
tagged with: calculated-columns
has body: First of all, please pardon my skills. I am trying to get into Python, I learn just for fun, let's say, I don't use it professionally and I am quite bad, to be honest. Probably there will be basic errors on my question. Anyway, I am trying to go over a dataframe's rows and columns. I want to check if the values of the columns (except the first one) are NaNs. If they are, then they should change to the value of the first one. import math for index, row in rawdata3.iterrows(): test = row[0] for column in row: if math.isnan(row.loc[column]) == True: row.loc[column] = test The error I get is something like this: the label [4.0] is not in the [columns] I also had other errors with slightly different code like: cannot do label indexing on class pandas.core.indexes.base.Index with these indexers class float Could you give me a hand, please? Thanks in advance! Cheers.
has title: Python - iterate over rows and columns

http://stackoverflow.com/comment/88323652
type: Comment
type: QuestionComment
has text: Yes I know `super()` can call methods of sibling of `object`, but this cannot change the fact that `object` appears at the very end of mro list except when old-style class is present.
score: 0
comment on: http://stackoverflow.com/q/50656716

http://stackoverflow.com/a/50552776
answers question: http://stackoverflow.com/q/50552756
has comment: http://stackoverflow.com/comment/88118245
score: 4
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88118230
has comment: http://stackoverflow.com/comment/88118420
type: Answer
has body: Use groupby with size first, then sort_values, create columns by reset_index and last if necessary change order of columns by reindex: df = (df.groupby(['Author', 'Comment'], sort=False).size() .sort_values(ascending=False) .reset_index(name='Number') .reindex(columns=['Author','Number','Comment'])) print (df) Author Number Comment 0 bob 4 Follow me 1 casy 3 Nice picture! 2 casy 2 Wow! 3 bob 1 Dissapointing 4 linda 1 Check my profile 5 linda 1 Interesting post 6 tom 1 I disagree 7 linda 1 I like this
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/88118450
accepted answer of: http://stackoverflow.com/q/50552756
has comment: http://stackoverflow.com/comment/88117752

http://stackoverflow.com/comment/123558123
score: 1
comment on: http://stackoverflow.com/q/50620954
type: Comment
type: QuestionComment
has text: @ekhumoro The Python interpreter is crashing with non-zero exit code when PyCharm/IntelliJ attempts to iterate properties. In this scenario, the Python interpreter does not provide an exception stack trace. It is possible that Linux could provide a `core` dump.

http://stackoverflow.com/q/50629482
tagged with: pycrypto
accepted answer: http://stackoverflow.com/a/50634103
type: Question
score: 0
answer count: 1
has title: pycrypto massup when install with crypto on mac
tagged with: centos
tagged with: python
tagged with: macos
tagged with: pip
has body: I am trying to install crypto and pycrypto in same virtual environment. [root@jnkslave01 tmp]# virtualenv test_pycrypto New python executable in /root/tmp/test_pycrypto/bin/python Installing setuptools, pip, wheel...done. [root@jnkslave01 tmp]# source test_pycrypto/bin/activate (test_pycrypto) [root@jnkslave01 tmp]# pip install crypto==1.4.1 pycrypto==2.6.1 Collecting crypto==1.4.1 /root/tmp/test_pycrypto/lib/python2.6/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:318: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#snimissingwarning. SNIMissingWarning /root/tmp/test_pycrypto/lib/python2.6/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning /root/tmp/test_pycrypto/lib/python2.6/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning /root/tmp/test_pycrypto/lib/python2.6/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLC…
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50634103

http://stackoverflow.com/q/50663594
score: 5
tagged with: deep-learning
downvote count: 0
favorite count: 0
has body: In some deep learning workflows, it is useful to train a model, extract it out of its graph using tf.graph_util.convert_variables_to_constants or tf.graph_util.extract_sub_graph so training-related tensors are left out, and then connect the extracted subgraph to other model(s) via tf.import_graph_def. In this way, the trained model can serve as a building block in a larger setup. Often, we'd like to backpropagate through the new, composite model, in order to fine-tune it, optimize the inputs and so on. However, it appears that one cannot define a gradient through a while_loop tensorflow operation in an imported graph, since it relies on 'outer context', an object added into the metagraph's collections (see TF issue #7404). Slightly adapting the example in this Github issue, here's an example of what I am trying to do: import tensorflow as tf g1=tf.Graph() sess1=tf.Session(graph=g1) with g1.as_default(): with sess1.as_default(): i=tf.constant(0, name="input") out=tf.while_loop(lambda i: tf.less(i,5), lambda i: [tf.add(i,1)], [i], name="output") loss=tf.square(out,name='loss') graph_def = tf.graph_util.convert_variables_to_constants(sess1,g1.as_graph_def(),['output/Exit']) g2 = tf.Graph() with g2.as_default(): tf.import_graph_def(graph_def,name='') i_imported = g2.get_tensor_by_name("input:0") out_imported = g2.get_tensor_by_name("output/Exit:0") tf.gradients(out_imported, i_imported) The last line raises an AttributeError: 'NoneType' object has no attribute 'outer_context' error. Tensorflow's solution to this issue is to use tf.train.export_meta_graph and tf.train.import_meta_graph so the outer context is copied, but this copies the entire graph, without editting. In this minimal case, the 'loss' tensor won't be removed. I tried copying the missing context to the new graph: g2.add_to_collection('while_context',g1.get_collection('while_context')) But it doesn't solve the issue. Is there a way to overcome this limitation or is it an irreparable Tensorflow design flaw?
type: UnansweredQuestion
tagged with: python
answer count: 0
tagged with: tensorflow
type: Question
upvote count: 5
has title: Computing gradients in extracted Tensorflow subgraph which contains a 'while_loop'

http://stackoverflow.com/q/50554467
has answer: http://stackoverflow.com/a/55174884
favorite count: 0
tagged with: package
tagged with: python
tagged with: spacy
type: UnansweredQuestion
tagged with: anaconda
has title: "Resolve Package Not Found" error in anaconda
score: 7
has comment: http://stackoverflow.com/comment/90650294
tagged with: conda
upvote count: 8
type: Question
has body: I installed anaconda in Windows and then I wanted to add this code conda env create -f robotreviewer_env_local.yml but I got this error ResolvePackageNotFound - spacy=0.101.0 - ptyprocess=0.5.1 How can I solve this problem?
answer count: 1
downvote count: 1

http://stackoverflow.com/q/50579629
type: UnansweredQuestion
has body: I tried to read an excel file into the Ijupyer notebook with the following code : import pandas as pd import numpy as np import matplotlib as plt df=pd.read_csv('Data_2.xlsx') However, it gave me the result : ParserError: Error tokenizing data. C error: Expected 1 fields in line 4, saw 2 The excel file looks as such
has comment: http://stackoverflow.com/comment/88169696
tagged with: python
linked to: http://stackoverflow.com/q/16888888
duplicate of: http://stackoverflow.com/q/16888888
score: 1
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/50580433
answer count: 1
has comment: http://stackoverflow.com/comment/88169743
downvote count: 1
has title: Parser error that i am stuck with
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/50618236
favorite count: 0
has answer: http://stackoverflow.com/a/60129901
tagged with: python
has body: AWS is not allow to convert existing DynamoDB tables to Global DynamoDB Tables. So I need to write some code or find already existing tool to do it. The existed tables has a lot data, because of it export-import process will take a long time, and downtime it is not an option. I have an approximate plan of action, to do migration: Create global tables Change application logic to start write in global tables. When request come to read data first try global tables, if there is no data - when read normal tables. Copy data from normal tables to global tables. Change application logic again to write and read only from global tables. Remove normal tables. I'm wondering if someone did a similar migration? How do you simplify read from two tables (global and normal)? Is there exists any plugin/lib/wrapper for boto, or pynamodb, or other lib to do this? Or you did migration using other method, please share it.
upvote count: 3
type: UnansweredQuestion
tagged with: amazon-dynamodb
has title: How can I migrate DynamoDB tables to Global DynamoDB tables with minimum downtime?
type: Question
has comment: http://stackoverflow.com/comment/93628953
score: 3
answer count: 1
downvote count: 0
tagged with: amazon-web-services

http://stackoverflow.com/comment/88405739
score: 0
type: Comment
type: QuestionComment
has text: Thanks! I had seen that issue before. The user is using joblib to dump the model and load it, while the file I've is unable to load using joblib. That's why am using the features : x taken from the trained model, and giving it an input. libsvm in python2 works (without using sklearn) but in python3 there's no libsvm package except scikit-learn support.
comment on: http://stackoverflow.com/q/50697579

http://stackoverflow.com/comment/88248337
score: 0
type: Comment
type: QuestionComment
has text: you mean that after loading moldel I use model.build_vocab(sentences,update=True)? and now what are the embedding vectors for missing word?
comment on: http://stackoverflow.com/q/50618993

http://stackoverflow.com/a/50583706
answers question: http://stackoverflow.com/q/50578810
has comment: http://stackoverflow.com/comment/88178492
score: 2
has comment: http://stackoverflow.com/comment/88177118
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88205447
downvote count: 0
has body: By inspecting Network tab in Chrome DevTools you can notice that the products you search are fetched after making a request to https://tennisexpress-com.ecomm-nav.com/search.js. You can see example response here. As you can see, it's a mess, so I wouldn't follow this approach. In your code, you couldn't see the products because the request is made by JavaScript (running in your browser) after the initial page load. Neither standalone urllib nor requests can render that content. However you can do that with Requests-HTML that has JavaScript support (it uses Chromium behind the scenes). Code: from itertools import chain from requests_html import HTMLSession session = HTMLSession() url = 'https://www.tennisexpress.com/search.cfm?searchKeyword=adidas+boost' r = session.get(url) r.html.render() links = list(chain(*[prod.absolute_links for prod in r.html.find('.product')])) I used chain to join all the sets with absolute links together and I created a list out of it. &gt;&gt;&gt; links ['https://www.tennisexpress.com/adidas-mens-barricade-2018-boost-tennis-shoes-black-and-night-metallic-62110', 'https://www.tennisexpress.com/adidas-mens-barricade-2018-boost-tennis-shoes-white-and-matte-silver-62109', ... 'https://www.tennisexpress.com/adidas-mens-supernova-glide-7-running-shoes-black-and-white-41636', 'https://www.tennisexpress.com/adidas-womens-adizero-boston-6-running-shoes-solar-yellow-and-midnight-gray-45268'] Don't forget to install Requests-HTML with pip install requests-html.
has comment: http://stackoverflow.com/comment/88176793
has comment: http://stackoverflow.com/comment/88209709
has comment: http://stackoverflow.com/comment/88209815
has comment: http://stackoverflow.com/comment/88176649
type: Answer
has comment: http://stackoverflow.com/comment/88179490
accepted answer of: http://stackoverflow.com/q/50578810
upvote count: 2

http://stackoverflow.com/comment/88178310
has text: Sorry about the formatting, but it looks like the df2 index is of type u'index'
type: AnswerComment
comment on: http://stackoverflow.com/a/50584450
score: 0
type: Comment

http://stackoverflow.com/q/50610728
type: Question
has comment: http://stackoverflow.com/comment/88231633
has comment: http://stackoverflow.com/comment/88231757
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/88232749
has comment: http://stackoverflow.com/comment/88231709
answer count: 1
has answer: http://stackoverflow.com/a/50612201
has comment: http://stackoverflow.com/comment/88232117
tagged with: sparse-matrix
tagged with: python
has comment: http://stackoverflow.com/comment/88231592
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50612201
has body: I'm trying to convert this code to use scipy sparse matrices as the real matrix is very large, but am having trouble with it. Please can anyone help? import numpy as np G = np.array([[0., 50., 50., 0.], [10., 0., 10., 0.], [0., 0., 0., 10.], [2., 0., 2., 0.]]) s = G.sum(axis=0) m = np.minimum(G, 1).transpose() sm = s * m sm_rnorm = (sm / sm.sum(axis=0)) smm = sm * sm_rnorm G += smm.transpose() print(G) I tried the following: import numpy as np from scipy.sparse import csc_matrix G = np.array([[0.,50.,50.,0.], [10.,0.,10.,0.], [0.,0.,0.,10.], [2.,0.,2.,0.]]) G = csc_matrix(G, dtype=np.float) s = csc_matrix(G.sum(axis=0)) m = csc_matrix.minimum(G, 1).transpose() sm = s * m sm_rnorm = (sm / csc_matrix(sm.sum(axis=0))) smm = sm * sm_rnorm G += smm.transpose() print(G) ...but get ValueError: dimension mismatch
has title: Converting dense matrix code to sparse matrix code
has comment: http://stackoverflow.com/comment/88231404
tagged with: scipy
has comment: http://stackoverflow.com/comment/88231590

http://stackoverflow.com/comment/88384155
comment on: http://stackoverflow.com/q/50686936
score: 0
type: Comment
type: QuestionComment
has text: What do you mean? Where is the definition of your model? Where is the line where you find the error? What is the error and its stack trace?

http://stackoverflow.com/q/50684351
score: -1
tagged with: amazon-web-services
has answer: http://stackoverflow.com/a/50684582
accepted answer: http://stackoverflow.com/a/50684582
has title: Can't make new folder in AWS EC2
answer count: 1
has comment: http://stackoverflow.com/comment/88381722
tagged with: amazon-ec2
favorite count: 0
tagged with: linux
has body: I am trying to make a new folder to SCP my python script so i can run it on AWS EC2 instance. So I have SSH and connected to my instance. I tried ls nothing shows. pwd shows: /home/ec2-user mkdir /newFile shows: mkdir: cannot create directory '/newFile': Permission denied sudo mkdir /newFile shows no error. But when I ls, nothing shows. What is happening? I am using a macbook, and my instance is AWS Linux AMI.
tagged with: python
type: AnsweredQuestion
upvote count: 2
downvote count: 3
type: Question

http://stackoverflow.com/comment/88208647
type: QuestionComment
has text: yes - cx_freeze when I last time used it :) had issues of not including all dependencies like MS redist, etc - so you obviously miss something on the other pc that you have to manually add to package when do installer of your prog
score: 0
comment on: http://stackoverflow.com/q/50599661
type: Comment

http://stackoverflow.com/a/70315382
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/50634986
upvote count: 1
has body: Maybe it's a little late, but this week I've been having a similar problem and managed to solve it. I stopped using lambda layers to fix the problem, instead I created my own layer. You can see how it works in my GitHub or Hugging Face repository. GitHub: https://github.com/FernandoPerezLara/image-preprocessing-layer Hugging Face: https://huggingface.co/fernandoperlar/preprocessing_image I hope it at least solves the problem for some future person. / Fernando

http://stackoverflow.com/a/50649114
type: AcceptedAnswer
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50648558
type: Answer
answers question: http://stackoverflow.com/q/50648558
has body: Use conda install tensorflow instead of pip For installations within anaconda virtual environments its preferable to use conda install package_name or switch back to version &lt;1.6 i.e pip install tensorflow==1.5 Solution reference : GitHub-TensorFlow
score: 2

http://stackoverflow.com/comment/88212954
type: QuestionComment
has text: The `{8}` into `.format()` is causing issues. You could leave it empty and pass the `8` as a second parameter to `format()`. such as: `'$\frac{}{}$'.format(i, 8)`
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50601877

http://stackoverflow.com/q/50550830
has comment: http://stackoverflow.com/comment/88112691
tagged with: python
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50551659
type: Question
has answer: http://stackoverflow.com/a/50551280
has answer: http://stackoverflow.com/a/50551659
has title: Jaspersoft - Python - LXML - CSV - Variable Children Tags
answer count: 2
tagged with: lxml
tagged with: http://stackoverflow.com/tag/csv
downvote count: 0
accepted answer: http://stackoverflow.com/a/50551280
favorite count: 0
has comment: http://stackoverflow.com/comment/88113036
tagged with: http://stackoverflow.com/tag/xml
has body: I am trying to export a user list from a Jaspersoft server into a CSV format as we do not currently have access to the DB or any Administration panel and we would have to raise a support ticket and wait for 2 days each time we would like a list. I figured I will try my luck using REST API and python and with the help of requests module I managed to export the XML that holds this information. The format of the extracted XML is this. Sample XML: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> doejoe@email.com true John Doe doejoe false MANAGER Beatings will continue until morale improves false DIRECTOR kathysmith@email.com true Kathy Smith kathysmith false false USER User Description false SUPER_MANAGER Super Manager description. false SUPER_DIRECTOR My code until now: import lxml.etree as ET import csv # load file tree = ET.parse('Format.xml') # iterate through each user tag users = tree.findall('.//user') with open('user_list.csv', "wb") as csv_file: writer = csv.writer(csv_file, delimiter=',') for user in users: email = user.find('emailAddress').text enabled = user.find('enabled').text externallyDefined = user.find('externallyDefined').text fullName = user.find('fullName').text tenantId = user.find('tenantId').text username = user.find('username').text writer.writerow(email + ',' + enabled + ',' + externallyDefined + ',' + fullName + ',' + tenantId + ',' + username) As you can tell - I am not a programmer or even close enough to that, so apologies should your eyes bleed - started learning python 3 weeks ago. My code is not working for several reasons: Each user can have from 1 to X amount of Roles so all the examples I managed to find have a standard amount of children. Some user attributes might be missing so I get an error when not found. Some attributes are repeating themselves e.g. ExternallyDefined in both user and role! My loops export each letter to a separate cell but that is something I believe I can solve. My end goal would be something like this:…
upvote count: 2

http://stackoverflow.com/comment/88120079
type: Comment
type: QuestionComment
has text: The code you posted is far from complete; the `data` and `strategy` packages are not publicly available libraries, but are imported in this script. Those modules are part of this profiling session, and could be loading large amounts of data on import.
comment on: http://stackoverflow.com/q/50554374
score: 0

http://stackoverflow.com/a/50598254
upvote count: 1
has comment: http://stackoverflow.com/comment/88211944
has body: you are looking for the max and argmax of the output: corr=scipy.correlate2d(A,B) maxCorr=corr.max() indexmaxCorr=np.argmax(corr) this is due because correlate is basically a convolution and then you have similarity value for different "shifting".
score: 1
answers question: http://stackoverflow.com/q/50597925
has comment: http://stackoverflow.com/comment/88230368
downvote count: 0
has comment: http://stackoverflow.com/comment/88231874
has comment: http://stackoverflow.com/comment/88228226
has comment: http://stackoverflow.com/comment/88231616
type: Answer
has comment: http://stackoverflow.com/comment/88211736

http://stackoverflow.com/comment/88178149
comment on: http://stackoverflow.com/q/50584218
type: Comment
type: QuestionComment
has text: The clearest thing to do in this case is to avoid map and use a list comprehension.
score: 0

http://stackoverflow.com/comment/88181286
comment on: http://stackoverflow.com/q/50585246
type: QuestionComment
has text: Thanks a lot. That made me realize that I gave a different package name to the `setup.py` than the name of the directory.
score: 1
type: Comment

http://stackoverflow.com/q/50635368
has body: I am trying to rephrase the implementation found here. This is what I have so far: import csv import math import random training_set_ratio = 0.67 training_set = [] test_set = [] class IrisFlower: def __init__(self, petal_length, petal_width, sepal_length, sepal_width, flower_type): self.petal_length = petal_length self.petal_width = petal_width self.sepal_length = sepal_length self.sepal_width = sepal_width self.flower_type = flower_type def __hash__(self) -&gt; int: return hash((self.petal_length, self.petal_width, self.sepal_length, self.sepal_width)) def __eq__(self, other): return (self.petal_length, self.petal_width, self.sepal_length, self.sepal_width) \ == (other.petal_length, other.petal_width, other.sepal_length, other.sepal_width) def load_data(): with open('dataset.csv') as csvfile: rows = csv.reader(csvfile, delimiter=',') for row in rows: iris_flower = IrisFlower(float(row[0]), float(row[1]), float(row[2]), float(row[3]), row[4]) if random.random() &lt; training_set_ratio: training_set.append(iris_flower) else: test_set.append(iris_flower) def euclidean_distance(flower_one: IrisFlower, flower_two: IrisFlower): distance = 0.0 distance = distance + math.pow(flower_one.petal_length - flower_two.petal_length, 2) distance = distance + math.pow(flower_one.petal_width - flower_two.petal_width, 2) distance = distance + math.pow(flower_one.sepal_length - flower_two.sepal_length, 2) distance = distance + math.pow(flower_one.sepal_width - flower_two.sepal_width, 2) return distance def get_neighbors(test_flower: IrisFlower): distances = [] for training_flower in training_set: dist = euclidean_distance(test_flower, training_flower) d = dict() d[training_flower] = dist print(d) return load_data() get_neighbors(test_set[0]) Currently, print statements in the following code block: def get_neighbors(test_flower: IrisFlower): distances = [] for training_flower in training_set: dist = euclidean_distance(test_flower, training_flower) d = dict() d[training_flower] = dist pr…
has answer: http://stackoverflow.com/a/50635488
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50635468
possible better answer: http://stackoverflow.com/a/50635488
has answer: http://stackoverflow.com/a/50635400
answer count: 3
tagged with: python-3.5
downvote count: 0
accepted answer: http://stackoverflow.com/a/50635400
type: Question
type: AnsweredQuestion
has title: How can I initialize dictionary in Python where key is an object?
score: 1
favorite count: 0

http://stackoverflow.com/q/50569689
has comment: http://stackoverflow.com/comment/88149326
has body: I want to know why this code doesn't work properly: it should break when the input not 1 ,2 or 3 while True: try: aw = int(input('Number : ')) if aw in [1,2,3] == False: print('give Number agian') else: print('correct') break except ValueError: print('please give a number')
type: UnansweredQuestion
tagged with: python
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/88149255
score: 0
linked to: http://stackoverflow.com/q/9284350
has comment: http://stackoverflow.com/comment/88149231
has comment: http://stackoverflow.com/comment/88149313
duplicate of: http://stackoverflow.com/q/9284350
has title: Error with if statment
tagged with: python-3.x

http://stackoverflow.com/q/50685218
has comment: http://stackoverflow.com/comment/88383210
has title: venv vs virtualenv - Why does venv not use the current pip and setuptools?
tagged with: python
favorite count: 0
score: 8
has answer: http://stackoverflow.com/a/56821159
type: UnansweredQuestion
tagged with: pip
linked to: http://stackoverflow.com/q/29689514
has comment: http://stackoverflow.com/comment/88380225
duplicate of: http://stackoverflow.com/q/29689514
tagged with: ubuntu-16.04
has comment: http://stackoverflow.com/comment/88380303
type: Question
tagged with: python-venv
has comment: http://stackoverflow.com/comment/88384026
answer count: 1
downvote count: 0
tagged with: virtualenv
has body: When using python -m venv env to create a new virtual environment in python3.X, env does not contain the pip and setuptools versions I would expect. Instead, it contains quite "old" versions: pip (8.1.1) and setuptools (20.7.0) as of June 2018. On the other hand, when using virtualenv env (installed via pip install virtualenv), the pip and setuptools packages are the latest available, i.e. pip (10.0.1) and setuptools (39.2.0) as of June 2018. The way I understood it, venv is the preferred module to build virtual environments because it does not need to create a new instance of the Python interpreter and uses the present modules (symlinks in Linux, copies in Windows) without needing to install anything ( https://www.reddit.com/r/learnpython/comments/4hsudz/pyvenv_vs_virtualenv/d2s2cda ). How come that venv's pip version doesn't match the current system's one? And that the behaviour using virtualenv is so different? PS: A short term solution is to use pip install --upgrade pip in the env. But that doesn't seem right to me. Minimum viable solution: $ python --version Python 3.6.5 $ pip --version pip 10.0.1 from /home/lionel/.local/lib/python3.6/site-packages/pip (python 3.6) $ python -m venv env $ . env/bin/activate (env) $ # Here I am at version 8.1.1 of pip. Why did venv create its own pip, (env) $ # instead of linking to the system one? As seen before, that was 10.0.1. (env) $ pip install --upgrade pip Collecting pip Using cached https://files.pythonhosted.org/packages/0f/74/ecd13431bcc456ed390b44c8a6e917c1820365cbebcb6a8974d1cd045ab4/pip-10.0.1-py2.py3-none-any.whl Installing collected packages: pip Found existing installation: pip 8.1.1 Uninstalling pip-8.1.1: Successfully uninstalled pip-8.1.1 Successfully installed pip-10.0.1 (env) $ pip list Package Version ------------- ------- pip 10.0.1 pkg-resources 0.0.0 setuptools 20.7.0 (env) $ # Solved, now pip is the one I was expecting!
has comment: http://stackoverflow.com/comment/88385599
upvote count: 8

http://stackoverflow.com/a/59241368
answers question: http://stackoverflow.com/q/50689359
downvote count: 0
has body: A simple approach is to add another field that is used only for sorting: class Item(models.Model): signature = models.CharField('Signatur', max_length=50) sort_string = models.CharField(max_length=60, blank=True, editable=False) class Meta: ordering = ['sort_string'] def save(self, *args, **kwargs): parts = self.signature.split() parts[2] = "{:06d}".format(int(parts[2])) self.sort_string = "".join(parts) super().save(*args, **kwargs) Depending on how often your data is updated vs read, this is probably very efficient. sort_string is calculated once whenever an Item is updated, but then it is available as a simple field whenever it is needed. It is simple to adjust the way sort_string is calculated to meet your exact requirements. It may also be useful (particularly during development) to add a re-save action to your admin: def re_save(modeladmin, request, queryset): for item in queryset: item.save() re_save.short_description = "Re-save" class ItemAdmin(admin.ModelAdmin): actions = [re_save, ] .... so it is easy to trigger re-calculation.
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/comment/88393957
comment on: http://stackoverflow.com/q/50691808
has text: *Right now, the "Not a Valid Price" part is being updated into the dictionary.* What does this mean? The code you posted doesn't do anything like this. Are you capturing the standard output (which of course includes anything you `print()`) into a file perhaps?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50563162
tagged with: python
has comment: http://stackoverflow.com/comment/88173702
has title: How to set a point on image in python?
score: 2
tagged with: tkinter
upvote count: 2
tagged with: coordinates
type: Question
has answer: http://stackoverflow.com/a/50617236
tagged with: image
has comment: http://stackoverflow.com/comment/88138433
answer count: 1
downvote count: 0
has body: How to set a point on the image and save its coordinates in the database? For example, I open the image, click on any place and there is a red dot. And on the left is written its position on the coordinates X Y? I have a code which make it, but without point on the image. from Tkinter import * from tkFileDialog import askopenfilename import Image, ImageTk if __name__ == "__main__": root = Tk() #setting up a tkinter canvas with scrollbars frame = Frame(root, bd=2, relief=SUNKEN) frame.grid_rowconfigure(0, weight=1) frame.grid_columnconfigure(0, weight=1) xscroll = Scrollbar(frame, orient=HORIZONTAL) xscroll.grid(row=1, column=0, sticky=E+W) yscroll = Scrollbar(frame) yscroll.grid(row=0, column=1, sticky=N+S) canvas = Canvas(frame, bd=0, xscrollcommand=xscroll.set, yscrollcommand=yscroll.set) canvas.grid(row=0, column=0, sticky=N+S+E+W) xscroll.config(command=canvas.xview) yscroll.config(command=canvas.yview) frame.pack(fill=BOTH,expand=1) #adding the image File = askopenfilename(parent=root, initialdir="C:/",title='Choose an image.') img = ImageTk.PhotoImage(Image.open(File)) canvas.create_image(0,0,image=img,anchor="nw") canvas.config(scrollregion=canvas.bbox(ALL)) #function to be called when mouse is clicked def printcoords(event): #outputting x and y coords to console print (event.x,event.y) #mouseclick event canvas.bind("&lt;Button 1&gt;",printcoords) root.mainloop()
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88145389
type: UnansweredQuestion

http://stackoverflow.com/comment/88241476
comment on: http://stackoverflow.com/q/50615788
has text: So your input is this HTML, and the output must be a single valued result?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50662760
type: AcceptedAnswer
downvote count: 0
score: 7
type: Answer
has body: If you are going to set the environment variable NLS_LANG you must do it before you create any connection; otherwise, it will have no effect. Better yet, however, is to use the following to create the connection as this does not depend on environment variables: connection = cx_Oracle.connect("user/password@connectString", encoding="UTF-8", nencoding="UTF-8")
has comment: http://stackoverflow.com/comment/105781630
upvote count: 7
answers question: http://stackoverflow.com/q/50638492
accepted answer of: http://stackoverflow.com/q/50638492

http://stackoverflow.com/q/50654624
has comment: http://stackoverflow.com/comment/88319447
has comment: http://stackoverflow.com/comment/88319480
score: 0
answer count: 2
tagged with: http://stackoverflow.com/tag/csv
has title: Python convert large(10GB) .csv to .tsv
has answer: http://stackoverflow.com/a/50654672
favorite count: 0
type: UnansweredQuestion
has body: New to python. Want to convert the large csv file to tsv. import re with open("D:/AddressEvaluation/NAD/NAD.csv", 'r') as myfile: with open("D:/NAD.txt", 'w') as csv_file: for line in myfile: fileContent = re.sub(",", "\t", line) csv_file.write(fileContent) Am I missing something? Correct me If I am wrong.
has comment: http://stackoverflow.com/comment/88319680
has answer: http://stackoverflow.com/a/50654838
tagged with: python
upvote count: 3
downvote count: 3
tagged with: file
type: Question

http://stackoverflow.com/q/50633961
tagged with: python
linked to: http://stackoverflow.com/q/1675766
tagged with: parallel-processing
downvote count: 0
accepted answer: http://stackoverflow.com/a/50634104
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50634104
type: Question
tagged with: python-multiprocessing
has comment: http://stackoverflow.com/comment/88278136
upvote count: 1
answer count: 1
has body: Consider the following toy example. I am making a parallelization to compute the value of square function while making some modifications of the shared object A. import multiprocessing A = [1, 2] def square(i): A[i] = 2 + A[i] return i * i square(0) square(1) print(A) A = [1, 2] multiprocessing.Pool().map(square, [0, 1]) print(A) The output is the following [3, 4] [1, 2] But I expect it to be [3, 4] [3, 4] As indicated above, the serial version of square function managed to change A from [1, 2] to [3, 4]. But the pool.map failed to modify A. So I am asking how to modify the shared object using pool().map. Thanks in advance!
has title: Pool().map: modify the shared object
favorite count: 0

http://stackoverflow.com/comment/88412272
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50684687
has text: @Rodrigo de Azevedo No in fact I want to maximize the summation of this vector elements. Max( sigma (bi)) –

http://stackoverflow.com/comment/88242380
has text: I actually follow the way when we build this utility in in own package.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50615566

http://stackoverflow.com/q/50675434
tagged with: network-programming
has comment: http://stackoverflow.com/comment/88360934
has body: My application has an issue where if it loses its connection, it blocks forever and the whole application needs to be restarted. Code in question: def run(encoder, port, channel): decoder_socket = socket.socket() decoder_socket.connect((decoder, port)) decoder_fp = decoder_socket.makefile("r", 0) parser = xml.sax.make_parser(['xml.sax.IncrementalParser']) parser.setContentHandler(RftDecoder()) while True: data = decoder_fp.readline().strip("\x00") if not(data): raise socket.error("no data") LOG.info("%s" % data.strip()) parser.feed(data) If the connection is actively closed by the other side, the exception is raised as expected, no problems. However when the connection is dropped (e.g., if Decoder crashes, or if the cable is unplugged), then the decoder_fp.readline() call blocks indefinitely. Strace doesn't show anything when this happens, it just continues sitting on a recv() call. So my question is, how can I detect when the connection is lost as described, and reconnect?
type: UnansweredQuestion
has title: How can I detect when my socket has lost its TCP connection and reconnect?
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/88360852
score: 2
has comment: http://stackoverflow.com/comment/88468831
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/88435935
has comment: http://stackoverflow.com/comment/88380950
favorite count: 0
has comment: http://stackoverflow.com/comment/88397278
type: Question
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/88360741
has comment: http://stackoverflow.com/comment/88431708
has comment: http://stackoverflow.com/comment/88397821
upvote count: 2
has comment: http://stackoverflow.com/comment/88360916

http://stackoverflow.com/a/50563422
answers question: http://stackoverflow.com/q/50563042
accepted answer of: http://stackoverflow.com/q/50563042
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: For ordering you can use count related_name in product queryset, to get only first two elements use slicing [:2]: obj = Product.objects.order_by('-count__count')[:2] serializer = ProductSerializer(instance=obj, many=True, context={'request': request}) return Response(serializer.data)
score: 2
upvote count: 2

http://stackoverflow.com/q/50569205
tagged with: python
score: 11
upvote count: 11
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50569494
type: Question
linked to: http://stackoverflow.com/q/48956286
possible better answer: http://stackoverflow.com/a/54312441
tagged with: flask
has answer: http://stackoverflow.com/a/54312441
has body: I seem to be having this issue with Pandas code inside a Bokeh callback. Here's part of the output before the error. My dataframe seems normal and I'm not sure why it's upset time temperature 0 2016-03-17 11:00:00 4.676 1 2016-03-17 11:30:00 4.633 2 2016-03-17 12:00:00 4.639 3 2016-03-17 12:30:00 4.603 4 2016-03-17 13:00:00 4.615 5 2016-03-17 13:30:00 4.650 6 2016-03-17 14:00:00 4.678 7 2016-03-17 14:30:00 4.698 8 2016-03-17 15:00:00 4.753 9 2016-03-17 15:30:00 4.847 ERROR:bokeh.server.protocol_handler:error handling message Message 'PATCH-DOC' ( revision 1): ValueError('window must be an integer',) And here's the code I changed from the flask embed example (link here): def callback(attr, old, new): df = pd.DataFrame.from_dict(source.data.copy()) print df[:10] if new == 0: data = df else: data = df.rolling('{0}D'.format(new)).mean() source.data = ColumnDataSource(data=data).data slider = Slider(start=0, end=30, value=0, step=1, title="Smoothing by N Days") slider.on_change('value', callback) I can also include the full code if that help, but the main change I have is just a doc.add_periodic_callback() that fetches new data periodically.
tagged with: python-2.7
answer count: 3
downvote count: 0
has title: Python, Pandas ; ValueError('window must be an integer',)
favorite count: 0
has answer: http://stackoverflow.com/a/50569494
has answer: http://stackoverflow.com/a/59003392

http://stackoverflow.com/comment/88221367
comment on: http://stackoverflow.com/a/50594837
type: AnswerComment
score: 0
type: Comment
has text: These values get changed when I export dataframe to csv. I have same values for most columns. They are not unique

http://stackoverflow.com/a/50692350
downvote count: 1
score: -1
upvote count: 0
type: Answer
has body: Close the file that you are trying to read and write and then try running your script. Hope it helps
answers question: http://stackoverflow.com/q/50692295
has comment: http://stackoverflow.com/comment/88394215

http://stackoverflow.com/comment/125107158
type: Comment
comment on: http://stackoverflow.com/a/56673095
has text: clearly the easiest way to go
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88400909
has text: How should I define my class_weights? More weights go with lower data?
comment on: http://stackoverflow.com/a/50694965
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50690068
favorite count: 0
type: Question
answer count: 1
has title: Stopping tornado from thread
upvote count: 3
tagged with: tornado
has comment: http://stackoverflow.com/comment/88400640
has answer: http://stackoverflow.com/a/57688560
downvote count: 0
type: UnansweredQuestion
has body: I'm running tornado, and monitoring various data sources etc from a separate thread. It's important in this instance to close the web server if the user closes the browser. I'm simply relying on heartbeat requests from the browser, and then want to stop the tornado ioloop. This is proving very difficult: # Start the main processing loop mLoop = threading.Thread(target = mainLoop, args=()) mLoop.start() # Set up webserver parser = argparse.ArgumentParser(description="Starts a webserver.") parser.add_argument("--port", type=int, default=8000, help="The port") args = parser.parse_args() handlers = [(r"/", IndexHandler), (r"/websocket", WebSocket), (r'/static/(.*)', tornado.web.StaticFileHandler, {'path': os.path.normpath(os.path.dirname(__file__))})] application = tornado.web.Application(handlers) application.listen(args.port) webbrowser.open("http://localhost:%d/" % args.port, new=2) tornado.ioloop.IOLoop.instance().start() The main loop needs to, in certain conditions, stop tornado, but it can't access the ioloop to call IOLoop.stop() (or probably better IOLoop.instance.stop()) because it's not the thread which started it. What's the best way to accomplish this?
score: 3
tagged with: python

http://stackoverflow.com/a/50636123
score: 1
has body: # Creating a data frame with 4 variables and 400 observations np.random.seed(42) randomdata = pd.DataFrame(np.random.randn(400, 4)) randomdata.head() 0 1 2 3 0 0.496714 -0.138264 0.647689 1.523030 1 -0.234153 -0.234137 1.579213 0.767435 2 -0.469474 0.542560 -0.463418 -0.465730 3 0.241962 -1.913280 -1.724918 -0.562288 4 -1.012831 0.314247 -0.908024 -1.412304 # Cap and floor for one variable randomdata[0].clip(lower=-0.5, upper=0.5) # Cap and floor entire dataframe clean_df = randomdata.clip(lower=-0.5, upper=0.5) clean_df.head() 0 1 2 3 0 0.496714 -0.138264 0.500000 0.50000 1 -0.234153 -0.234137 0.500000 0.50000 2 -0.469474 0.500000 -0.463418 -0.46573 3 0.241962 -0.500000 -0.500000 -0.50000 4 -0.500000 0.314247 -0.500000 -0.50000
has comment: http://stackoverflow.com/comment/88305697
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/50635540
downvote count: 0

http://stackoverflow.com/comment/88182272
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50585211
has text: Why do you think you *cannot* access index labels with the result from `s["A"].apply(lambda x: set([x]))`?
score: 0

http://stackoverflow.com/comment/136273718
comment on: http://stackoverflow.com/a/64558207
type: Comment
score: 0
type: AnswerComment
has text: Great solution! I was wondering how I could automate this process!

http://stackoverflow.com/a/50642746
answers question: http://stackoverflow.com/q/50641374
score: 0
has body: Create a input-placeholder and use this as the input to both networks: Eg DNN1: hidden1 = (input * W1) + b1 DNN2: hidden1 = (input * W1) + b1 Can you do this?
type: Answer
has comment: http://stackoverflow.com/comment/88298753
has comment: http://stackoverflow.com/comment/88296137
has comment: http://stackoverflow.com/comment/88296286

http://stackoverflow.com/q/50695888
type: Question
has comment: http://stackoverflow.com/comment/88403038
linked to: http://stackoverflow.com/q/50476501
tagged with: matplotlib
score: 0
has comment: http://stackoverflow.com/comment/88401910
tagged with: seaborn
type: UnansweredQuestion
tagged with: python
has title: Matplotlib not found
answer count: 0
has body: I have been trying to workout a matplotlib package. Even though it is installed and is show in conda list. I cannot import it in jupyter notebook Can't figure out any solution. Have already tried reinstalling the packages a couple of times

http://stackoverflow.com/comment/88170360
type: AnswerComment
type: Comment
has text: Meh. By the way, I don't think this is a duplicate.
comment on: http://stackoverflow.com/a/50580272
score: 0

http://stackoverflow.com/comment/88370666
type: Comment
type: QuestionComment
has text: 1.11.4 is a minor release - it's really unlikely that the upgrade from 1.11.1 is causing the problem, especially when the messages framework has been stable for years. Your links to google drive don't work, but you should really include the relevant code in your question instead of linking to another site. Please show the views that you redirect to, and how you display the messages in those templates.
score: 0
comment on: http://stackoverflow.com/q/50679343

http://stackoverflow.com/comment/88377287
score: 1
type: QuestionComment
has text: @Chris_Rands Okay: so then basically I would have to write some rule stating that: if the first and second letter are capitals already, skip `.capitalize()` ?
type: Comment
comment on: http://stackoverflow.com/q/50683716

http://stackoverflow.com/comment/88167685
comment on: http://stackoverflow.com/q/50578948
score: 0
type: Comment
type: QuestionComment
has text: @coldspeed I have tried that as well, I get `ValueError: malformed string`

http://stackoverflow.com/q/50591662
upvote count: 1
type: Question
tagged with: django-models
has title: Changing mySQL Query to Django
accepted answer: http://stackoverflow.com/a/50591707
downvote count: 0
answer count: 1
has body: I am having difficulties changing the following MySQL Query to a Django Query SELECT * FROM dashboard_db.dashboard_system ds JOIN dashboard_db.dashboard_userpreference up ON ds.id = up.system_id WHERE username = "&lt;user&gt;" Here are the models in my Django application class System(models.Model): system_name = models.CharField(max_length = 40) LOCATION = (('0', 'Inernal'),('1','External')) location = models.CharField(max_length=1, choices=LOCATION) def __str__(self): return self.system_name class UserPreference(models.Model): username = models.CharField(max_length = 40) system = models.ForeignKey(System, on_delete = models.CASCADE) def __str__(self): return self.username I have been trying to use unions and a few other options. I am aware that Performing a raw SQL query is an option. However I was wondering if it is possible to perform the join using a Django styled query.
favorite count: 0
has comment: http://stackoverflow.com/comment/88192704
has answer: http://stackoverflow.com/a/50591707
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/88192677
tagged with: mysql

http://stackoverflow.com/comment/88182154
type: QuestionComment
comment on: http://stackoverflow.com/q/50585211
has text: When you use apply on a dataframe it applies to each column. Hence, you have the double output you see in your first attempt.
score: 0
type: Comment

http://stackoverflow.com/comment/88145487
comment on: http://stackoverflow.com/a/50567628
has text: OP wants to create a string, not evaluate the expression.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50630090
has comment: http://stackoverflow.com/comment/88290080
type: Answer
has body: How about this then: from django.views.generic import ListView from django.urls import reverse class DemoView2(ListView): model = MandateTable template_name = 'demo2.html' context_object_name = 'pg' paginate_by = 1 queryset = MandateTable.objects.all()[:5] #For Testing purspose, working on only 5 objects def post(self, request, *args, **kwargs): if 'accept' in request.POST: # do acceptable stuff pass elif 'reject' in request.POST: # do rejectable stuff pass return super().get(request, *args, **kwargs) def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) page_obj = context['page_obj'] if page_obj.has_next(): context['next'] = "?page=" + str(page_obj.next_page_number()) else: context['next'] = reverse('demo') return context &lt;!--demo2.html--&gt; &lt;form method='post'&gt; {% csrf_token %} {% for mandates in pg %} &lt;p&gt;{{ mandates.FIELD_1 }}&lt;/p&gt; &lt;p&gt;{{ mandates.FIELD_2 }}&lt;/p&gt; &lt;p&gt;{{ mandates.FELD_3 }}&lt;/p&gt; &lt;p&gt;{{ mandates.FIELD_4 }}&lt;/p&gt; &lt;p&gt;{{ mandates.FIELD_5 }}&lt;/p&gt; {% endfor %} {% if is_paginated %} &lt;ul class="pagination"&gt; {% if page_obj.has_previous %} &lt;li&gt;&lt;a href="?page={{ page_obj.previous_page_number }}"&gt;&amp;laquo;&lt;/a&gt;&lt;/li&gt; {% else %} &lt;li class="disabled"&gt;&lt;span&gt;&amp;laquo;&lt;/span&gt;&lt;/li&gt; {% endif %} &lt;button name='accept' class="btn btn-danger btn-lg" type="submit" formaction={{ next }}&gt;Accept&lt;/button&gt; &lt;button name='reject' class="btn btn-danger btn-lg" type="submit" formaction={{ next }}&gt;Reject&lt;/button&gt; &lt;/ul&gt; {% endif %} &lt;/form&gt; You would still need to somehow include the objects shown on that page into request.POST so you can do work on them (maybe by using hidden inputs). Never worked with pagination before.
score: 0
has comment: http://stackoverflow.com/comment/88295580
answers question: http://stackoverflow.com/q/50623606

http://stackoverflow.com/q/50569618
downvote count: 0
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/50569711
accepted answer: http://stackoverflow.com/a/50569964
has answer: http://stackoverflow.com/a/75850038
answer count: 3
has body: I've tried some code but I was not successful to send a file message with my bot. After upload my file I'm not able to get file_id and access_hash and other from the server to send it. It's my code: @dispatcher.message_handler(PhotoFilter()) def ask_photo(bot, update): user_peer = update.get_effective_user() bot.upload_file(file="../files/upload_file_test.jpeg", file_type="file", success_callback=file_upload_success,failure_callback=failure) def file_upload_success(response): photo_message = PhotoMessage(file_id=response.file_id, access_hash=response.access_hash, name="photo", file_size="100", mime_type="image/jpeg", thumb=response.thumb, width=80, height=80, caption_text="caption") bot.send_message(photo_message, user_peer) It doesn't work! :( any help?
favorite count: 0
has answer: http://stackoverflow.com/a/50569964
tagged with: bale-messenger
possible better answer: http://stackoverflow.com/a/50569711
tagged with: python
has title: how to send a local file in bale bot to a client?
score: 2
type: AnsweredQuestion
tagged with: bots

http://stackoverflow.com/q/50560182
has body: import re string = re.sub(r'-\n', '', string) I want to tokenize words of a text. The problem is, that all words, which are at the end of a line, are tokenized wrong. So i have to remove the hyphen before a new line character. Thanks for your help!
score: 1
type: Question
has title: Match hyphen in combination with new line character
tagged with: nltk
downvote count: 0
accepted answer: http://stackoverflow.com/a/50560228
answer count: 1
favorite count: 0
upvote count: 1
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/50560228
type: AnsweredQuestion
tagged with: tokenize

http://stackoverflow.com/comment/88155821
comment on: http://stackoverflow.com/q/50572962
score: 0
type: Comment
has text: The existing network has a 90 node softmax head. There is no merit to removing other nodes. Just get your detections and throw away classes that you don't want. If you do feel the need to remove other classes from the network itself, then you have to modify `pipeline.config` file and change `NUM_CLASSES: 1` and retrain the network aka fine-tune it.
type: QuestionComment

http://stackoverflow.com/comment/88393991
has text: Thanks got it working from your first suggestion! First post on stack overflow and its solved in 5 minutes :)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50692167

http://stackoverflow.com/comment/88277856
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50633792
type: QuestionComment
has text: I added the error. Sorry about that.

http://stackoverflow.com/q/50689401
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/50690367
has title: Custom operations on network weights while computing
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/47585864
has answer: http://stackoverflow.com/a/50691617
possible better answer: http://stackoverflow.com/a/50690367
tagged with: tensorflow
type: Question
answer count: 2
downvote count: 0
tagged with: neural-network
has body: I am using TensorFlow and Python to create custom neural network. I need to make changes on weights and biases before each input data is passed. The architecture of network is common (sequential, supervised, with backpropagation) and the only difference is that before each pass I need to make some calculations. So for example I have some inputs (x) and before I pass them throught the network and calculate network results (y), in each pass I need to run a function to change the weights. My question is how would be possible to do that and after I calculate new weights and biases, that the network calculates everything else (whole network calculation, loss, and optimization functions) further normally? If it is possible how could I reach weights and then create that additional custom step?
accepted answer: http://stackoverflow.com/a/50691617
favorite count: 0

list
type: Tag
tags question: http://stackoverflow.com/q/50647260
tags question: http://stackoverflow.com/q/50611571
tags question: http://stackoverflow.com/q/50655189
tags question: http://stackoverflow.com/q/50637446
tags question: http://stackoverflow.com/q/50577241
tags question: http://stackoverflow.com/q/50554405
tags question: http://stackoverflow.com/q/50664026
tags question: http://stackoverflow.com/q/50631323
tags question: http://stackoverflow.com/q/50689079
tags question: http://stackoverflow.com/q/50662071
tags question: http://stackoverflow.com/q/50658713
tags question: http://stackoverflow.com/q/50639390
tags question: http://stackoverflow.com/q/50623709
tags question: http://stackoverflow.com/q/50662620
tags question: http://stackoverflow.com/q/50594166
tags question: http://stackoverflow.com/q/50543932
tags question: http://stackoverflow.com/q/50622804
tags question: http://stackoverflow.com/q/50671627
tags question: http://stackoverflow.com/q/50590106
tags question: http://stackoverflow.com/q/50651691
tags question: http://stackoverflow.com/q/50685813
tags question: http://stackoverflow.com/q/50574244
tags question: http://stackoverflow.com/q/50693145
tags question: http://stackoverflow.com/q/50674866
tags question: http://stackoverflow.com/q/50565860
tags question: http://stackoverflow.com/q/50650250
tags question: http://stackoverflow.com/q/50556875
tags question: http://stackoverflow.com/q/50695766
tags question: http://stackoverflow.com/q/50635116
tags question: http://stackoverflow.com/q/50619573
tags question: http://stackoverflow.com/q/50640730
tags question: http://stackoverflow.com/q/50658809
tag name: list
tags question: http://stackoverflow.com/q/50542213
tags question: http://stackoverflow.com/q/50606828
tags question: http://stackoverflow.com/q/50615169
tags question: http://stackoverflow.com/q/50628617
tags question: http://stackoverflow.com/q/50574717
tags question: http://stackoverflow.com/q/50618639
tags question: http://stackoverflow.com/q/50656393
tags question: http://stackoverflow.com/q/50553485
tags question: http://stackoverflow.com/q/50598383
tags question: http://stackoverflow.com/q/50680788
tags question: http://stackoverflow.com/q/50615293
tags question: http://stackoverflow.com/q/50552360
tags question: http://stackoverflow.com/q/50628422
tags question: http://stackoverflow.com/q/50563064
tags question: http://stackoverflow.com/q/50616439
tags question: http://stackoverflow.com/q/50615482
tags question: http://stackoverflow.com/q/50621438
tags question: http://stackoverflow.com/q/50545103
tags question: http://stackoverflow.com/q/50563646
tags question: http://stackoverflow.com/q/50676725
tags question: http://stackoverflow.com/q/50545324
tags question: http://stackoverflow.com/q/50667212
tags question: http://stackoverflow.com/q/50618761
tags question: http://stackoverflow.com/q/50546540
tags question: http://stackoverflow.com/q/50562428
tags question: http://stackoverflow.com/q/50566982
tags question: http://stackoverflow.com/q/50582759
tags question: http://stackoverflow.com/q/50615191
tags question: http://stackoverflow.com/q/50567789
tags question: http://stackoverflow.com/q/50542610
tags question: http://stackoverflow.com/q/50559986
tags question: http://stackoverflow.com/q/50564348
tags question: http://stackoverflow.com/q/50671360
tags question: http://stackoverflow.com/q/50669785
tags question: http://stackoverflow.com/q/50653133
tags question: http://stackoverflow.com/q/50665271
tags question: http://stackoverflow.com/q/50661733
tags question: http://stackoverflow.com/q/50656257
tags question: http://stackoverflow.com/q/50660521
tags question: http://stackoverflow.com/q/50593062
tags question: http://stackoverflow.com/q/50604402
tags question: http://stackoverflow.com/q/50656958
tags question: http://stackoverflow.com/q/50555842
tags question: http://stackoverflow.com/q/50689146
tags question: http://stackoverflow.com/q/50656414
tags question: http://stackoverflow.com/q/50672570

http://stackoverflow.com/comment/88136421
type: QuestionComment
score: 2
has text: Also, just feed your algorithm the same histogram in reverse: `[2, 5, 8, 6, 8, 1, 2, 4]`. Your code gives a result of 25. FWIW, you can find various solutions [here](https://stackoverflow.com/q/4311694/4014959).
comment on: http://stackoverflow.com/q/50560882
type: Comment

http://stackoverflow.com/comment/88680053
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50659377
type: Comment
has text: The usefulness of this approach is building an end-to-end model which you can feed the original inputs to your autoencoders. This means composing both full autoencoder models with the dense layers. This also allows you to intelligently retrain the autoencoder weights with respect to the MLP objective if you want to. The alternative approach you mention is along the lines of Daniel's first approach.

http://stackoverflow.com/a/72537332
answers question: http://stackoverflow.com/q/50556216
type: Answer
score: 0
has body: def qt_object_properties(qt_object: object) -&gt; dict: &quot;&quot;&quot; Create a dictionary of property names and values from a QObject. :param qt_object: The QObject to retrieve properties from. :type qt_object: object :return: Dictionary with format {'name': property_name, 'value': property_value} :rtype: dict &quot;&quot;&quot; properties: list = [] # Returns a list of QByteArray. button_properties: list = qt_object.dynamicPropertyNames() for prop in button_properties: # Decode the QByteArray into a string. name: str = str(prop, 'utf-8') # Get the property value from the button. value: str = qt_object.property(name) properties.append({'name': name, 'value': value}) return properties btn: object = QPushButton('My Button', self) # Add properties to the button widget. These can be generated in a loop if necessary. btn.setProperty('property1', True) btn.setProperty('property2', False) print(qt_object_properties(btn)) Output: &gt;&gt; [{'name': 'property1', 'value': True}, {'name': 'property2', 'value': False}]

http://stackoverflow.com/comment/88383641
comment on: http://stackoverflow.com/q/50686700
type: QuestionComment
has text: None of the duplicated answers are helping because there is no perfect solution to this problem. If you find an ideal solution to your question here, it will also solve the switch question, and vice versa.
type: Comment
score: 1

http://stackoverflow.com/q/50585076
upvote count: 3
type: UnansweredQuestion
score: 3
type: Question
has title: No library stub file for module lxml.html in python
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/69386250
favorite count: 0
has answer: http://stackoverflow.com/a/52554942
tagged with: python
has body: Upon adding this line import lxml.html vim displays No library stub file for module lxml.html. What does it mean?
has answer: http://stackoverflow.com/a/76139466

http://stackoverflow.com/a/50691750
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50691154
type: Answer
upvote count: 1
has body: This is the way I solved it. I used the removegarbage function I found here to replace all non-alphanumeric characters. def removegarbage(str): # Replace one or more non-word (non-alphanumeric) chars with a space str = re.sub(r'\W+', ' ', str) str = str.lower() return str doc = removegarbage(doc.decode('raw_unicode_escape')) If you open the txt file in a basic text editor (like, notepad), you would still see those illegible characters. But if you open it in the console (or possibly even in an advanced text editor?), you would see those characters are gone: &gt;&gt;&gt;print(doc) 'aia group limited 友邦保險控股有限公司 real life real impact a nnua l rep ort 2015 stock code 1299 vision purpose our vision is to be the pre eminent life insurance provider in the asia pacific region that is our service to our customers and our shareholders our purpose is to play a leadership role in driving economic and social development across the region that is our service to societies and their people about aia aia group limited and its subsidiaries collectively aia or the group comprise the largest independent publicly listed pan asian life insurance group it has a presence in 18 markets in asia paciﬁc wholly owned branches and subsidiaries in hong kong thailand singapore malaysia china korea the philippines australia indonesia taiwan ... ... ... Yeah, the punctuations and capitalizations are gone too, but that is ok as punctuations and capitalizations don't matter for what I intend to do with this extracted text.

http://stackoverflow.com/q/50559045
has title: How to print line of a file after match an exact string pattern with python?
favorite count: 0
has body: I have a list list = ['plutino?','res 2:11','Uranus L4','res 9:19','damocloid','cubewano?','plutino'] I want to search every element from the list in a file with the next format and print the line after match 1995QY9 | 1995_QY9 | plutino | 32929 | | 39.445 | 0.260 | 29.193 | 49.696 | 4.8 | 66 | # 0.400 | 1.21 BR-U | ? 1997CU29 | 1997_CU29 | cubewano | 33001 | | 43.534 | 0.039 | 41.815 | 45.253 | 1.5 | 243 | | 1.82 RR | 1998BU48 | 1998_BU48 | Centaur | 33128 | | 33.363 | 0.381 | 20.647 | 46.078 | 14.2 | 213 | # 0.052 | 1.59 RR | ? 1998VG44 | 1998_VG44 | plutino | 33340 | | 39.170 | 0.250 | 29.367 | 48.974 | 3.0 | 398 | # 0.028 | 1.51 IR | 1998SN165 | 1998_SN165 | inner classic | 35671 | | 37.742 | 0.041 | 36.189 | 39.295 | 4.6 | 393 | # 0.060 | 1.13 BB | 2000VU2 | 2000_VU2 | unusual | 37117 | Narcissus | 6.878 | 0.554 | 3.071 | 10.685 | 13.8 | 11 | # 0.088 | | 1999HX11 | 1999_HX11 | plutino? | 38083 | Rhadamanthus | 39.220 | 0.151 | 33.295 | 45.144 | 12.7 | 168 | | 1.18 BR | 1999HB12 | 1999_HB12 | res 2:5 | 38084 | | 56.376 | 0.422 | 32.566 | 80.187 | 13.1 | 176 | | 1.39 BR-IR | I am using the next code to do that for i in list: with open("tnolist.txt") as f: for line in f: if re.search(i, line): print(line) The code works fine for all element, except for plutino. When the variable i is plutino the code prints lines for plutino and for plutino?.
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/50559104
score: 1
has comment: http://stackoverflow.com/comment/88129099
type: Question
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88129162
has comment: http://stackoverflow.com/comment/88128885
has comment: http://stackoverflow.com/comment/88129184
tagged with: python

http://stackoverflow.com/a/51461765
accepted answer of: http://stackoverflow.com/q/50589085
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50589085
type: Answer
score: 1
has body: Continuing from the suggestion of the previous answer.I didn't find an already made Python solution that rewrites the class name in the elements and the class attribute of each path so I have created one myself: https://github.com/Amirh24/SVGAppender Feel free to use it :)
upvote count: 1

http://stackoverflow.com/q/50552759
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88117178
tagged with: models
has comment: http://stackoverflow.com/comment/88116397
type: Question
has title: python django models int() argument must be a string a bytes-like object or a number not a datetime
has body: In Django models, I'm trying to create two tables: Job and Images, and I'm trying to relate the image table to the jobs table through the job_id. But every time I migrate, I get the following error: int() argument must be a string a bytes-like object or a number not a datetime My code below: from Django.db import models class Job(models.Model): job_id = models.IntegerField(default=1, primary_key=True) summary = models.CharField(max_length=200) upload = models.FileField(upload_to='uploads/') class Images(models.Model): image_id = models.IntegerField(default=1, primary_key=True) image = models.ImageField(upload_to='images/') job_id = models.ForeignKey(Job, on_delete=models.CASCADE)
tagged with: postgresql
has comment: http://stackoverflow.com/comment/88117262
score: 0
tagged with: sql
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/50561412
linked to: http://stackoverflow.com/q/39141856
tagged with: pandas
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/39141856
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/88133565
has body: How to replace a multiple version in easiest way? Here's my data: No Device 1 asus 2 Xiaomi 3 xiaomi 4 Asus 5 Samsung I want to make it: No Device 1 Asus 2 Xiaomi 3 Xiaomi 4 Asus 5 Samsung What I did is: f = {'xiaomi':'Xiaomi', 'asus':'Asus'} df['Device'] = df['Device'].map(f) But the result is: No Device 1 Asus 2 NaN 3 Xiaomi 4 NaN 5 NaN
type: Question
has comment: http://stackoverflow.com/comment/88133616
accepted answer: http://stackoverflow.com/a/50561612
tagged with: python
score: 0
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/50561425
downvote count: 1
possible better answer: http://stackoverflow.com/a/50561452
has answer: http://stackoverflow.com/a/50561452
tagged with: dataframe
has answer: http://stackoverflow.com/a/50561612
has title: Capitalize a string column in pandas

http://stackoverflow.com/q/50597376
tagged with: google-cloud-ml
tagged with: python
type: UnansweredQuestion
has title: Invalid character found in base64 while using a deployed model on cloudml
tagged with: tensorflow
type: Question
linked to: http://stackoverflow.com/q/53410469
score: 3
has comment: http://stackoverflow.com/comment/112719175
has answer: http://stackoverflow.com/a/50606625
tagged with: google-cloud-platform
has body: For better context, I have uploaded a pre-trained model on cloud ml. It's an inceptionV3 model converted from keras to acceptable format in tensorflow. from keras.applications.inception_v3 import InceptionV3 model = InceptionV3(weights='imagenet') from keras.models import Model intermediate_layer_model = Model(inputs=model.input,outputs=model.layers[311].output) with tf.Graph().as_default() as g_input: input_b64 = tf.placeholder(shape=(1,), dtype=tf.string, name='input') input_bytes = tf.decode_base64(input_b64[0]) image = tf.image.decode_image(input_bytes) image_f = tf.image.convert_image_dtype(image, dtype=tf.float32) input_image = tf.expand_dims(image_f, 0) output = tf.identity(input_image, name='input_image') g_input_def = g_input.as_graph_def() K.set_learning_phase(0) sess = K.get_session() from tensorflow.python.framework import graph_util g_trans = sess.graph g_trans_def = graph_util.convert_variables_to_constants(sess, g_trans.as_graph_def(), [intermediate_layer_model.output.name.replace(':0','')]) with tf.Graph().as_default() as g_combined: x = tf.placeholder(tf.string, name="input_b64") im, = tf.import_graph_def(g_input_def, input_map={'input:0': x}, return_elements=["input_image:0"]) pred, = tf.import_graph_def(g_trans_def, input_map={intermediate_layer_model.input.name: im, 'batch_normalization_1/keras_learning_phase:0': False}, return_elements=[intermediate_layer_model.output.name]) with tf.Session() as sess2: inputs = {"inputs": tf.saved_model.utils.build_tensor_info(x)} outputs = {"outputs":tf.saved_model.utils.build_tensor_info(pred)} signature =tf.saved_model.signature_def_utils.build_signature_def( inputs=inputs, outputs=outputs, method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME ) # save as SavedModel b = tf.saved_model.builder.SavedModelBuilder('inceptionv4/') b.add_meta_graph_and_variables(sess2, [tf.saved_model.tag_constants.SERVING], signature_def_map={'serving_default': signature}) b.save() The generated pb file works fine whe…
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
upvote count: 3

http://stackoverflow.com/q/50685811
tagged with: python-2.7
answer count: 2
tagged with: odoo-10
has answer: http://stackoverflow.com/a/50685855
duplicate of: http://stackoverflow.com/q/3559559
possible better answer: http://stackoverflow.com/a/50685888
favorite count: 0
has title: How to change 000-000 to 000000 in Python?
has body: I'm making an odoo10 module, but I need to change a string like 000-000 to 000000 How can I do that?
downvote count: 5
tagged with: python
type: AnsweredQuestion
upvote count: 0
score: -5
has comment: http://stackoverflow.com/comment/88381409
type: Question
accepted answer: http://stackoverflow.com/a/50685855
has answer: http://stackoverflow.com/a/50685888
linked to: http://stackoverflow.com/q/3559559

http://stackoverflow.com/comment/88382523
type: AnswerComment
type: Comment
has text: Thanks @Ram! Idk why it didn't immediately occur to me to make the names dictionary keys. Much easier approach.
comment on: http://stackoverflow.com/a/50636617
score: 0

http://stackoverflow.com/a/50630173
has body: If you are attempting to implement a true breadth-first-search, you can simplify your solution using getattr, to handle tree leaves (left or right attributes storing None), and collections.deque for simpler element access from both ends. Note that collections.deque contains a __bool__ method, thus, you do not need an explicit size comparison in your while loop. For demonstration purposes, The code below creates a full binary tree with a __repr__ method for answer validation, and then provides the solution class. Also, to find the tree level order, as detailed in this similar problem, you can use recursion for a simpler result: Binary Tree implementation: import collections, random class Tree: full_nodes = [] def __init__(self, **kwargs): self.__dict__ = {i:kwargs.get(i) for i in ['left', 'right', 'value']} Tree.full_nodes.append(kwargs.get('value')) def __bool__(self): return bool(getattr(self, 'value')) def __lt__(self, _node): return self.value &lt; getattr(_node, 'value', _node) def insert_val(self, val): if self.value is None: self.value = val else: if val &lt; self.value: if self.left is None: self.left = Tree(value = val) else: self.left.insert_val(val) else: if self.right is None: self.right = Tree(value = val) else: self.right.insert_val(val) def __repr__(self): return f'&lt;tree storing nodes {list(filter(None, Tree.full_nodes))}&gt;' @classmethod def load_tree(cls, num=10, bounds = [1, 100]): _t = cls() for i in range(num): _t.insert_val(random.choice(range(*bounds))) return _t Solutions: class Solution: @staticmethod def bfs(tree, _to_find): queue = collections.deque([tree]) seen = [] while queue: _current = queue.popleft() if getattr(_current, 'value', None) == _to_find: return True l = list(filter(None, [getattr(_current, i, None) for i in ['left', 'right'] if getattr(_current, i, None) not in seen])) queue.extend(l) seen.extend(l) return False @staticmethod def level_nodes(tree): return [list(filter(None, [*(Solution.level_nodes(tree.left) if isinstanc…
type: Answer
downvote count: 1
upvote count: 0
score: -1
answers question: http://stackoverflow.com/q/50618058

http://stackoverflow.com/q/50546268
has answer: http://stackoverflow.com/a/50546428
answer count: 1
tagged with: javascript
tagged with: byte
has comment: http://stackoverflow.com/comment/88103726
has comment: http://stackoverflow.com/comment/88103550
tagged with: python
tagged with: node.js
has body: I have a function I am mapping from Javascript: var commandBytes = [4,1,0,0,0,0, Math.floor(224 + (52/16)), 52 % 16]; ...this is how I have in Python: data = bytearray([4,1,0,0,0,0, 224 + 52 // 16, 52 % 16]) ...this is what the output looks like in IDLE: bytearray(b'\x04\x01\x00\x00\x00\x00\xe3\x04') ...this is what the original output looks like when output by Javascript to the Command Prompt window: &lt;Buffer 04 01 00 00 00 00 e3 04&gt; ...first issue I have is the bytes in IDLE seem to be printed in hex rather than actual numbers. Second is, even though I know my connection to the machine I am passing the command to is good as I am getting a response, the command itself does not work. What do I need to change so that my Python output replicates my Javascript output? Thanks
score: 0
type: UnansweredQuestion
has title: Replicating byte string creation done in Javascript into Python 2.7
type: Question

http://stackoverflow.com/comment/88329636
type: Comment
has text: @I changed what I am trying to do now looks a bit different. I made a mistake in my explanation please check it. I alway want to lag by 2 not 4 or 6 later and so on.
comment on: http://stackoverflow.com/a/50659762
type: AnswerComment
score: 0

http://stackoverflow.com/q/50646426
type: AnsweredQuestion
has title: How to use pre-trained models without classes in Tensorflow?
answer count: 2
has answer: http://stackoverflow.com/a/50649987
tagged with: keras
has answer: http://stackoverflow.com/a/50650325
has body: I'm trying to use a pretrained network such as tf.keras.applications.ResNet50 but I have two problems: I just want to obtain the top embedding layers at the end of the network, because I don't want to do any image classification. So due to this there is no need for a classes number I think. tf.keras.applications.ResNet50 takes a default parameter 'classes=1000' Is there a way how I can omit this parameter? My input pictures are 128*128*1 pixels and not 224*224*3 What is the best way to fix my input data shape? My goal is to make a triplet loss network with the output of a resnet network. Thanks a lot!
has comment: http://stackoverflow.com/comment/88310406
possible better answer: http://stackoverflow.com/a/50650325
tagged with: python
score: 0
accepted answer: http://stackoverflow.com/a/50649987
tagged with: resnet
has comment: http://stackoverflow.com/comment/88310261
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/88322973
comment on: http://stackoverflow.com/a/50655109
type: AnswerComment
type: Comment
score: 1
has text: Start the range at 1 and then you don't need `if x`. Consider `np.logical_xor.reduce(x).any()` instead of `any(...)` (I personally think it reads nicer, might also be faster). Ideally duplicate arrays in the input should be removed first to make this faster and avoid duplicates in the output (as there are now), although if OP needs the indices of the arrays that will make things harder.

scikit-learn
tags question: http://stackoverflow.com/q/50585078
tags question: http://stackoverflow.com/q/50634781
tags question: http://stackoverflow.com/q/50573084
tags question: http://stackoverflow.com/q/50697579
tags question: http://stackoverflow.com/q/50659994
tags question: http://stackoverflow.com/q/50598225
tags question: http://stackoverflow.com/q/50551428
tags question: http://stackoverflow.com/q/50665855
tags question: http://stackoverflow.com/q/50571419
tags question: http://stackoverflow.com/q/50583772
tags question: http://stackoverflow.com/q/50642763
tags question: http://stackoverflow.com/q/50542636
tags question: http://stackoverflow.com/q/50626539
tags question: http://stackoverflow.com/q/50586912
tags question: http://stackoverflow.com/q/50639614
tags question: http://stackoverflow.com/q/50565937
tags question: http://stackoverflow.com/q/50544917
tags question: http://stackoverflow.com/q/50586486
tags question: http://stackoverflow.com/q/50557129
tags question: http://stackoverflow.com/q/50641576
tags question: http://stackoverflow.com/q/50671503
tags question: http://stackoverflow.com/q/50628266
tags question: http://stackoverflow.com/q/50633488
tags question: http://stackoverflow.com/q/50569288
tags question: http://stackoverflow.com/q/50671283
tags question: http://stackoverflow.com/q/50633153
tags question: http://stackoverflow.com/q/50567008
tags question: http://stackoverflow.com/q/50546170
tags question: http://stackoverflow.com/q/50669873
tags question: http://stackoverflow.com/q/50556642
tags question: http://stackoverflow.com/q/50544771
tags question: http://stackoverflow.com/q/50668340
tags question: http://stackoverflow.com/q/50546065
tags question: http://stackoverflow.com/q/50661075
tags question: http://stackoverflow.com/q/50580848
tags question: http://stackoverflow.com/q/50639464
tags question: http://stackoverflow.com/q/50564834
tags question: http://stackoverflow.com/q/50639003
tags question: http://stackoverflow.com/q/50658725
tags question: http://stackoverflow.com/q/50598405
tags question: http://stackoverflow.com/q/50646415
tags question: http://stackoverflow.com/q/50575118
tags question: http://stackoverflow.com/q/50614069
tags question: http://stackoverflow.com/q/50564099
tag name: scikit-learn
tags question: http://stackoverflow.com/q/50665240
tags question: http://stackoverflow.com/q/50692660
tags question: http://stackoverflow.com/q/50651861
tags question: http://stackoverflow.com/q/50628586
tags question: http://stackoverflow.com/q/50659884
tags question: http://stackoverflow.com/q/50676717
type: Tag
tags question: http://stackoverflow.com/q/50545339
tags question: http://stackoverflow.com/q/50628376
tags question: http://stackoverflow.com/q/50552142
tags question: http://stackoverflow.com/q/50658576
tags question: http://stackoverflow.com/q/50656471
tags question: http://stackoverflow.com/q/50558581
tags question: http://stackoverflow.com/q/50666091
tags question: http://stackoverflow.com/q/50582637
tags question: http://stackoverflow.com/q/50591123
tags question: http://stackoverflow.com/q/50579544
tags question: http://stackoverflow.com/q/50575580
tags question: http://stackoverflow.com/q/50691868
tags question: http://stackoverflow.com/q/50673632
tags question: http://stackoverflow.com/q/50610593
tags question: http://stackoverflow.com/q/50659056
tags question: http://stackoverflow.com/q/50603453
tags question: http://stackoverflow.com/q/50621387
tags question: http://stackoverflow.com/q/50577947
tags question: http://stackoverflow.com/q/50698063
tags question: http://stackoverflow.com/q/50612523
tags question: http://stackoverflow.com/q/50573579
tags question: http://stackoverflow.com/q/50651581
tags question: http://stackoverflow.com/q/50574339
tags question: http://stackoverflow.com/q/50549681
tags question: http://stackoverflow.com/q/50625975
tags question: http://stackoverflow.com/q/50635335
tags question: http://stackoverflow.com/q/50629219

http://stackoverflow.com/a/74258957
has body: Handling larger than memory CSV files Below code converts CSV to Parquet without loading the whole csv file into the memory import pandas as pd import pyarrow as pa import pyarrow.parquet as pq new_schema = pa.schema([ ('col1', pa.int64()), ('col2', pa.int64()), ('newcol', pa.int64()) ]) csv_column_list = ['col1', 'col2'] with pq.ParquetWriter('my_parq_data.parquet', schema=new_schema) as writer: with pd.read_csv('my_data.csv', header=None, names=csv_column_list, chunksize=100000) as reader: for df in reader: # transformation: transform df by adding a new static column with column name 'newcol' and value 9999999 df['newcol'] = 9999999 # convert pandas df to record batch transformed_batch = pa.RecordBatch.from_pandas(df, schema=new_schema) writer.write_batch(transformed_batch) Above code: Reads the large CSV file in chunks. Transforms the data frame by adding the new column. Converts the df to arrow record batch. Writes the transformed arrow batch as a new row group to the parquet file. Note: Do not keep the chunk size very low. This will result in poor compression since chunk size corresponds to the row group size in the new parquet file as well.
answers question: http://stackoverflow.com/q/50604133
type: Answer
score: 8
downvote count: 0
upvote count: 8

http://stackoverflow.com/comment/88271267
comment on: http://stackoverflow.com/q/50630123
score: 0
type: Comment
type: QuestionComment
has text: Do you know what the extra words you predict should be? bAbI is designed to predict single words.

http://stackoverflow.com/comment/88215186
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50593550
has text: Apparently I have the same problem with `multiprocessing` (when I replace the `pool = multiprocess.Pool(4)` with `pool = multiprocessing.Pool(4)`
score: 0

http://stackoverflow.com/comment/88123769
comment on: http://stackoverflow.com/q/50556352
type: Comment
has text: Or, `plt.gcf().autofmt_xdate()`
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88567593
type: QuestionComment
comment on: http://stackoverflow.com/q/50630877
has text: modify account is used to modify the existing account. set the default account first and modify the account with your new details
score: 0
type: Comment

http://stackoverflow.com/a/50633548
has comment: http://stackoverflow.com/comment/88296675
score: 3
has comment: http://stackoverflow.com/comment/88277348
has comment: http://stackoverflow.com/comment/88280105
upvote count: 3
has body: You cannot pass a table name as a parameter, alas. You have to munge it into the query string: sql = """ SELECT * FROM `{0}`; """.format(table) cursor.execute(sql)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88302182
has comment: http://stackoverflow.com/comment/88284522
type: Answer
accepted answer of: http://stackoverflow.com/q/50633524
has comment: http://stackoverflow.com/comment/88305988
downvote count: 0
answers question: http://stackoverflow.com/q/50633524

http://stackoverflow.com/comment/88109063
has text: @coldspeed I ran with your first solution and it took about 3 seconds (around 5 million data). This is just a sample data and the actual dataset is much larger so had to find the quickest possible way. Maybe there was something I did wrong which might have took much longer than it should have when I first tried using method suggested by kshikama, still your method was faster for sure
comment on: http://stackoverflow.com/q/50548942
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50659967
has comment: http://stackoverflow.com/comment/88329991
downvote count: 0
tagged with: pandas
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50660000
has answer: http://stackoverflow.com/a/50660000
score: 1
has comment: http://stackoverflow.com/comment/88329934
favorite count: 0
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/50659978
answer count: 2
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50659978
has body: I have the below pandas dataframe, and I would like to transform into a sequence of elements into a single column without losing the temporal order of the id and fruit column. id fruit ---|------ 101 apple 102 apple 101 watermelon 101 orange 102 orange 104 lemon 105 lemon 104 lemon 105 apple 103 grapes For example, the new dataframe should look like this (*): id col 101 apple, watermelon, orange 102 apple, orange 103 grapes 104 lemon, lemon 105 apple I tried to: f = {'url' : lambda x: np.unique(x).tolist()} df = df.groupby('id', as_index=False).agg(f).reindex(columns=df.columns) def foo(row): #just to remove the brackets return ', '.join(row) df4['url'] = df4['fruit'].apply(tweak) df4 However, although this is working when I do: list(df.loc362['fruit']) The collected information in each row is not temporally sorted (following the order of appearance order of the fruit column). Thus, how can I get (*)?
has title: How to append all the elements with the same id in a pandas dataframe row?

http://stackoverflow.com/comment/88236729
comment on: http://stackoverflow.com/q/50613188
has text: @roganjosh My issue right now is that when I run the program at the start, I clean it with ```with open('data.json', 'w') as f: json.dump(Infotext, f) f.write("\n")``` Which will then give me the start in the json file *First name : Last name : email* - And then when the script is finished with randomized the names and emails the output gonna be more like I added in the edited code.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50591009
answers question: http://stackoverflow.com/q/50575113
downvote count: 0
type: Answer
has body: Your requirements.txt is not in the correct format. It seems to me that you have generated it using pip list. You want to use pip freeze when generating your requirements.txt.
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/88204092

http://stackoverflow.com/a/50626031
answers question: http://stackoverflow.com/q/50625392
has body: I haven't read the whole code but you might (or not...) be able to make the thing work by monkeypatching cluster.worker: from django_q import cluster # in case you need to call the original implementation original_worker = cluster.worker def myworker(...): # your code here cluster.worker = myworker # now cluster will use `myworker` But this is to be considered as a temporary workaround at best. The proper solution would be to fork djangoq so it only uses it's own worker function as default and let you pass any other callable.
type: Answer
score: 0

http://stackoverflow.com/comment/88427866
score: 1
has text: I just found a short tutorial on how to use pyDev with Anaconda [here](https://github.com/mikec964/chelmbigstock/wiki/Set-up-Eclipse-(PyDev)-to-use-Anaconda-with-Python-2.7-and-3.x). Once you get the hang of it, anaconda environments will be an asset because they are quite powerful.
type: AnswerComment
comment on: http://stackoverflow.com/a/50644376
type: Comment

http://stackoverflow.com/q/50648271
answer count: 2
upvote count: 1
has title: How do I index based on another array in Keras
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88308174
tagged with: python
has comment: http://stackoverflow.com/comment/88307859
tagged with: indexing
has answer: http://stackoverflow.com/a/50650814
has comment: http://stackoverflow.com/comment/88308093
downvote count: 0
score: 1
has body: I have 2 tensors a and b which have the following shapes &gt;&gt;K.int_shape(a) (None, 5 , 2) &gt;&gt;K.int_shape(b) (None, 5) What I want to get is a tensor c &gt;&gt;K.int_shape(c) (None, 2) such that along axis 0, you pick the index of largest element in b and use that to index a along axis 1. Example - say I have a = np.array([[[2, 7], [6, 5], [9, 9], [4, 2], [5, 9]], [[8, 1], [8, 8], [3, 9], [9, 2], [9, 1]], [[3, 9], [6, 4], [5, 7], [5, 2], [5, 6]], [[7, 5], [9, 9], [9, 5], [9, 8], [5, 7]], [[6, 3], [1, 7], [3, 6], [8, 2], [3, 2]], [[6, 4], [5, 9], [8, 6], [5, 2], [5, 2]], [[2, 6], [6, 5], [3, 1], [6, 2], [6, 4]]]) and I have b = np.array([[ 0.27, 0.25, 0.23, 0.06, 0.19], [ 0.3 , 0.13, 0.17, 0.2 , 0.2 ], [ 0.08, 0.04, 0.40, 0.36, 0.12], [ 0.3 , 0.33, 0.11, 0.07, 0.19], [ 0.15, 0.21, 0.30, 0.12, 0.22], [ 0.3 , 0.13, 0.23, 0.1 , 0.23], [ 0.26, 0.35 , 0.25 , 0.07, 0.07]]) What I expect c to be c = np.zeros((7,2)) for i in range(7): ind = np.argmax(b[i, :]) c[i, :] = a[i, ind, :] c array([[ 2., 7.], [ 8., 1.], [ 5., 7.], [ 9., 9.], [ 3., 6.], [ 6., 4.], [ 6., 5.]])
type: Question
tagged with: theano
has answer: http://stackoverflow.com/a/50648726
tagged with: keras

http://stackoverflow.com/q/50542668
has answer: http://stackoverflow.com/a/50546869
type: Question
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/50547224
answer count: 3
tagged with: python
has title: How to convert a malformed bytes to dictionary?
tagged with: python-3.x
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/50546762
has body: I have a Kafka consumer which reads the bytes and I need to treat it as a dictionary. This is how the producer publishes: def on_status(self, status): print "on_status" if status.retweeted: return tweetText = status.text.encode('utf8') created_at = status.created_at id = status.id if (re.findall(self.httpCheck, tweetText) or re.findall(self.httpsCheck, tweetText)): return if (re.search('[a-zA-Z]', tweetText)): try: self.idSelf += 1 self.tweet["tweet"] = tweetText self.tweet["id"] = id self.tweet["sequence"] = self.idSelf self.tweet["created_at"] = created_at future = producer.send('bubble-test', bytes(self.tweet)) except Exception as e: print e finally: producer.flush() This is how consumer treats the bytes data: consumer = KafkaConsumer('bubble-test', bootstrap_servers='localhost:9092', auto_offset_reset='earliest') for message in consumer: tweet = ast.literal_eval(message.value) print (type(tweet)) sys.exit() While using ast.literal_eval(), I get the following error: ValueError: malformed node or string: b'{\'created_at\': datetime.datetime(2018, 5, 25, 13, 35, 11), \'tweet\': "RT @KKRiders: Mavi to bowl the first ball of #Qualifier2. Saha on strike. Let\'s go!\n\n#SRHvKKR #TeesraVaar #KKRHaiTaiyaar", \'id\': 1000007371131764736, \'sequence\': 1}' How do I treat it as a dictionary, which is my end result?
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50546869
has answer: http://stackoverflow.com/a/50547224

http://stackoverflow.com/q/50560607
linked to: http://stackoverflow.com/q/15367760
has answer: http://stackoverflow.com/a/50560754
linked to: http://stackoverflow.com/q/26498652
tagged with: python
has comment: http://stackoverflow.com/comment/88131732
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
has body: Everything works perfect for a couple hours an then i'll get this error, an it will stop running. todolist_items = len(todoalso) UnboundLocalError: local variable 'todoalso' referenced before assignment I think this is the section Im having trouble with but I dont understand why. response = requests.get("https://beta.todoist.com/API/v8/tasks", params={"token":todoist_TOKEN}) if response.status_code == 200: todoalso = response.json() global todolist_items todolist_items = len(todoalso)
has answer: http://stackoverflow.com/a/50560654
type: Question
duplicate of: http://stackoverflow.com/q/22101836
has comment: http://stackoverflow.com/comment/88131682
score: -2
has answer: http://stackoverflow.com/a/50560671
linked to: http://stackoverflow.com/q/22101836
has title: local variable referenced before assignment json
has comment: http://stackoverflow.com/comment/88131677
answer count: 3
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/88131703
accepted answer: http://stackoverflow.com/a/50560754
possible better answer: http://stackoverflow.com/a/50560654
favorite count: 0

http://stackoverflow.com/q/50566226
tagged with: signal-processing
type: Question
has answer: http://stackoverflow.com/a/50568436
tagged with: filtering
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/50569407
accepted answer: http://stackoverflow.com/a/50569407
favorite count: 0
possible better answer: http://stackoverflow.com/a/50568436
tagged with: python
has title: How to find out if filter functions work with half-amplitude or half-power cut-offs
has body: I used scipy.signal.firwin to filter a signal that I have. Now I want to report the cutoff frequency used, however the documentation is not clear on these points: How is the cutoff frequency specified? As half-power(-3dB) or half-amplitude(-6dB)? ... Where is the cutoff frequency "located"? In the middle of transition band? At the edge between passband and transition band? ... In my case, knowing about the speficis of scipy.signal.firwin would already be helpful. But a bonus answer would be to show how I can computationally find out about this (or maybe through plotting?)
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: scipy

http://stackoverflow.com/comment/88295929
comment on: http://stackoverflow.com/q/50642551
score: 0
has text: I edited my post.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50677834
has answer: http://stackoverflow.com/a/50678075
tagged with: generator
has title: Loss always go to nan when transfer learning by ResNet50 in keras
tagged with: tensorflow
type: Question
tagged with: neural-network
score: 0
answer count: 1
tagged with: keras
has body: I am using transfer learning to train a image classifier by ResNet50 model in Keras and by loading the pre-trained weights, but the loss go to nan initially and instantly and the acc stay in random level. Actually, I don't know what is wrong because I have used this model to train a classifier successfully, though it was not with high acc but it works well. This time it failed. I tuned the lr but nothing happened. Someone said the data may have problems, so I changed the data and only to find with different images the same model will show different results(that is to say, some data/images works well and another data/images will results loss:nan instantly). How could that be? I am really confused and can't figure out what is wrong with my images. Dataset: 8 classes and each class contains about 300 images. Here is the code for all: import keras import h5py import numpy as np import matplotlib.pyplot as plt from keras.applications import ResNet50 from keras.models import Sequential from keras.layers import Dense, Flatten, GlobalAveragePooling2D from keras.applications.resnet50 import preprocess_input from keras.preprocessing.image import ImageDataGenerator data_generator = ImageDataGenerator(preprocessing_function= preprocess_input, rescale = 1./255) train_generator = data_generator.flow_from_directory("image/train", target_size = (100, 100), batch_size = 32, class_mode = "categorical") dev_generator = data_generator.flow_from_directory("image/dev", target_size = (100, 100), batch_size = 32, class_mode = "categorical") num_classes = 8 model = Sequential() model.add(ResNet50(include_top = False, pooling = "avg", weights= "resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5")) model.add(Dense(num_classes, activation = "softmax")) model.layers[0].trainable = False model.compile(optimizer= "adam", loss= "categorical_crossentropy", metrics=["accuracy"]) model.fit_generator(train_generator, steps_per_epoch= 1, epochs = 1) and the running output is: Epoch 1/1 1/1 [=========…
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/88112469
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50550549
has text: I have made edit,can you give example or link regarding constructor parameter.
type: AnswerComment

http://stackoverflow.com/a/50647448
upvote count: 2
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/88308855
downvote count: 1
answers question: http://stackoverflow.com/q/50647391
has body: You should install msgpack and then install pandas again.
has comment: http://stackoverflow.com/comment/88305781

http://stackoverflow.com/comment/88301539
type: Comment
has text: I'm getting an error: `Can only compare identically-labeled DataFrame objects`. If you add in another row to table1 that doesn't exist in table2, it all falls apart, as should be a more representative dataset for what I'm working with. I'll edit the starting dataset
comment on: http://stackoverflow.com/a/50645338
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88272807
type: QuestionComment
comment on: http://stackoverflow.com/q/50630103
has text: If i use tensorflow-gpu to run the graph is the opencv loop required to run on gpu too? Also can training a model from scratch to detect only people , instead of using the pretrained standard graphs that recognize up to 90 classes , get better performances? I’m sorry for all this questions but i’m a novice in this field and i’m trying to learn as much as possible
score: 0
type: Comment

http://stackoverflow.com/a/50609573
has body: Does this work for you? I've used the dictionaries get method which allows a default to be returned if the acronym cannot be found. Return is placed in to a new entry field called resultsBox once the enter key is pressed inside the first entry field. from tkinter import* acronym_dictionary={"AKA":"Also known as", "OT":"Overtime"} def return_entry(en): content=entry.get() result = acronym_dictionary.get(content,"Not Found") print(result) resultBox.delete(0,END) resultBox.insert(0,result) master=Tk() master.title("The Acronym Search Engine") master.geometry('300x100') Label(master, text="Search box:").grid(row=0, sticky=W) entry=Entry(master) entry.grid(row=0, column=1) entry.bind('&lt;Return&gt;', return_entry) Label(master, text="Result:").grid(row=1,column=0) resultBox=Entry(master) resultBox.grid(row=1,column=1) mainloop()
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50606250
score: 0
has comment: http://stackoverflow.com/comment/88248389
type: Answer
answers question: http://stackoverflow.com/q/50606250

http://stackoverflow.com/comment/88197562
type: QuestionComment
has text: Anyway **it's mistaken to read in 5Gb and write it out, without chunking**. The memory usage will be insane, and if you take an exception you lose everything. What is `commentsXML`, where does it come from, how large is it, and what does `commentsXML(element_fields)` do, is it a lookup?
comment on: http://stackoverflow.com/q/50593590
score: 0
type: Comment

http://stackoverflow.com/comment/88240441
has text: @abamert I am using the if(i+1 < len(s)): because if i don't i am getting an error when running the programme since it gets out of the string length
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50615188

http://stackoverflow.com/comment/88265753
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50627548
has text: See [this answer](https://stackoverflow.com/a/47116576/2286337).

http://stackoverflow.com/q/50647581
has body: We use robot framework at work to do some automated testing, and I need to add a few tests. This format is already in the repo, I cannot change anything drastically. I am using a keywords file that looks like this: #!/usr/bin/env python3 # -*- coding: utf-8 -*- from robot.api.deco import keyword class testkeywords(object): """ """ def __init__(self): pass @keyword('I compare ${first_number} with ${second_number}') def compare(self, first_number, second_number): if (int(first_number) != int(second_number)): raise ValueError('Numbers are not the same.') The .robot file has two tests, one that passes and one that fails: *** Settings *** Library testkeywords.py *** Variables *** ${num_a} 5 ${num_b} 6 *** Test Cases *** Compare same numbers I compare ${num_a} with ${num_a} Compare different numbers I compare ${num_a} with ${num_b} The Compare different numbers test fails as expected, but it's still a FAIL. How can I set it to expect a failure and hence pass the keyword?
score: 4
has title: How to expect a failure in robot framework in Python?
possible better answer: http://stackoverflow.com/a/68950318
answer count: 2
has answer: http://stackoverflow.com/a/68950318
downvote count: 1
tagged with: robotframework
upvote count: 5
has answer: http://stackoverflow.com/a/50648095
has comment: http://stackoverflow.com/comment/88308245
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88328619
favorite count: 0
has comment: http://stackoverflow.com/comment/88355661
type: Question
accepted answer: http://stackoverflow.com/a/50648095
tagged with: python

http://stackoverflow.com/q/50683895
has title: importing pycurl with libcurl4 raises ImportError
favorite count: 0
type: Question
has body: I am using Ubuntu 18.04. If I install libcurl4 (instead of libcurl3), when I import pycurl installed with pipenv I get &gt;&gt;&gt; import pycurl Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: /usr/lib/x86_64-linux-gnu/libcurl.so.4: version `CURL_OPENSSL_3' not found (required by /home/pietro/envs/try_fabric-kcbGLH3z/lib/python3.6/site-packages/pycurl.cpython-36m-x86_64-linux-gnu.so) Note that this error is raised only when I use a pycurl installed with pipenv or pip. If I use instead pycurl installed through apt on system python there are any errors... What can I do to avoid this impasse?
tagged with: python
tagged with: pip
upvote count: 1
answer count: 1
tagged with: pycurl
tagged with: pipenv
has answer: http://stackoverflow.com/a/50687263
has comment: http://stackoverflow.com/comment/88379218
accepted answer: http://stackoverflow.com/a/50687263
has comment: http://stackoverflow.com/comment/88379534
type: AnsweredQuestion
tagged with: libcurl
downvote count: 0
score: 1

http://stackoverflow.com/comment/88400219
has text: That works perfectly to create the list but how do i use that list in an input. Sorry im new to this. I edited the original question and put the code in
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50695476

http://stackoverflow.com/q/50688550
has title: Max gcc optimization for C extensions?
has comment: http://stackoverflow.com/comment/88386961
type: UnansweredQuestion
tagged with: python
answer count: 0
has body: At least when GCC is used, Python compiles every C extension with mild speed optimization, that is, with the -O2 flag. What is the most portable way to make it use the most aggressive speed optimization available (for gcc -O3)? I think there is a way to forcefully add -O3 as compilation options for each extension (extra_compile_args attribute), but I am not keen in doing that as the underlying C compiler may not necessarily be gcc (it may understand or like -O3).
type: Question
has comment: http://stackoverflow.com/comment/88387068
has comment: http://stackoverflow.com/comment/88427533
tagged with: compiler-optimization
tagged with: gcc
score: 0
has comment: http://stackoverflow.com/comment/88427941
has comment: http://stackoverflow.com/comment/88387047

http://stackoverflow.com/comment/88248032
type: Comment
has text: It may work but again the problem is going the pandas way... I don't want to do that and work with formatting the csv in the initial phase itself. So any way with which we can read 2 files, do something similar to map/merge based on id will really help.
comment on: http://stackoverflow.com/q/50618621
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88282439
has text: Hi @Sijan Bhandari, i ran the xml file, using the content and got the following error: KeyError: 'nite:root'
type: Comment
comment on: http://stackoverflow.com/a/50595178
score: 0
type: AnswerComment

http://stackoverflow.com/q/50596400
tagged with: python
downvote count: 1
has title: Could not find a version
score: -1
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/50596432
linked to: http://stackoverflow.com/q/31328368
tagged with: operating-system
has comment: http://stackoverflow.com/comment/88201915
has comment: http://stackoverflow.com/comment/88202300
answer count: 1
has body: I'm on mac trying to install the module "arcpy" with pip. I use this command: pip install --user arcpy And I get this error: Could not find a version that satisfies the requirement os (from versions: ) No matching distribution found for arcpy Can someone tell me the problem?
favorite count: 0
has comment: http://stackoverflow.com/comment/88202002
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88201958
tagged with: pip

http://stackoverflow.com/a/50582636
type: AcceptedAnswer
downvote count: 0
has body: I believe need DatetimeIndex.floor: print (dr.floor('S')) DatetimeIndex(['2011-01-01 00:00:00', '2011-01-01 03:25:42', '2011-01-01 06:51:25', '2011-01-01 10:17:08', '2011-01-01 13:42:51', '2011-01-01 17:08:34', '2011-01-01 20:34:17', '2011-01-02 00:00:00', '2011-01-02 03:25:42', '2011-01-02 06:51:25', '2011-01-02 10:17:08', '2011-01-02 13:42:51', '2011-01-02 17:08:34', '2011-01-02 20:34:17', '2011-01-03 00:00:00'], dtype='datetime64[ns]', freq=None)
type: Answer
accepted answer of: http://stackoverflow.com/q/50582589
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/50582589

http://stackoverflow.com/q/50584760
linked to: http://stackoverflow.com/q/469913
type: AnsweredQuestion
has body: I have research, but found no answer to the question below. How can I do a boolean comparison for a list of substrings in a list of strings? Below is the code: string = {'strings_1': ['AEAB', 'AC', 'AI'], 'strings_2':['BB', 'BA', 'AG'], 'strings_3': ['AABD', 'DD', 'PP'], 'strings_4': ['AV', 'AB', 'BV']} df_string = pd.DataFrame(data = string) substring_list = ['AA', 'AE'] for row in df_string.itertuples(index = False): combine_row_str = [row[0], row[1], row[2]] #below is the main operation print(all(substring in row_str for substring in substring_list for row_str in combine_row_str)) The output I get is: False False False The output I want is: True False False
upvote count: 3
accepted answer: http://stackoverflow.com/a/50585915
type: Question
has title: Boolean comparison of a list of substring with a list of string
tagged with: dataframe
answer count: 2
tagged with: pandas
score: 3
downvote count: 0
tagged with: string
possible better answer: http://stackoverflow.com/a/50585068
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50585915
has answer: http://stackoverflow.com/a/50585068
tagged with: python

http://stackoverflow.com/q/50616037
answer count: 1
downvote count: 0
favorite count: 0
has title: sudo easy_install pip not working
type: UnansweredQuestion
tagged with: python
tagged with: easy-install
has body: I'm having trouble executing the sudo easy_install pip command on my mac. I'm not behind a firewall. I'm using python version 2.7.10. The version of macOS Sierra is 10.12.4. Here is the error I receive: Searching for pip Reading https://pypi.python.org/simple/pip/ Download error on https://pypi.python.org/simple/pip/: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) -- Some packages may not be found! Couldn't find index page for 'pip' (maybe misspelled?) Scanning index of all packages (this may take a while) Reading https://pypi.python.org/simple/ Download error on https://pypi.python.org/simple/: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) -- Some packages may not be found! No local packages or download links found for pip error: Could not find suitable distribution for Requirement.parse('pip')
has comment: http://stackoverflow.com/comment/88242104
has comment: http://stackoverflow.com/comment/88278473
tagged with: pip
has comment: http://stackoverflow.com/comment/88246587
type: Question
has answer: http://stackoverflow.com/a/50634468
upvote count: 5
score: 5
linked to: http://stackoverflow.com/q/44316292
has comment: http://stackoverflow.com/comment/88279361

http://stackoverflow.com/comment/88383978
type: QuestionComment
score: 1
has text: You probably have whitespace in one of the columns. As @AntonvBR points out, using to_dict() will help with this issue.
comment on: http://stackoverflow.com/q/50686970
type: Comment

http://stackoverflow.com/comment/88211707
type: Comment
type: QuestionComment
has text: While writing this I was thinking about trying to connect a client socket (on the same host with the server socket) to the server and wait for success. If not, something with the server could be wrong. I will try and answer my question it it works.
comment on: http://stackoverflow.com/q/50572997
score: 0

http://stackoverflow.com/comment/88300594
type: AnswerComment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/172249/discussion-between-tingting-and-aldream).
type: Comment
comment on: http://stackoverflow.com/a/50625174
score: 0

http://stackoverflow.com/a/52766855
score: 4
downvote count: 0
has body: I usually in stall gensim using pip on anaconda prompt using the following command pip install -U gensim or simply pip install gensim as shown in the anaconda documentation.
has comment: http://stackoverflow.com/comment/128493355
type: Answer
answers question: http://stackoverflow.com/q/50555303
has comment: http://stackoverflow.com/comment/128459640
upvote count: 4

cassandra
tags question: http://stackoverflow.com/q/50630585
type: Tag
tag name: cassandra
tags question: http://stackoverflow.com/q/50592682

http://stackoverflow.com/comment/90306014
comment on: http://stackoverflow.com/a/51019597
score: 0
type: AnswerComment
type: Comment
has text: What kind of error do you get? Can you run the script manually if you have no admin rights? @26099

http://stackoverflow.com/comment/88109526
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50546760
has text: @SteffenUllrich I added the error
score: 0

http://stackoverflow.com/a/50665644
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50665565
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50665565
has body: This should work: from datetime import datetime psycopg2.extras.execute_values(cursor, insert_stmt, [('AAPL',datetime.fromtimestamp(1528004700)), ('AAPL', datetime.fromtimestamp(1528005600))]) Edit: In general, Postgres has no way of guessing that your 1528004700 is a timestamp, you need to state it explicitly in some way. Your solution with to_timestamp places "this is a timestamp" on the Postgres side, above code places it on the python side. From the information point of view they are equivalent, I did not check which one is more efficient.
type: Answer
downvote count: 0

http://stackoverflow.com/comment/88405520
type: QuestionComment
has text: @SimeonIkudabo Can't use matplotlib, I need the bar chat exported as html
comment on: http://stackoverflow.com/q/50697847
score: 0
type: Comment

http://stackoverflow.com/comment/88195449
score: 0
has text: Are you looking to run the other program from within your Python script and capture its output, or are you looking to have the user pipe the output of the other program into the input or your program?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50593048

http://stackoverflow.com/q/50564837
has comment: http://stackoverflow.com/comment/88140561
tagged with: excel
linked to: http://stackoverflow.com/q/10993612
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/88140331
has comment: http://stackoverflow.com/comment/88140750
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/88140027
tagged with: http://stackoverflow.com/tag/xlsx
has comment: http://stackoverflow.com/comment/88140270
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/88140431
has answer: http://stackoverflow.com/a/50565484
has comment: http://stackoverflow.com/comment/88140554
tagged with: python
has comment: http://stackoverflow.com/comment/88139943
has body: This is my first time posting here so I am sorry if I've missed some of the code of conduct you usually have. I am having problems converting my Excel (xlsx) file to a CSV file using Python. This is required by my job, I wouldn't be otherwise doing it. So my excel file is structured like this: I have a name for our service, our buy price for it, and our customers buy price for it. The problem that I am facing is that when lets say for example I have a line like this in my xlsx file: BasicLevel 1798,20 1998,00 ExtremLevel 2,25 2,50 But whenever I convert my xlsx file to a csv file, the line turns into this: BasicLevel 1516.41 1684.9 ExtremLevel 43344 43102 So now what has happened is that the numbers have indeed changed. This makes the whole program obsolete as the numbers HAVE to be correct. This is my xlsx to CSV conversion code: def csv_from_excel_max(): wb = xlrd.open_workbook("Pricelist.xlsx") sh = wb.sheet_by_name("EUR") result_file = open("result_file.csv", "wb") wr = csv.writer(result_file, delimiter=";") rownum = 0 while rownum &lt; sh.nrows: wr.writerow([str(sh.cell(rownum, 3).value.replace(u"\xa0", "").replace(u"\u2122", "")).encode("utf-8"), sh.cell(rownum, 9).value, sh.cell(rownum, 10).value]) rownum += 1
type: UnansweredQuestion
has title: Numbers change when converting from XLSX to CSV

http://stackoverflow.com/comment/88106376
has text: @eyllanesc i got it ...Thanks....the actual error was from the code...my dpath didn't specify a zip file.....
score: 0
comment on: http://stackoverflow.com/q/50547526
type: Comment
type: QuestionComment

http://stackoverflow.com/a/56285610
upvote count: 13
answers question: http://stackoverflow.com/q/50655738
downvote count: 0
type: Answer
score: 13
has body: For Mac: Install Pytesseract (pip install pytesseract should work) Install Tesseract but only with homebrew, pip installation somehow doesn't work. (brew install tesseract) Get the path of brew installation of Tesseract on your device (brew list tesseract) Add the path into your code, not in sys path. The path is to be added along with code, using pytesseract.pytesseract.tesseract_cmd = '&lt;path received in step 3&gt;' - (e.g. pytesseract.pytesseract.tesseract_cmd = '/usr/local/Cellar/tesseract/4.0.0_1/bin/tesseract') This should work fine.

http://stackoverflow.com/comment/100264044
score: 0
has text: My solution was not to run `multiple` as is but via sync celery
type: QuestionComment
comment on: http://stackoverflow.com/q/50568485
type: Comment

http://stackoverflow.com/comment/88353327
type: Comment
has text: i can get the point of the first example but the others are really weird. like xy weird
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50670932

http://stackoverflow.com/comment/88371417
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50672033
has text: @DmytroOvdiienko yes I did. Also tried to create a _ndarray_ pointer by `array_of_double_pointer = np.ctypeslib.ndpointer(c_double, flags='C_CONTIGUOUS')` and pass in the original _ndarray_ object `np_array` to the function call. This throws the same access violation error.
type: Comment

http://stackoverflow.com/comment/88151220
type: Comment
comment on: http://stackoverflow.com/q/50570632
score: 1
has text: Please include enough details to reproduce the behavior you're asking about **inside the question text itself**, as described in the first "some questions are still off-topic" bullet point at https://stackoverflow.com/help/on-topic. When someone needs to follow a link to understand a question, that means that question could become useless if the link breaks / external content is removed / etc; our goal is to build a knowledgebase that lasts.
type: QuestionComment

http://stackoverflow.com/comment/88264712
type: Comment
type: QuestionComment
has text: instead of putting up the image, write the code.
score: 0
comment on: http://stackoverflow.com/q/50627310

http://stackoverflow.com/comment/88221062
type: QuestionComment
comment on: http://stackoverflow.com/q/50605433
score: 0
has text: Try `xhost +` in the terminal and then `xhost -` when you are finished. Your question is not really about progamming BTW.
type: Comment

http://stackoverflow.com/a/50644903
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50644615
has body: # standardize datetime format for comparison datadf['WeekEnding'] = pd.to_datetime(datadf.WeekEnding, format='%m/%d/%Y %H:%M') datadf['ReleaseDate'] = pd.to_datetime(datadf.ReleaseDate, format='%m/%d/%Y') # replace weekending with release date if smaller datadf['WeekEnding'] = datadf['WeekEnding'].where( datadf['WeekEnding'] &gt; datadf['ReleaseDate'], datadf['ReleaseDate'] ) datadf.groupby( ['TitleCode', 'ReleaseDate', 'WeekEnding'] ).TotalUnits.sum().reset_index()
type: Answer
accepted answer of: http://stackoverflow.com/q/50644615

http://stackoverflow.com/q/50617476
score: 1
tagged with: normalization
answer count: 1
downvote count: 0
tagged with: histogram
linked to: http://stackoverflow.com/q/15558136
has answer: http://stackoverflow.com/a/50618360
favorite count: 0
has title: How do I plot a histogram where the maximum y-value is one?
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50618360
upvote count: 1
has body: I have the following histogram: The blue columns are the data while the red line is the theoretical line. I generated this by first plotting the histogram, and then scaling the theoretical curve (which has a maximum of 1) to the approximate value of the peak of the histogram. I want to avoid this manual scaling by making the histogram have a peak value of 1 as well. How do I do this with Python? A previous question provides a way to get the peak value (122 in my case) but I can't figure out how to use that to scale the histogram. It seems like once I invoke the hist command it will create the current histogram, which makes sense since that's what histograms are - the columns shouldn't take fractional values. In other words I need a different approach. Any help appreciated.
type: Question

http://stackoverflow.com/a/50652368
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50648829
has body: Since you are creating the frame with a a fixed size then there may not be another EVT_SIZE event after the widgets and sizers have been created. Since the default EVT_SIZE handler is where the sizer is triggered to do its layout, then that means there will not be an initial layout of the widgets. They will just be left at their default sizes and locations. An easy workaround will take care of this problem for you. Simply add a call to frame.SendSizeEvent after everything has been created and set, to get an extra event so the sizers will be able to do their layout.
has comment: http://stackoverflow.com/comment/88318545
type: Answer
has comment: http://stackoverflow.com/comment/88445577
has comment: http://stackoverflow.com/comment/88419957
answers question: http://stackoverflow.com/q/50648829

http://stackoverflow.com/q/50609740
has body: I have the following code that is running in a celery task, self.resdict['jobs'] contains a list of subtasks and I am checking the status of them in a while loop. while any([x.status for x in self.resdict['jobs'].values() if x.status is not 'SUCCESS']): print([x.status for x in self.resdict['jobs'].values() if x.status is not 'SUCCESS']) print(any([x.status for x in self.resdict['jobs'].values() if x.status is not 'SUCCESS'])) time.sleep(.5) else: for a in self.resdict['accounts'][0]['result']: account = a['number'] if isinstance(a['number'], str) else False self.resdict[account] = self.resdict['jobs'][account].result[0]['result'][0]['Device Information']['subattributes'] When I run this code with CELERY_ALWAYS_EAGER = True and CELERY_EAGER_PROPAGATES_EXCEPTIONS = True, it gives me the results I expect if the list contains all 'SUCCESS' So what I am getting when I run with always eager: print([x.status for x in self.resdict['jobs'].values() if x.status is not 'SUCCESS']) = ['SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS'] print(any([x.status for x in self.resdict['jobs'].values() if x.status is not 'SUCCESS'])) = False When I run without always eager, inside celery debug I see: print([x.status for x in self.resdict['jobs'].values() if x.status is not 'SUCCESS']) = ['SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS', 'SUCCESS'] print(any([x.status for x in self.resdict['jobs'].values() if x.status is not 'SUCCESS'])) = True Which is not correct since the list only contains 'SUCCESS'. Any idea why celery is saying True when it should be False?
has title: celery any() statement giving wrong result inside task
type: Question
score: 0
has answer: http://stackoverflow.com/a/50610421
answer count: 1
type: UnansweredQuestion
tagged with: python
tagged with: celery

http://stackoverflow.com/comment/88198703
has text: Couldn't you avoid `np.isclose` by converting `df.A` to Categorical?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50592420
type: Comment

http://stackoverflow.com/comment/88380692
comment on: http://stackoverflow.com/q/50679145
score: 0
type: Comment
type: QuestionComment
has text: my.routing.key has to match the pattern my.#.*

http://stackoverflow.com/q/50565259
upvote count: 2
tagged with: python-multithreading
answer count: 1
has comment: http://stackoverflow.com/comment/88142135
has comment: http://stackoverflow.com/comment/88147124
has answer: http://stackoverflow.com/a/50595505
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88140638
has title: Flask object has no attribute app_context
score: 2
downvote count: 0
has body: I'm trying to send emails periodically with flask mail, but I'm stuck with this error: Flask object has no attribute app_context def mail_periodic(): print "sending mail at " +time.ctime() app = current_app._get_current_object() msg = Message("no-reply: Avantgarde.Rentals", sender="avantgarde.rentals.noreply@gmail.com", ) msg.add_recipient('aladinne.k@gmail.com') msg.body = 'Email periodic ' mail2 = Mail(app) with app.app_context(): mail2.send(msg) print"email sent " threading.Timer(5, mail_periodic).start() @app.route('/startcronemailing') def startcronemailing(): try: mail_periodic() except Exception, exception: return exception.message return "crone mailing started" the exception that i got : Exception in thread Thread-3: Traceback (most recent call last): File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner self.run() File "C:\Python27\lib\threading.py", line 1073, in run self.function(*self.args, **self.kwargs) File "app.py", line 113, in mail_periodic host_link='http://' + request.host, File "C:\Python27\lib\site-packages\werkzeug\local.py", line 336, in __getattr__ return getattr(self._get_current_object(), name) File "C:\Python27\lib\site-packages\werkzeug\local.py", line 295, in _get_current_object return self.__local() File "C:\Python27\lib\site-packages\flask\globals.py", line 19, in _lookup_object raise RuntimeError('working outside of request context') RuntimeError: working outside of request context please note that even if i use another mailing service like sendgrid i got the same error
tagged with: flask
favorite count: 0
tagged with: flask-mail
type: Question
tagged with: python

http://stackoverflow.com/q/50662620
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50662691
type: Question
has title: Finding New Max/Min Points In a List
has comment: http://stackoverflow.com/comment/88335422
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88335434
has comment: http://stackoverflow.com/comment/88335572
tagged with: python
has body: I am currently working with historical stock data in python with pandas datareader analyzing data from the last 250 trading days. One objective I am trying to accomplish is finding each time a new max price or min price occurs in the data. An example of what I am trying to do is as follows: max_point = [] min_point = [] test = [] for x in aapl[1][:]: test.append(x) if x &gt; max(test): max_point.append(x) if x &lt; min(test): min_point.append(x) This is my current non-working code, and I was wondering if I could get some insight on how to correctly write this code. Since I am relatively new to python, any other tips on the best ways to work with list iterations would also greatly be appreciated!
has comment: http://stackoverflow.com/comment/88335426
tagged with: list

http://stackoverflow.com/a/50677072
score: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50676950
has body: Be careful when concatenating strings, you might miss some spaces. For example: "2018-05-01"+ 'AND customers.end_date &lt;=' => "2018-05-01AND customers.end_date &lt;='. Etc. The other thing is adding quotes around date inside query. In your case quotes around are not part of query. So you could write instead: "'2018-05-01'"+ ' AND customers.end_date &lt;='. Or see the full example by @Dataichou
upvote count: 1

http://stackoverflow.com/comment/88263287
comment on: http://stackoverflow.com/q/50626573
type: QuestionComment
has text: Please check the CSV file, I have given few data there
score: 0
type: Comment

http://stackoverflow.com/comment/88339194
type: QuestionComment
has text: Thanks. Do you know deal with this error? ValueError: cannot index with vector containing NA / NaN values. I try dropna, it doesn't work out.
score: 0
comment on: http://stackoverflow.com/q/50664483
type: Comment

http://stackoverflow.com/comment/88304593
type: Comment
type: QuestionComment
has text: Show your code.
score: 2
comment on: http://stackoverflow.com/q/50647031

http://stackoverflow.com/comment/88382582
has text: yeah, i figured it out right after and it worked as you said
score: 0
comment on: http://stackoverflow.com/q/50684329
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50575118
tagged with: python
answer count: 0
has title: Affinity propagation clustering of radio signal strength data using sklearn
type: UnansweredQuestion
score: 0
upvote count: 1
tagged with: machine-learning
downvote count: 1
has comment: http://stackoverflow.com/comment/88160566
tagged with: hierarchical-clustering
type: Question
tagged with: cluster-analysis
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/88163293
favorite count: 0
has comment: http://stackoverflow.com/comment/88163378
has body: I am trying to cluster my datasets (radio signal strength from WiFi access points at a 2-D surface) using affinity propagation. I followed this and this links to grasp the basics of affinity propagation clustering. The sample code available at sklearn is as follows: from sklearn.cluster import AffinityPropagation from sklearn import metrics from sklearn.datasets.samples_generator import make_blobs # Generate sample data centers = [[1, 1], [-1, -1], [1, -1]] X, labels_true = make_blobs(n_samples=300, centers=centers, cluster_std=0.5, random_state=0) # Compute Affinity Propagation af = AffinityPropagation(preference=-50).fit(X) cluster_centers_indices = af.cluster_centers_indices_ labels = af.labels_ The above code runs well. I want to modify it for my own datasets. My datasets are in the following form: Here, each dot represent a grid point on the 2-D surface. And each grid point contains radio signal strength from various WiFi access points. I want to cluster the grid points according to the similarity on radio signal strength from WiFi access points. Can I do it using sklearn? Has any one done it using sklearn? Any links or sample code, please. Thank you.

http://stackoverflow.com/comment/88289728
type: AnswerComment
type: Comment
has text: Thanks, I never thought of `object` columns as series of pointers, that's a useful way to think about it.
score: 1
comment on: http://stackoverflow.com/a/50603926

http://stackoverflow.com/comment/88389473
score: 0
type: QuestionComment
type: Comment
has text: Please show that. The way autoscroll is designed to work is that it hides the scrollbars unless there's something that is scrollable, and your code doesn't have anything that's scrollable. I also strongly recommend you reduce your [mcve] down even further to only work with a couple columns and a vertical scrollbar. Once you get that working, then you can focus on horizontal scrolling which is a little trickier with the treeview widget.
comment on: http://stackoverflow.com/q/50686913

http://stackoverflow.com/a/50603255
type: Answer
has body: Here a try : a = [[1,2],[3,4],[5,6]] def FirstRuleLink (a): for i,nxt_elmnt in zip(a, a[1:]): if i[0] &lt;= nxt_elmnt[0] and i[1] &lt;= nxt_elmnt[1]: pass else: return False
has comment: http://stackoverflow.com/comment/88216475
accepted answer of: http://stackoverflow.com/q/50603097
has comment: http://stackoverflow.com/comment/88218244
answers question: http://stackoverflow.com/q/50603097
type: AcceptedAnswer
score: 0

http://stackoverflow.com/q/50686742
linked to: http://stackoverflow.com/q/17686596
has title: Function that modifies an argument outside that function without using "return" python
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88384220
type: Question
duplicate of: http://stackoverflow.com/q/17686596
tagged with: numpy
has body: I use python 2.7. Say I have an array X and a function that centers this array according to means : import numpy as np X = np.array([[float(i+j) for i in range(3)] for j in range(3)]) If we print X at this point X = array([[ 0., 1., 2.], [ 1., 2., 3.], [ 2., 3., 4.]]) Now let's compute the mean (according to each column) and write the function that centers each X[i,j] according to the j-th column's mean. means = X.means(axis=0) #mean for each column We print means = array([ 1., 2., 3.]) (seem's legit). def center(arr, means) : for i, mean in enumerate(means) : arr[:, i] -= mean # Instructions # end of the function without return X or something Let' call this function on X : center(X), and print again X, one will have : X = array([[-1., -1., -1.], [ 0., 0., 0.], [ 1., 1., 1.]]) So, X is modified whereas it shouldn't be since it is not returned. My question is twofold : 1-How come X is modified outside the function whereas I don't return it 2- Is there something to do to avoid that modification that can lead to big confusion The solution I found is to np.copy the arr before the for loop, (inside the center function), and deal with the copy to keep X as it is. Note that this problem doesn't arise when dealing with int or float. PS : I suppose that the problem rely on how the arrays are stored and the way broadcasting is made in Python but I believe there is a way to get a better grip on it Thanks for your time
has comment: http://stackoverflow.com/comment/88385979
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/88383637

http://stackoverflow.com/comment/88104106
type: AnswerComment
type: Comment
has text: Is that maybe because the "While" is still true?
comment on: http://stackoverflow.com/a/50546644
score: 0

http://stackoverflow.com/q/50668209
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50669389
tagged with: web-scraping
tagged with: scrapy
type: Question
has title: Why does my Scrapy spider only scrape some of my data?
accepted answer: http://stackoverflow.com/a/50669389
answer count: 1
score: 0
has body: I'm trying to use Scrapy to scrape IMDb data (episode information and cast list) for each episode of Law &amp; Order: SVU. After I run the code below, I export it to CSV via the command line with "scrapy crawl svu -o svu.csv". The code below successfully pulls episode information, but the CSV does not contain the cast list. How do I fix the code to extract and export both the episode information and the cast list? My thoughts &amp; attempts: I believe that the cast list is extracted because it is visible in the terminal when the spider runs, so it may be an export issue. If I comment out my first Yield statement (episode information), the cast list is successfully exported. This makes me think it isn't just an export issue. Thanks for the help! import scrapy class SvuSpider(scrapy.Spider): name = "svu" start_urls = [ 'https://www.imdb.com/title/tt0629700/?ref_=ttep_ep1' ] def parse(self, response): # Gather episode information yield { 'season': response.xpath("//div[@class='bp_heading']/text()")[0].extract(), 'episode': response.xpath("//div[@class='bp_heading']/text()")[1].extract(), 'episode_name': response.xpath("//h1[@itemprop='name']/text()").extract_first().strip(), 'date_published': response.xpath("//div[@class='subtext']/a/meta[@itemprop='datePublished']/@content").extract(), 'rating_value': response.xpath("//span[@itemprop='ratingValue']/text()").extract(), 'rating_count': response.xpath("//span[@itemprop='ratingCount']/text()").extract() } # Follow link to full cast list for a in response.xpath("//div[@class='see-more']/a"): yield response.follow(a, callback=self.parse_cast) # Follow link to next episode for a in response.xpath("//a[@class='bp_item np_next']"): yield response.follow(a, callback=self.parse) def parse_cast(self,response): # Gather cast list data for actor in response.xpath("//table[@class='cast_list']"): yield { 'actor': response.xpath("//td[@itemprop='actor']/a/span[@itemprop='name']/text()").extract(), 'character': response.xpath("//td[@cl…
tagged with: python

http://stackoverflow.com/q/50556604
upvote count: 3
has answer: http://stackoverflow.com/a/50557881
answer count: 3
has body: How can a docx table be indented? I am trying to line a table up with a tab stop set at 2cm. The following script creates a header, some text and a table: import docx from docx.shared import Cm doc = docx.Document() style = doc.styles['Normal'] style.paragraph_format.tab_stops.add_tab_stop(Cm(2)) doc.add_paragraph('My header', style='Heading 1') doc.add_paragraph('\tText is tabbed') # This indents the paragraph inside, not the table # style = doc.styles['Table Grid'] # style.paragraph_format.left_indent = Cm(2) table = doc.add_table(rows=0, cols=2, style="Table Grid") for rowy in range(1, 5): row_cells = table.add_row().cells row_cells[0].text = 'Row {}'.format(rowy) row_cells[0].width = Cm(5) row_cells[1].text = '' row_cells[1].width = Cm(1.2) doc.save('output.docx') It produces a table with no ident as follows: How can the table be indented as follows? (preferably without having to load an existing document): If for example left-indent is added to the Table Grid style (by uncommenting the lines), it will be applied at the paragraph level, not the table level resulting in the following (which is not wanted): In Microsoft Word, this can be done on the table properties by entering 2.0 cm for Indent from left.
has answer: http://stackoverflow.com/a/54699631
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/50557881
downvote count: 0
type: Question
tagged with: python-docx
has answer: http://stackoverflow.com/a/55142896
accepted answer: http://stackoverflow.com/a/55142896
has title: Using Python's docx library, how can a table be indented?

header
tags question: http://stackoverflow.com/q/50687489
type: Tag
tag name: header
tags question: http://stackoverflow.com/q/50547464

http://stackoverflow.com/q/50554405
has body: The nth comment get removed and the nth username is checked in other comments, and if the nth username is not in all comments(nth comment is already removed) it will be passed/appended in warn_usernames and afterward, the nth comment gets again added in the comments. Cycle continues usernames = ["a", "b", "c"] warn_usernames = [] comments = [["b"], ["a", "c"], ["a", "b"]] n = 0 while n &lt; len(usernames): commente = comments[n] print(commente) usernamee = usernames[n] print(usernamee) comments.pop(n) if str(usernamee) not in str(comments): warn_usernames.append(usernamee) comments.insert(n, commente) n = n + 1 print(warn_usernames) result I get [] result I expect to get [c] Thanks in advance, and I hope you got my question.
downvote count: 2
has comment: http://stackoverflow.com/comment/88121096
has comment: http://stackoverflow.com/comment/88120395
has comment: http://stackoverflow.com/comment/88119807
type: Question
has title: Append and Remove to check if the text is in the list
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/88119909
has comment: http://stackoverflow.com/comment/88120680
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/88120368
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88119831
tagged with: python
has answer: http://stackoverflow.com/a/50556952
tagged with: append
tagged with: list

http://stackoverflow.com/comment/88405005
score: 1
type: AnswerComment
type: Comment
has text: Change the regex to `(?:^|\n|\. )(?=[A-Z])(.*\.)` in that case, see [this demo](https://regex101.com/r/VmW2oY/1).
comment on: http://stackoverflow.com/a/50659354

http://stackoverflow.com/comment/88113632
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50551356
has text: What happens if you set `num_cores = 1`?

http://stackoverflow.com/comment/88203688
type: QuestionComment
has text: @AnttiHaapala there _is_ a python solution and it looks very much like the most upvoted one here: https://stackoverflow.com/a/1851138/6451573. Sounds like a duplicate to me.
type: Comment
comment on: http://stackoverflow.com/q/50592576
score: 0

http://stackoverflow.com/q/50640978
has body: How can I copy with openpyxl the rule(conditional formatting) from an excel cell to another one(without knowing the rule in advance)? Or alternatively, how can I retrieve the rule of a cell and set it to a new one? Thanks
type: Question
has title: Copy rule of excel cell with openpyxl
tagged with: python
tagged with: excel
tagged with: rule
upvote count: 3
tagged with: openpyxl
tagged with: conditional-formatting
downvote count: 1
answer count: 0
type: UnansweredQuestion
score: 2
favorite count: 0

http://stackoverflow.com/q/50551692
tagged with: python-3.x
tagged with: python
has body: I have this code which reduces a color to a minimal amount of colors to help identify what it is; it was working earlier, but now it says ValueError: x must consist of vectors of length 3 but has shape (480, 640, 4) Like I said it was working earlier, but then I tried adding 'white' because white turns to yellow and now it doesn't work at all import numpy as np from matplotlib import colors from scipy.spatial import cKDTree as KDTree from scipy.misc import face from PIL import Image REDUCED_COLOR_SPACE = True # borrow a list of named colors from matplotlib if REDUCED_COLOR_SPACE: use_colors = {k: colors.cnames[k] for k in ['red', 'green', 'blue', 'black', 'yellow', 'purple']} else: use_colors = colors.cnames # translate hexstring to RGB tuple named_colors = {k: tuple(map(int, (v[1:3], v[3:5], v[5:7]), 3*(16,))) for k, v in use_colors.items()} ncol = len(named_colors) if REDUCED_COLOR_SPACE: ncol -= 1 no_match = named_colors.pop('purple') else: no_match = named_colors['purple'] # make an array containing the RGB values color_tuples = list(named_colors.values()) color_tuples.append(no_match) color_tuples = np.array(color_tuples) color_names = list(named_colors) color_names.append('no match') # get example picture img = Image.open('apple.png') # build tree tree = KDTree(color_tuples[:-1]) # tolerance for color match `inf` means use best match no matter how # bad it may be tolerance = np.inf # find closest color in tree for each pixel in picture dist, idx = tree.query(img, distance_upper_bound=tolerance) # count and reattach names counts = dict(zip(color_names, np.bincount(idx.ravel(), None, ncol+1))) print(counts) import pylab pylab.imshow(img) pylab.savefig('apple.png') pylab.clf() pylab.imshow(color_tuples[idx]) pylab.savefig('minimal.png' if REDUCED_COLOR_SPACE else 'reduced.png') It did work before: And it did work after: The problem is: When I run it, I get this error 'line 45, in dist, idx = tree.query(img, distance_upper_bound=tolerance) File "ckdtree.pyx", line…
has comment: http://stackoverflow.com/comment/88114314
downvote count: 1
type: AnsweredQuestion
tagged with: matplotlib
score: -1
type: Question
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50553917
has title: ValueError: x must consist of vectors of length 3 but has shape (480, 640, 4)
accepted answer: http://stackoverflow.com/a/50553917
has comment: http://stackoverflow.com/comment/88114902
favorite count: 0

http://stackoverflow.com/comment/134468723
type: Comment
comment on: http://stackoverflow.com/a/60313656
score: 0
type: AnswerComment
has text: This works, but is giving a `SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame...`

http://stackoverflow.com/comment/88169247
score: 1
comment on: http://stackoverflow.com/a/50579829
type: AnswerComment
has text: I think here you need to put `.get` in your print statement, without it it doesn't work: `print(os.environ.get['test_var'])`
type: Comment

http://stackoverflow.com/comment/88297818
has text: Try the link https://developers.google.com/youtube/v3/guides/uploading_a_video It has a sample python script with the usage guidelines.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50643701

http://stackoverflow.com/q/50674419
has comment: http://stackoverflow.com/comment/88359556
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50675124
has comment: http://stackoverflow.com/comment/88359193
has answer: http://stackoverflow.com/a/50675124
type: Question
answer count: 3
has answer: http://stackoverflow.com/a/57844130
accepted answer: http://stackoverflow.com/a/50675110
has body: enter image description here I have a problem that I am working on Django tutorial and I want to take it in my browser at /polls/34/ but I don't know how to do that It will refuse from localhost when I try to put in browser I use python3 and django 2.0 Django tutorial gave this Take a look in your browser, at “/polls/34/”. It’ll run the detail() method and display whatever ID you provide in the URL. Try “/polls/34/results/” and “/polls/34/vote/” too – these will display the placeholder results and voting pages but I can't load that Please Suugests and check below code mysite/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] mysite/polls/urls.py from django.urls import path from . import views urlpatterns = [ # ex: /polls/ path('', views.index, name='index'), # ex: /polls/5/ path('&lt;int:question_id&gt;/', views.detail, name='detail'), # ex: /polls/5/results/ path('&lt;int:question_id&gt;/results/', views.results, name='results'), # ex: /polls/5/vote/ path('&lt;int:question_id&gt;/vote/', views.vote, name='vote'), ] mysite/polls/views.py from django.http import HttpResponse def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id)
score: 0
tagged with: django
tagged with: python
has title: Django tutorial error part3
has answer: http://stackoverflow.com/a/50675110
has comment: http://stackoverflow.com/comment/88358724

http://stackoverflow.com/comment/88162216
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50576329
has text: It is precisely the fact that there is no overlap here that makes the in-place optimization a possibility. The time when the name `mystring` is re-bound is the same instant the old `mystring` ceases to have a reference. Keep another reference to the old and you won't see the optimization anymore!

http://stackoverflow.com/q/50611581
has body: I can't import Flask 1.0 or run the development server all of a sudden. Traceback (most recent call last): File "/data/data/ru.iiec.pydroid3/files/accomp_files/iiec_hackrun/iiec_hackrun.py", line 29, in &lt;module&gt; start(fakepyfile,mainpyfile) File "/data/data/ru.iiec.pydroid3/files/accomp_files/iiec_hackrun/iiec_hackrun.py", line 28, in start exec(open(mainpyfile).read(), __main__.__dict__) File "&lt;string&gt;", line 6, in &lt;module&gt; File "/data/data/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.6/site-packages/flask/__init__.py", line 21, in &lt;module&gt; from .app import Flask, Request, Response File "/data/data/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.6/site-packages/flask/app.py", line 25, in &lt;module&gt; from . import cli, json File "/data/data/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.6/site-packages/flask/json/__init__.py", line 21, in &lt;module&gt; from itsdangerous import json as _json File "/data/data/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.6/site-packages/itsdangerous.py", line 38, in &lt;module&gt; import simplejson as json File "/data/data/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.6/site-packages/simplejson/__init__.py", line 115, in &lt;module&gt; from .encoder import JSONEncoder, JSONEncoderForHTML File "/data/data/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.6/site-packages/simplejson/encoder.py", line 15, in &lt;module&gt; c_encode_basestring_ascii, c_make_encoder = _import_speedups() File "/data/data/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.6/site-packages/simplejson/encoder.py", line 12, in _import_speedups return _speedups.encode_basestring_ascii, _speedups.make_encoder AttributeError: module 'markupsafe._speedups' has no attribute 'encode_basestring_ascii'
has answer: http://stackoverflow.com/a/50620790
type: Question
upvote count: 0
score: -2
tagged with: flask
answer count: 1
has title: Flask attribute error
favorite count: 0
type: UnansweredQuestion
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/88233670
has comment: http://stackoverflow.com/comment/88233481

http://stackoverflow.com/q/50607838
type: Question
has comment: http://stackoverflow.com/comment/88240323
downvote count: 0
tagged with: http://stackoverflow.com/tag/r
tagged with: rest
has body: I am looking to expose a couple of machine learning algorithms as REST APIs to integrate them into product loop. These are written in R and Python, I am trying to achieve the following: Should be easy to deploy and run Should be able to handle the load on production with high throughput Should be easily maintainable as machine learning team won't have much exposure on API aspect of the applications I have had a brief look at the frameworks like Flask, rApache, rServe, OpenCPU, Plumber, however, these sound like not built for production (maybe I am wrong). I am not familiar with Python or r so don't know much about concurrency/threading aspect of these, in this case: Is this the correct way to expose the service (i.e. with these wrappers) Can I write something in Java and call the r script from command line or shell? Is that an option or it will create a tight coupling? Should I ditch the idea of exposing it as a REST service and look into RPC or cloud functions?
tagged with: python
favorite count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/88508739
upvote count: 2
type: UnansweredQuestion
tagged with: production-environment
tagged with: web-services
score: 2
has title: Exposing R and Python scripts via Web Service

http://stackoverflow.com/q/50655959
type: Question
upvote count: 4
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88321951
score: 4
has title: python "in" operator reflected magic method
has answer: http://stackoverflow.com/a/50656314
tagged with: python
favorite count: 0
has body: | operator has two magic methods, normal and reflected. # object + other __or__(self, other) # Implements bitwise or using the | operator. # other + object __ror__(self, other) # Implements reflected bitwise or using the | operator. in operator only has one magic method. # item in object __contains__(self, item) # __contains__ defines behavior for membership tests using in and not in. How can I implement in operator reflected magic method? # object in sequence __rcontains__(self, sequence): # defines behavior for self in or not in sequence It will be useful when you want to implement sql conditions class Field(object): def __lt__(self, other): return '&lt;', self._value, other Model.objects.filter(Field('a') &gt; 1) Model.objects.filter(Field('a') in [1, 2, 3, 4])
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88322199
has comment: http://stackoverflow.com/comment/88322268

http://stackoverflow.com/comment/88304784
type: QuestionComment
has text: did you also run migrate?
type: Comment
comment on: http://stackoverflow.com/q/50647108
score: 0

http://stackoverflow.com/q/50551776
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/50551959
answer count: 2
upvote count: 1
has body: I want to create chunks out of an array under certain conditions. Lets say I want all chunks that are not null. array = np.random.randint(2, size=10) # array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0]) out = chunks(array) # array([[0,[1]],[4,[1, 1]],[8,[1]]) Now i know that the first chunk starts a index 0 and contains [1] 0: 0 -&gt; [1] 1: 4 -&gt; [1,1] 2: 8 -&gt; [1] It does not have to look like this, but I did not know any better. So far, I have done it with for loops. But every time I look my code, it depresses me :). Is There any better way (Numpy magic)?
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88114661
has answer: http://stackoverflow.com/a/50551959
downvote count: 0
has comment: http://stackoverflow.com/comment/88114514
has title: Python chunk array on condition
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50551924
accepted answer: http://stackoverflow.com/a/50551924
score: 1

http://stackoverflow.com/comment/88271077
type: Comment
type: QuestionComment
has text: You could just match then remove the escapes later `(?m)^(\d{6})([^\S\r\n]*)(\#.*)` via callback
comment on: http://stackoverflow.com/q/50630388
score: 0

http://stackoverflow.com/comment/88256409
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50622088
score: 0
has text: for n ranging 100 i checked this form 100 to 1000 i did approximation check

http://stackoverflow.com/comment/88138092
type: Comment
score: 0
has text: @Andrea Foderaro Please accept the answer. It does work for you.
type: AnswerComment
comment on: http://stackoverflow.com/a/50563919

http://stackoverflow.com/q/50602212
has title: Hiding of figures instead of overlapping
has comment: http://stackoverflow.com/comment/88215208
tagged with: sensors
tagged with: tkinter
has comment: http://stackoverflow.com/comment/88217940
has body: I have a function that should simulate a sensor. For this task I have implemented a function that reads the mouse-click and puts a little Circle in the Frame. With a Button I start then the simulated growing of a sensor wave with this function: import matplotlib.pyplot as plt import matplotlib import math import numpy as np import time matplotlib.use('TkAgg') from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk from matplotlib.backend_bases import key_press_handler import sys if sys.version_info[0] &lt; 3: import Tkinter as Tk else: import tkinter as Tk root = Tk.Tk() root.wm_title("Localization") x = [0. , 100.] y = [0. , 100.] fig1 = plt.figure() ax1 = fig1.add_subplot(111, aspect='equal') ax1.axis([min(x), max(x), min(y), max(y)]) # a tk.DrawingArea canvas1 = FigureCanvasTkAgg(fig1, master=root) canvas1.draw() canvas1.get_tk_widget().pack(side=Tk.LEFT, fill=Tk.X, expand=1) toolbar = NavigationToolbar2Tk(canvas1, root) toolbar.update() canvas1._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) coords = [] distanceToMid = [] timer = [] def onclick(event): counter = 0 if event.button: print('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (event.button, event.x, event.y, event.xdata, event.ydata)) plt.plot(event.xdata, event.ydata, ',') #right click sets the black node circles if (event.button == 3 and counter &lt; 9): ix,iy = event.xdata, event.ydata coords.append((ix,iy)) circle = plt.Circle((event.xdata,event.ydata), 0.5, color='black', alpha=1) ax1.add_artist(circle) fig1.canvas.draw() counter += 1 #double-click imitates the wave from the middle if event.dblclick: for i in range(1, 72): circle_mid = plt.Circle((50,50), i ,color='red', alpha=1, fill=1) ax1.add_artist(circle_mid) fig1.canvas.draw() circle_clear = plt.Circle((50,50), 72, color="white", alpha=1, fill=1) ax1.add_artist(circle_clear) for j in range(0,len(coords)): circle_loc = plt.Circle(coords[j],0.5,color="black", alpha=1, fill=1) ax1.add_artist(circle_loc) fig1.canvas…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88216105
tagged with: pip
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/88215069
has comment: http://stackoverflow.com/comment/88221539
tagged with: matplotlib
type: Question
has comment: http://stackoverflow.com/comment/88215097
score: 0

http://stackoverflow.com/a/50688406
accepted answer of: http://stackoverflow.com/q/50687912
answers question: http://stackoverflow.com/q/50687912
has body: The c argument of scatter expects either a single color specifier (e.g. 'blue') or a series of color specifiers (e.g. ['blue', 'red', ...]) or a series of numbers that are mapped using the colormap (e.g. [1, 2, 3, 4, ...], as you used it here). However, in your commented-out case, the series you provide is not matchable to your data, so scatter doesn't know what to do with it. What do you want to do with it? You might e.g. try height1 = np.arange(len(x1)) sc=plt.scatter(x1, y1, c=height1, vmin=np.min(height1)-0.5, vmax=np.max(height1)+0.5, marker='o', s=40, cmap=plt.cm.get_cmap('jet', len(height))) Edit: The way this works is as follows: Every data point (x, y) is associated with an element in c, that is c[i] is assigned to the marker at (x[i], y[i]). This is why c, x and y all have to have the same length, otherwise the matching doesn't work. NaN values in c will not help here. However, your values in c are only converted to colors using the colormap you specififed. And the range of the colormap is determined by vmin and vmax. So, to make sure your color use the same data range for all your data sets, just precompute vmin and vmax prior to plotting using all data and set it accordingly. So in your case: h1 = np.arange(len(x1)) h2 = np.arange(len(x2)) minval = min([np.min(h) for h in [h1, h2]]) maxval = max([np.max(h) for h in [h1, h2]]) nh = len(np.arange(minval, maxval+1, 1)) and then sc=plt.scatter(x1, y1, c=h1, marker='o', s=40, vmin=minval-0.5, vmax=maxval+0.5, cmap=plt.cm.get_cmap('jet', nh) ) and for the colorbar cbar=plt.colorbar(sc, cax=cax, ticks=np.arange(minval, maxval+1,1.0))
upvote count: 2
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/88653211
has comment: http://stackoverflow.com/comment/88418905
score: 2
downvote count: 0

http://stackoverflow.com/q/50644615
answer count: 1
accepted answer: http://stackoverflow.com/a/50644903
tagged with: pandas
tagged with: python
type: AnsweredQuestion
has title: Grouping items before a certain date
has answer: http://stackoverflow.com/a/50644903
type: Question
score: 0
has body: I have the following dataframes: import pandas as pd from io import StringIO data = StringIO("""TitleCode,ReleaseDate,WeekEnding,TotalUnits A,12/16/2017,12/2/2017 0:00,5 A,12/16/2017,12/9/2017 0:00,10 A,12/16/2017,12/16/2017 0:00,2 A,12/16/2017,12/23/2017 0:00,5 A,12/16/2017,12/30/2017 0:00,4 B,1/6/2018,1/13/2017 0:00,4 B,1/6/2018,1/20/2017 0:00,2 """) result = StringIO("""TitleCode,ReleaseDate,WeekEnding,TotalUnits A,12/16/2017,12/16/2017 0:00,17 A,12/16/2017,12/23/2017 0:00,5 A,12/16/2017,12/30/2017 0:00,4 B,1/6/2018,1/13/2017 0:00,4 B,1/6/2018,1/13/2017 0:00,2 """) datadf = pd.read_csv(data, parse_dates=True) resultdf = pd.read_csv(result, parse_dates=True) datadf TitleCode ReleaseDate WeekEnding TotalUnits 0 A 12/16/2017 12/2/2017 0:00 5 1 A 12/16/2017 12/9/2017 0:00 10 2 A 12/16/2017 12/16/2017 0:00 2 3 A 12/16/2017 12/23/2017 0:00 5 4 A 12/16/2017 12/30/2017 0:00 4 5 B 1/6/2018 1/13/2017 0:00 4 6 B 1/6/2018 1/13/2017 0:00 2 resultdf TitleCode ReleaseDate WeekEnding TotalUnits 0 A 12/16/2017 12/16/2017 0:00 17 1 A 12/16/2017 12/23/2017 0:00 5 2 A 12/16/2017 12/30/2017 0:00 4 3 B 1/6/2018 1/13/2017 0:00 4 4 B 1/6/2018 1/20/2017 0:00 2 The datadf dataframe shows item sales by week, and the release date of the item. I want to group together all pre-sell sales, that is, sales that occur before the release date (resultdf). The only way I can think of doing it is by looping over the dataframe but there must be a more efficient way of doing this. Thanks!

http://stackoverflow.com/comment/88204545
has text: Thanks for your answer Ehsan, Your answer was useful too
type: AnswerComment
comment on: http://stackoverflow.com/a/50569711
type: Comment
score: 1

http://stackoverflow.com/a/50680515
answers question: http://stackoverflow.com/q/50678665
accepted answer of: http://stackoverflow.com/q/50678665
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: One solution might be using os library with for loop import os import textract files_path = [os.path.abspath(x) for x in os.listdir()] # Excluding not .pdf files files_path = [pdf for pdf in files_path if '.pdf' in pdf] pdfs = [] for file in files_path: text = textract.process(file, method='tesseract', language='eng') pdfs += [text] Get all files in the current directory Exclude not .pdf files Save the text into a list (could be different data structure)
score: 3
upvote count: 3

http://stackoverflow.com/comment/88253165
has text: Hope my edition doesn't misunderstand what you mean.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50621387

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/50595638
tags question: http://stackoverflow.com/q/50658408
tags question: http://stackoverflow.com/q/50605055
tags question: http://stackoverflow.com/q/50631375
tags question: http://stackoverflow.com/q/50591411
type: Tag
tags question: http://stackoverflow.com/q/50546852
tags question: http://stackoverflow.com/q/50553201
tags question: http://stackoverflow.com/q/50690966
tags question: http://stackoverflow.com/q/50551356
tags question: http://stackoverflow.com/q/50584217
tags question: http://stackoverflow.com/q/50670158
tags question: http://stackoverflow.com/q/50668416
tags question: http://stackoverflow.com/q/50555973
tags question: http://stackoverflow.com/q/50555566
tags question: http://stackoverflow.com/q/50591637

http://stackoverflow.com/q/50640687
has answer: http://stackoverflow.com/a/50640931
has body: I am relatively new in machine learning especially when it comes to implementing algorithms. I am using python and tensorflow library to implement a neural network to train on a dataset which has about 20 classes. I am able to train and get predictions successfully but I have a question, Is it possible to get top k classes along with their probabilities using tensorflow instead of just a single prediction? If it is possible how can this be done? Thanks for your guidance. Update 01: I am adding code of what I am doing. So I build a neural network with 3 layers having tanh, sigmoid, &amp; sigmoid respectively as activation functions for the hidden layers and softmax for output layer. The code for training and prediction is as follows: y_pred = None with tf.Session() as sess: sess.run(init) for epoch in range(training_epochs): # running the training_epoch numbered epoch _,cost = sess.run([optimizer,cost_function],feed_dict={X:tr_features,Y:tr_labels}) cost_history = np.append(cost_history,cost) # predict results based on the trained model y_pred = sess.run(tf.argmax(y_,1),feed_dict={X: ts_features}) Right now y_pred is a list of class labels for each test example of ts_features. But instead of getting 1 single class label for each test example I am hoping to get top-k predictions for each example each of the k-predictions accompanied by some kind of probability.
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/50640931
tagged with: python
type: AnsweredQuestion
upvote count: 3
tagged with: tensorflow
type: Question
score: 3
has title: Get top-k predictions from tensorflow

http://stackoverflow.com/comment/88398797
has text: @coldspeed - Check last NOTE
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50694694
type: Comment

http://stackoverflow.com/q/50569041
duplicate of: http://stackoverflow.com/q/11007627
has body: I want the following code to run the defined function, and save the output of the defined function in the specified variable "functionsOutput". And then, I want to replace the new lines in the variable with spaces. But my code below isn't doing that. What am i doing wrong? The assignment of the function output to a variable is printing out the output. I don't want that. I want the output stored in the variable. #!/usr/bin/python2.7 mylist = [ "hello", "you", "are", "so", "cool" ] def printWithoutNewlines(): for objects in mylist: objects = objects.replace('hello', "hi") print objects functionsOutput = printWithoutNewlines() functionsOutput.replace('\n', ' ')
type: Question
has title: Python function printing output during variable assignment
answer count: 3
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/88148461
has comment: http://stackoverflow.com/comment/88148007
favorite count: 0
has answer: http://stackoverflow.com/a/50569208
has comment: http://stackoverflow.com/comment/88147962
has answer: http://stackoverflow.com/a/50569119
has answer: http://stackoverflow.com/a/50569111
tagged with: python
linked to: http://stackoverflow.com/q/11007627
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/q/50603543
has title: python reading numbers from xlsx as different types
answer count: 0
has comment: http://stackoverflow.com/comment/88226596
tagged with: openpyxl
tagged with: excel
type: Question
score: 0
has body: I have Python reading the following xlsx. What I noticed when I run the code again on the a similar xlsx but located in a different directory the types of numbers change. I tried to format the cells in xlsx so they are the same but it doesn't seem to work. On the first xlsx I see the value in B1 as long and B15 as float, but in the second xlsx i see them as numpy.float64. from openpyxl import load_workbook import pandas as pd import xlrd import string as st from string import ascii_uppercase # allows creation of Excel "A1" reference import numpy as np #address_1='C:/Users/user/Desktop/target/new version/xlsx/new colour.xlsx'#new version/xlsx/new colour.xlsx' address_1='C:/Users/user/Desktop/target/new/xlsx/colour.xlsx' book_formula = load_workbook(address_1,data_only=False)# location of file book = load_workbook(address_1,data_only=True)# location of file l = list(st.ascii_uppercase) + [letter1 + letter2 for letter1 in ascii_uppercase for letter2 in ascii_uppercase] #reference data i.e. = sheets_formula = book_formula.get_sheet_names() name = [] ref_equal_dup = [] ref_cell_dup = [] # this has duplicates this goes through each worksheet to get the cells in each index_1 = 0 def equal(): ref_equal_dup.append(str('=') + l[col] + str(row+1)) ref_equal_dup.append(str('=') + l[col] + '$' + str(row+1)) ref_equal_dup.append(str('=') + '$' + l[col] + '$' + str(row+1)) ref_equal_dup.append(str('=') + '$' + l[col] + str(row+1)) def cell(): ref_cell_dup.append( l[col] + str(row+1)) ref_cell_dup.append( l[col] + '$' + str(row+1)) ref_cell_dup.append( '$' + l[col] + '$' + str(row+1)) ref_cell_dup.append( '$' + l[col] + str(row+1)) while index_1 &lt;len(sheets_formula): name.append((str('=') + str(sheets_formula[index_1]) + str('!'))) df = pd.DataFrame(book_formula[(sheets_formula[index_1])].values) rows, cols = len(df.index) - 1, len(df.columns) - 1 for col in range(cols): for row in range(rows): equal() cell() index_1 = index_1 + 1 # removes the dup from ref_cell_dup and ref_equa…
has comment: http://stackoverflow.com/comment/88250574
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/88218305
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50593550
has text: @abarnert, more specifically, the `multiprocessing` module gives me a pickling error, that's why I switched to the other library (as it uses dill)

http://stackoverflow.com/a/50612280
answers question: http://stackoverflow.com/q/50609312
score: 0
type: Answer
has body: Below , I show another example, avoiding importing or saving a file, but is almost the same problem, when I print(df): for n in range(40): print(n) a = repr(n) Here, I get 40 numbers in variable "a" print(a) import pandas as pd df = pd.DataFrame.from_records(a) df.columns = 'number' Here, almost 40 number that I got desappear and only get the last number (39) and unformatted (or split in 2 differents cases) print(df)

http://stackoverflow.com/comment/88136147
has text: @jezrael I don't seem to experience that bug with `0.20.3`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50562606
score: 0

http://stackoverflow.com/q/50688673
answer count: 1
has body: I'm very new to Python and am learning how packages and modules work but have run into a snag. Initially I created a very simple package to be deployed as a Lambda function. I have a file in the root directory called lambda.py which contains a handler function, and I put most of my business logic in a separate file. I created a subdirectory - for this example let's say it's called testme - and more specifically put it in __init__.py underneath that subdirectory. Initially this worked great. Inside my lambda.py file I could use this import statement: from testme import TestThing # TestThing is the name of the class However, now that the code is growing, I've been splitting things into multiple files. As a result, my code no longer runs; I get the following error: TypeError: 'module' object is not callable Here's a simplified version of what my code looks like now, to illustrate the problem. What am I missing? What can I do to make these modules "callable"? /lambda.py: #!/usr/bin/env python2 # -*- coding: utf-8 -*- from testme import TestThing def handler(event, context): abc = TestThing(event.get('value')) abc.show_value() if __name__ == '__main__': handler({'value': 5}, None) /testme/__init__.py: #!/usr/bin/env python2 # -*- coding: utf-8 -*- __project__ = "testme" __version__ = "0.1.0" __description__ = "Test MCVE" __url__ = "https://stackoverflow.com" __author__ = "soapergem" __all__ = ["TestThing"] /testme/TestThing.py: #!/usr/bin/env python2 # -*- coding: utf-8 -*- class TestThing: def __init__(self, value): self.value = value def show_value(self): print 'The value is %s' % self.value Like I said, the reason I'm doing all this is because the real world example has enough code that I want to split it into multiple files inside the subdirectory. And so I left an __init__.py file there to just to serve as an index essentially. But I am very unsure of what the best practices are for package structure, or how to get this working.
accepted answer: http://stackoverflow.com/a/50688718
tagged with: python
has title: How do I structure a package so that its modules are callable?
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/50688718
score: 0

http://stackoverflow.com/comment/88160368
type: QuestionComment
comment on: http://stackoverflow.com/q/50573209
has text: I assume you meant "as being ingested". Maybe you're misunderstanding that Dataframe operations are lazy? No computations are performed until an action. In other words, 3 filter operations after "reading" the file (as a stream) is not inefficient. And that's the only way to do what you want... In other words, are you able to get any dataframe? Have you been able to split the rows into columns?
score: 0
type: Comment

http://stackoverflow.com/a/70526550
has comment: http://stackoverflow.com/comment/124672632
has body: Maybe this will help you. I managed to use ChromeDriver version 96.0.4664.45 editing in JUPYTER, I was using Pycharm before and it didn't respond.
type: Answer
answers question: http://stackoverflow.com/q/50692358
score: 0

macos
tags question: http://stackoverflow.com/q/50686096
tags question: http://stackoverflow.com/q/50639973
tags question: http://stackoverflow.com/q/50562698
tags question: http://stackoverflow.com/q/50653103
tags question: http://stackoverflow.com/q/50623283
tags question: http://stackoverflow.com/q/50566848
tags question: http://stackoverflow.com/q/50595980
tags question: http://stackoverflow.com/q/50635811
tags question: http://stackoverflow.com/q/50690141
tags question: http://stackoverflow.com/q/50640716
tags question: http://stackoverflow.com/q/50677265
tags question: http://stackoverflow.com/q/50551198
tags question: http://stackoverflow.com/q/50687324
tags question: http://stackoverflow.com/q/50629482
type: Tag
tags question: http://stackoverflow.com/q/50602088
tag name: macos
tags question: http://stackoverflow.com/q/50673522
tags question: http://stackoverflow.com/q/50636155
tags question: http://stackoverflow.com/q/50563950

http://stackoverflow.com/comment/88310595
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50642269
type: AnswerComment
has text: then the problem is not in QV

http://stackoverflow.com/a/50542870
type: Answer
score: 2
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/50542815
has body: You are creating so called one-hot vector (each row in matrix is a one-hot vector meaning that only one value is True). mylist = [0, 3, 2, 1, 1, 2] one_hot = np.zeros((len(mylist), 4), dtype=np.bool) for i, v in enumerate(mylist): one_hot[i, v] = True Output array([[ True, False, False, False], [False, False, False, True], [False, False, True, False], [False, True, False, False], [False, True, False, False], [False, False, True, False]], dtype=bool)

http://stackoverflow.com/comment/113607752
has text: [This stackoverflow answer](https://stackoverflow.com/a/39814710/2992902) resolved my issue in Windows 10 using Powershell
comment on: http://stackoverflow.com/q/50673632
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88275180
comment on: http://stackoverflow.com/a/50632272
type: AnswerComment
score: 0
type: Comment
has text: don't remove it. Just edit the last part out. My secret technique is "never read question titles" :)

http://stackoverflow.com/a/50620094
answers question: http://stackoverflow.com/q/50619974
has body: Your code is wrong because /n cannot be converted to int as it is not a numerical character. Try this: data=f.readlines() data_int = [] for item in data: data_int.append(int(item)) a = np.array(data_int) yvec1 = a.astype(int) print(yvec1)
score: 0
has comment: http://stackoverflow.com/comment/88249915
type: Answer

http://stackoverflow.com/comment/88453495
comment on: http://stackoverflow.com/q/50630280
score: 0
type: Comment
type: QuestionComment
has text: I might be wrong, but I feel if a python script can't handle the memory your data uses all at once, excel might have an even bigger problem...

http://stackoverflow.com/a/50599614
upvote count: 1
has body: For a Sandbox environment like yours, a sandbox image is made on a Linux OS (CentOS). The Zeppelin Notebook points, in all probability, to the Python installation that comes along with every Linux OS. If you wish to have your own installation of Python and your own set of libraries for Data Analysis like those in the SciPy stack. You need to install Anaconda on your Virtual machine. Your VM eed to be connected to the internet so that you can download and install the Anaconda package for testing. You can then point Zeppelin to the anaconda's directory till the following path : /home/user/anaconda3/bin/python where user is your username Zeppelin Configuration also confirms the fact that it uses the default python installation at /usr/bin/python. You can go through its documentation for more Information UPDATE Hi Joseph, Spark Installations, by default, use the Python interpreter and the python libraries that have been installed on your OS. The folder structure that you have shown only tell you the location of the PySpark module. This module is a library like Pandas ior NumPy. What you can do is install the SciPy Stack[NumPy, Pandas, MatplotLib etc..] via the command pip install package name and import those libraries directly into your Zeppelin Notebook. Use the command whereis python in the terminal of your snadbox, the result would give you something as follows /usr/bin/python /usr/bin/python2.7 .... In your Zeppelin Configuration, for the property zeppelin.pyspark.python you can set the first value from the out put of the previous command i.e /usr/bin/python. So now all the libraries you installed via the pip install command would be available for you in zeppelin. This process would only work for your Sandbox environment. In a real production cluster, your administrator needs to install all these libraries on all the nodes of your Spark cluster.
answers question: http://stackoverflow.com/q/50599469
has comment: http://stackoverflow.com/comment/88213130
score: 1
has comment: http://stackoverflow.com/comment/88220007
has comment: http://stackoverflow.com/comment/88213210
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50599469
has comment: http://stackoverflow.com/comment/88210273
type: Answer
has comment: http://stackoverflow.com/comment/88209126
has comment: http://stackoverflow.com/comment/88213308
has comment: http://stackoverflow.com/comment/88216981
has comment: http://stackoverflow.com/comment/88219627

http://stackoverflow.com/a/74448288
score: 0
type: Answer
has body: It did not work for me (probably I did something wrong) but I could fix this with a while loop and locatedOnscreen where I then use two if statements and break where we see the picture. while 1: sleep(1) black_market = pt.locateOnScreen( "imgs/black_market.png", grayscale=False, region=(709,646,161,141), confidence=0.8) if black_market is not None: print("I see black market") break black_market = pt.locateOnScreen( "imgs/black_market.png", grayscale=False, region=(709,646,161,141), confidence=0.8) if black_market is None: print("I do not see black market")
answers question: http://stackoverflow.com/q/50643931

http://stackoverflow.com/a/50622027
has body: You can try python filename.py -emIdentify=-E
has comment: http://stackoverflow.com/comment/88262732
upvote count: 1
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50621922

http://stackoverflow.com/q/50686123
has comment: http://stackoverflow.com/comment/88382081
linked to: http://stackoverflow.com/q/38263789
has comment: http://stackoverflow.com/comment/88403952
tagged with: lbph-algorithm
downvote count: 0
favorite count: 0
has title: LBP implementation in Python
type: UnansweredQuestion
tagged with: machine-learning
upvote count: 1
tagged with: python
tagged with: computer-vision
answer count: 0
score: 1
tagged with: image-processing
has body: I'm implementing the LBP characteristics for images with Python. I'm using it for clasifying pedestrians but I don't obtain good results and it lasts too long because of for loops nested (about 3 hours). Can anyone see a mistake in the implementation? And any suggestions for make it more efficient? The function is this: I'm using blocks of 16x16 and moving it 8 pixels. def LBP_img_basic(img): size2, size1 = img.shape numbers = [] dx = 8 dy = 8 cell_x = 16 cell_y = 16 x = 0 y = 0 hist_list = [] while y + cell_y &lt;= size2: for i in range(y, y + cell_y): for j in range(x, x + cell_x): hood = np.zeros((3,3), dtype = int) if j == 0 and i == 0: hood[1:3, 1:3] = img[i:i+2, j:j+2] elif i == 0 and j == size1 - 1: hood[1:3, 0:2] = img[i:i+2, j-1:j+1] elif j == 0 and i == size2 - 1: hood[0:2, 1:3] = img[i-1:i+1, j:j+2] elif i == size2 - 1 and j == size1 - 1: hood[0:2, 0:2] = img[i-1 : i+1, j-1:j+1] elif i == 0: hood[1:3,0:3] = img[i:i+2, j-1:j+2] elif j == 0: hood[0:3, 1:3] = img[i-1:i+2, j:j+2] elif i == size2 - 1: hood[0:2, 0:3] = img[i-1 : i+1, j-1:j+2] elif j == size1 - 1: hood[0:3, 0:2] = img[i-1 : i+2, j-1:j+1] else: hood = img[i-1 : i+2, j-1:j+2] ordered_hood = np.concatenate((hood[0], [hood[1,2], hood[2,2], hood[2,1], hood[2,0], hood[1,0]])) for k in range(len(ordered_hood)): if ordered_hood[k] &lt; hood [1,1]: ordered_hood[k] = 0 else: ordered_hood[k] = 1 binary = "" for digit in ordered_hood: binary += str(digit) integer = int(binary, 2) numbers.append(integer) hist = np.zeros(256) for l in numbers: hist[l] += 1 hist_list = np.concatenate((hist_list, hist)) if x + dx + cell_x &gt; size1: x = 0 y = y + dy else: x = x + dx return hist_list
type: Question

http://stackoverflow.com/q/50675374
score: 1
has title: the data output is horizontal from the following code, can it possbile to vertical
has answer: http://stackoverflow.com/a/50675454
has answer: http://stackoverflow.com/a/50675517
type: Question
answer count: 3
possible better answer: http://stackoverflow.com/a/50675616
has body: the data output is horizontal from the following code, can it possbile to vertical, many thanks ! from bs4 import BeautifulSoup import urllib2 url1 = "url" content1 = urllib2.urlopen(url1).read() soup = BeautifulSoup(content1,"lxml") div = soup.find("form", {"name": "SelHorse"}) rows = div.findAll('table')[6].findAll('tr') for row in rows: print (row.text)
upvote count: 1
favorite count: 0
tagged with: beautifulsoup
tagged with: python
accepted answer: http://stackoverflow.com/a/50675517
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/50675616

http://stackoverflow.com/q/50553628
score: 1
type: Question
has comment: http://stackoverflow.com/comment/88187038
has body: I am trying to run Python script from Google Cloud Natural Language API Python Samples https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/language/cloud-client/v1beta2/snippets.py I have not made any modifications, so I expected it would just work. Specifically, I want to run entities analysis on a text file/document. and the relevant part of the code is below. def entities_file(gcs_uri): """Detects entities in the file located in Google Cloud Storage.""" client = language_v1beta2.LanguageServiceClient() # Instantiates a plain text document. document = types.Document( gcs_content_uri=gcs_uri, type=enums.Document.Type.PLAIN_TEXT) # Detects sentiment in the document. You can also analyze HTML with: # document.type == enums.Document.Type.HTML entities = client.analyze_entities(document).entities # entity types from enums.Entity.Type entity_type = ('UNKNOWN', 'PERSON', 'LOCATION', 'ORGANIZATION', 'EVENT', 'WORK_OF_ART', 'CONSUMER_GOOD', 'OTHER') for entity in entities: print('=' * 20) print(u'{:&lt;16}: {}'.format('name', entity.name)) print(u'{:&lt;16}: {}'.format('type', entity_type[entity.type])) print(u'{:&lt;16}: {}'.format('metadata', entity.metadata)) print(u'{:&lt;16}: {}'.format('salience', entity.salience)) print(u'{:&lt;16}: {}'.format('wikipedia_url', entity.metadata.get('wikipedia_url', '-'))) I have put my text file (utf-8 encoding) on cloud storage at gs://neotokyo-cloud-bucket/TXT/TTS-01.txt I am running the script in Google cloud shell. and when I run the file: python snippets.py entities-file gs://neotokyo-cloud-bucket/TXT/TTS-01.txt I get the following error, which appears to be protobuf related. [libprotobuf ERROR google/protobuf/wire_format_lite.cc:629]. String field 'google.cloud.language.v1beta2.TextSpan.content' contains invalid UTF-8 data when parsing a protocol buffer. Use the 'bytes' type if you intend to send raw bytes. ERROR:root:Exception deserializing message! Traceback (most recent call last): File "/usr/local/lib/pyth…
has answer: http://stackoverflow.com/a/59331309
answer count: 2
tagged with: google-cloud-platform
upvote count: 1
has comment: http://stackoverflow.com/comment/88231030
favorite count: 0
tagged with: google-cloud-nl
tagged with: protocol-buffers
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50614485
has title: String field 'google.cloud.language.v1beta2.TextSpan.content' contains invalid UTF-8 data when parsing a protocol buffer
downvote count: 0

http://stackoverflow.com/q/50607119
type: Question
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/88225226
tagged with: pandas
tagged with: python
type: UnansweredQuestion
has body: Let's say that we're given a simple pandas dataframe: df = pd.DataFrame({"A": [1,2,3], "B": [4,5,6]}) I would like to append a new row to this dataframe. Why doesn't the following approach work? df.iloc[len(df)]=[9,9] Interestingly, it all works normally if we use .loc[] instead, even though len(df) is an integer and .iloc[] is used for integer-location based indexing, unlike .loc[].
has comment: http://stackoverflow.com/comment/88224283
tagged with: indexing
has title: Adding a new row to a dataframe - why .loc[len(df)] instead of .iloc[len(df)]?
has answer: http://stackoverflow.com/a/50607256
tagged with: dataframe

http://stackoverflow.com/comment/88232264
type: QuestionComment
has text: You said, "Below is not working". Do you get any errors?
score: 0
comment on: http://stackoverflow.com/q/50611165
type: Comment

http://stackoverflow.com/comment/88348913
score: 0
has text: Consider dumping out the results every 10k instead of waiting for it to run out of memory at 50k entries.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50630280

http://stackoverflow.com/q/50696080
type: Question
tagged with: function
has title: How do I create a 3D plot using a function that returns a plot?
tagged with: scatter
has answer: http://stackoverflow.com/a/50696297
tagged with: 3d
score: 3
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50696297
favorite count: 0
has body: I would like to make a 3D plot using a function that returns a plot and the input argument it takes. This is my code for the function: def cumulative(moment): bins = np.zeros(32) x = upper_bin for i in range(32): bins[i] = burst_average[moment, 0:i+1].sum() plt.ylim(ymax = 1000) plt.xlabel('grain size (um)') plt.ylabel('concentration (uL/L)') plt.title('grain size distribution over time') plt.plot(x, bins, c = 'b', label=dates[i]) return import ipywidgets as widgets from ipywidgets import interact interact(cumulative, moment=widgets.FloatSlider(min = int(0), max = int(nr_burst-1), step = 1, description = 'moment')); where x is a list of 32 values, bins is an array of 32 values as well that changes for every moment. In total, nr_burst plots are made, which is about 2017. The widget works, however I want to include this in my report, so I would like a 3D plot instead. I tried something like from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits import mplot3d b0 = np.linspace(0, nr_burst-1, nr_burst) b= [] for i in range(len(b0)): b.append(int(b0[i])) ax.scatter3D(cumulative(b), b) This did not work, gave the error ValueError: Arguments 'xs' and 'ys' must be of same size. I also tried the function to return x and b and plot like ax.scatter3D(cumulative(b)[0], b, cumulative(b)[1]) Which gave the error TypeError: 'NoneType' object is not subscriptable.
tagged with: python
tagged with: plot
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/a/58900584
score: 13
answers question: http://stackoverflow.com/q/50581138
upvote count: 14
downvote count: 1
has body: There is no need to install the entire azure package. I believe you are using the new azure-storage-blob library, but since BlockBlobService is from the old azure-storage library, to continue using it, you need to pip uninstall azure-storage-blob if you have installed the new library by accident, and then pip install azure-storage to install the old library. If you would like to use the new library or cannot do the above, feel free to refer to my answer here which details the context and full instructions of using either the new azure-storage-blob library or the old azure-storage library.
type: Answer
has comment: http://stackoverflow.com/comment/112887280

http://stackoverflow.com/comment/88299045
has text: Nope, nope, nope, my bad ! I only had changed the _backend function_ arguments and forgot to change in the actual `ctc_decode` arguments. Thank you very much for your good answer.
score: 0
comment on: http://stackoverflow.com/a/50643303
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50630662
downvote count: 0
has body: Finally found a solution juste after posting. See doc for reference c = session.query(Child).\ filter(Child.parent.has(Parent.grandparent.has(GrandParent.id == 2))).\ filter(Child.index == 2).first()
type: Answer
score: 4
answers question: http://stackoverflow.com/q/50630166
upvote count: 4

http://stackoverflow.com/comment/88307635
score: 0
has text: What do you mean by "small"? These percentage differences are correct, there is no numerical roundoff. (The difference in the exponents is 2 or more, so it is more than 100 times smaller, so the percentage difference is greater than 99%.)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50648329

http://stackoverflow.com/q/50666417
has answer: http://stackoverflow.com/a/77978589
type: Question
has comment: http://stackoverflow.com/comment/88342941
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/88343129
has comment: http://stackoverflow.com/comment/88345373
has comment: http://stackoverflow.com/comment/88343322
has answer: http://stackoverflow.com/a/50666477
has title: Encoding a tuple or dict in Python?
favorite count: 0
has comment: http://stackoverflow.com/comment/88342897
tagged with: python-3.x
tagged with: tuples
has comment: http://stackoverflow.com/comment/88343107
tagged with: byte
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/88342970
has body: I'm using the cryptography module to encrypt some data and then trying to store it in my SQL datbase. When it is a string, it works. However, when I'm trying to use a tuple or a dict it fails. I have the following as my function that is being called. (uses crypytography.Fernet.encrypt). def encrypt(to_encrypt): ''' Takes a bytestring and returns a token. ''' key = get_key() f = make_fernet_object(key) token = f.encrypt(to_encrypt) return token If I try to pass a tuple or dict to it directly, I get TypeError: data must be bytes. If I use bytes(my_tuple) Then I get TypeError: 'str' object cannot be interpreted as an integer How do I turn my tuple (which contains 2 strings and a dict) into a bytes object that Fernet will encrypt so I can put the blob in my SQL database? edit - The tuple in question is in the format.. my_tuple = ('username', 'password', {'memorable question':'memorable answer', 'memorable question 2', 'memorable answer 2'})
has comment: http://stackoverflow.com/comment/88343429
downvote count: 2

http://stackoverflow.com/comment/88228612
has text: @Rahul see this https://www.architectryan.com/2012/10/02/add-to-the-path-on-mac-os-x-mountain-lion/
comment on: http://stackoverflow.com/a/50606572
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88312158
score: 0
type: QuestionComment
has text: @jeremysprofile I guess that's something I'll need to learn to appreciate then. I'm still new at this, so in my mind, I was trying to create all the objects in bulk, so that I could work directly with them, with a naming convention that made sense to me. Having to add a little logic to my program via the if statement against a list seems like an unnecessary (but apparently necessary) step...to me. But again, still learning so I'm sure there's tried and true reasoning behind this approach.
type: Comment
comment on: http://stackoverflow.com/q/50650133

http://stackoverflow.com/a/50609323
has body: The recursion depth is deeper than needed to solve the maze problem. The maximum recursion depth must not be much deeper than the "length of your path up to the exit". The length of your path is 33 (= steps to be done in the 10 * 9 tiles map before the exit is reached). If the maze would have much more branches, then also the recursion depth would grow. However, it does not sound plausible that the recursion depth exceeds several 1000s. This has one reason: you allow to continue the search into opposite direction (so where the search comes from). This is not necessary to find the shortest path and it would massively decrease your recursion depth, if you avoid it.
type: Answer
has comment: http://stackoverflow.com/comment/88235529
score: 0
answers question: http://stackoverflow.com/q/50593248
has comment: http://stackoverflow.com/comment/88235380

http://stackoverflow.com/q/50667698
has comment: http://stackoverflow.com/comment/88347822
has title: Fastest way to count element in a list satisfying conditions
has comment: http://stackoverflow.com/comment/88346611
possible better answer: http://stackoverflow.com/a/50669293
has answer: http://stackoverflow.com/a/50669293
has answer: http://stackoverflow.com/a/50668895
type: AnsweredQuestion
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88346980
type: Question
has body: I want to get the number of elements in a list satisfying certain conditions specified by another list. The way I did is using sum and any. The simple testing codes are: &gt;&gt;&gt; x1 = list(xrange(300)) &gt;&gt;&gt; x2 = [random.randrange(20, 50) for i in xrange(30)] &gt;&gt;&gt; def test(): ns = [] for i in xrange(10000): ns.append(sum(1 for j in x2 if any(abs(k-j)&lt;=10 for k in x1))) return ns Using Profiler shows that the sum and any caused the most time, any way to improve this? &gt;&gt;&gt; cProfile.run('ns = test()') 8120003 function calls in 0.699 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.003 0.003 1.552 1.552 &lt;pyshell#678&gt;:2(test) 310000 0.139 0.000 1.532 0.000 &lt;pyshell#678&gt;:5(&lt;genexpr&gt;) 1 0.000 0.000 1.552 1.552 &lt;string&gt;:1(&lt;module&gt;) 7490000 0.196 0.000 0.196 0.000 {abs} 300000 0.345 0.000 1.377 0.000 {any} 10000 0.001 0.000 0.001 0.000 {method 'append' of 'list' objects} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 10000 0.016 0.000 1.548 0.000 {sum} The function test only contain 10000 iterations. Generally, I would have tens of thousands iterations, and using the cProfile.run shows that this block cause majority of executing time. =================================================================== Edit According to @DavisHerring's answer, using binary search. from _bisect import * &gt;&gt;&gt; x1 = list(xrange(300)) &gt;&gt;&gt; x2 = [random.randrange(20, 50) for i in xrange(30)] &gt;&gt;&gt; def testx(): ns = [] x2k = sorted(x2) x1k = sorted(x1) for i in xrange(10000): bx = [bisect_left(x1k, xk) for xk in x2k] rn = sum(1 if k==0 and x1k[k]-xk&lt;=10 else 1 if k==len(x1k) and xk-x1k[k-1]&lt;=10 else xk-x1k[k-1]&lt;=10 or x1k[k]-xk&lt;=10 for k, xk in zip(bx, x2k)) ns.append(rn) return ns According to cProfile.run, 0.196 seconds is reached, 3x+ faster.
answer count: 2
tagged with: python
score: 4
accepted answer: http://stackoverflow.com/a/50668895
has comment: http://stackoverflow.com/comment/88345654
has comment: http://stackoverflow.com/comment/88345440
upvote count: 4

http://stackoverflow.com/a/50613823
accepted answer of: http://stackoverflow.com/q/50612394
type: Answer
score: 1
has body: You need to pass pass_context=True to @bot.command @bot.command(pass_context=True) @asyncio.coroutine def info(ctx): server = ctx.message.author.server server_name = server.name server_id = server.id server_owner = server.owner.name print("server name: {}" "server id: {}" "server owner: {}" .format(server_name, server_id, server_owner))
upvote count: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50612394

http://stackoverflow.com/comment/88353705
score: 1
has text: @D.Vidal for a in range(0,19): why not ?
comment on: http://stackoverflow.com/q/50671971
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88386531
type: Comment
has text: The issue with writing Unicode data to CSV is explained in the docs. The short version is: Python 2's `csv` module doesn't understand Unicode, but the [Examples](https://docs.python.org/2/library/csv.html#examples) show various ways to work around it. There are multiple duplicate questions on this here, but they all basically tell you to use those examples, or to search PyPI or elsewhere for modules that essentially just wrap up those examples (one of which you don't want, because it was abandoned many years ago, which I know because I wrote it…).
type: QuestionComment
comment on: http://stackoverflow.com/q/50688353
score: 0

http://stackoverflow.com/a/54951882
downvote count: 0
has comment: http://stackoverflow.com/comment/110956284
upvote count: 2
type: Answer
score: 2
has body: Good job on finding the VM distribution. That's half of the battle. But unless I'm mistaken by the formula in the scipy.stats.vonmises docs, the formula assumes that the data is centered at 0, which may not be the case. So we should probably build our own VM distribution. And for our Vm distribution, we'll make sure it is periodic over a 24 hr range instead of the traditional 2pi range. See the code and comments below. Also, I assumed your data were the times that you saw some event happening, you will need to readjust if that is not the case. from scipy.optimize import curve_fit import numpy as np from matplotlib import pyplot as plt # Define the von mises kernel density estimator def circular_von_mises_kde(x,mu,sigma): # Adjust data to take it to range of 2pi x = [(hr)*2*np.pi/24 for hr in x] mu*=2*np.pi/24 sigma*=2*np.pi/24 # Compute kappa for vm kde kappa = 1/sigma**2 return np.exp((kappa)*np.cos((x-mu)))/(2*np.pi*i0(kappa)) # Assuming your data is occurences of some event at the given hour of the day frequencies= np.zeros((24)) frequencies[data]=1 hr_data = np.linspace(1,24, 24) fit_params, cov = curve_fit(circular_von_mises_kde, hr_data, data_to_fit, bounds=(0,24)) plt.plot(hr_data, frequencies, 'k.',label='Raw data') plt.plot(np.linspace(1,25, 1000), circular_von_mises_kde(np.linspace(1,25, 1000), *fit_params), 'r-',label='Von Mises Fit') plt.legend() plt.xlabel('Hours (0-24)') plt.show() print('The predicted mean is {mu} and the standard deviation is {sigma}'.format( mu=round(fit_params[0],3), sigma=round(fit_params[1], 3))) Click to see the result of the above code * As a quick caveat, you're likely going to need a larger dataset to do some proper fitting and to really establish a population trend.
answers question: http://stackoverflow.com/q/50693921

http://stackoverflow.com/q/50650433
tagged with: pip
tagged with: python
tagged with: pyodbc
has title: python 3.6 // Update pyodbc
type: AnsweredQuestion
tagged with: anaconda
has comment: http://stackoverflow.com/comment/88312068
type: Question
has answer: http://stackoverflow.com/a/50650865
has comment: http://stackoverflow.com/comment/88311795
has comment: http://stackoverflow.com/comment/88312025
score: 0
tagged with: batch-file
accepted answer: http://stackoverflow.com/a/50650865
has body: I would like to upgrade a module in python called "pyodbc". I use python 3.6 with spider in Anaconda and my version of "pyodbc" is 4.0.22 and the one of my coworker is 3.0.16. I would like to upgrade to 4.0.23. I tried with a batch file : C: cd path to Anaconda3 python -m pip install --user -U pyodbc and I tried manually with the anaconda navigator but nothing works. It's always for me 4.02.22 unfortunately. Thank you in advance for the help.
answer count: 1

http://stackoverflow.com/comment/88177387
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50579716
has text: `xy_ind = np.stack(np.mgrid[:1, :1000], axis=-1) print(xy_ind.shape)` outputs `[1, 1000, 2]` while `xy_ind = tf.stack(tf.meshgrid(tf.range(1), tf.range(1000)), axis=-1) s = tf.shape(xy_ind) print(s.eval())` outputs `[1000, 1, 2]`
type: AnswerComment

http://stackoverflow.com/q/50595069
tagged with: python
has title: Python: Flask server on Windows -- how to SSL ify the Flask web server?
has answer: http://stackoverflow.com/a/50828737
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50828737
type: Question
tagged with: ssl
tagged with: flask
score: 0
has comment: http://stackoverflow.com/comment/88199934
has body: I have an ssl cert imported into the personal store in the computer account. I thought this would do it: netsh http add sslcert ipport=0.0.0.0:443 certhash=8caef2be185a0c94d################ appid="{7E46BD40-39C6-4813-B414-019AD3332421}" netsh http add iplisten ipaddress=0.0.0.0:443 But it is serving plain text, not over SSL. What step is missing?
answer count: 1
linked to: http://stackoverflow.com/q/50595269

valueerror
tags question: http://stackoverflow.com/q/50628138
tag name: valueerror
type: Tag
tags question: http://stackoverflow.com/q/50663334
tags question: http://stackoverflow.com/q/50549933
tags question: http://stackoverflow.com/q/50552644

http://stackoverflow.com/comment/88386422
comment on: http://stackoverflow.com/q/50688295
has text: It is not clear to me what you are looking for. Do you have a big list that you want to write to files?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88170798
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50570338
has text: ye i saw it and tryied but nothin

http://stackoverflow.com/q/50650949
has answer: http://stackoverflow.com/a/50651870
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: The script I have is exporting all users but I am looking to export users who have a type = xyz. There are two types of users in the directory such as type a and type b and i only want to export users who have type attribute matches b. Please help me to add a clause/statement in the script so it should only pull users with Type "B" and ignore other users with ant other type. import requests import json import re import sys import csv orgName = "" apiKey = "" api_token = "SSWS "+ apiKey headers = {'Accept':'application/json','Content-Type':'application/json','Authorization':api_token} def GetPaginatedResponse(url): response = requests.request("GET", url, headers=headers) returnResponseList = [] responseJSON = json.dumps(response.json()) responseList = json.loads(responseJSON) returnResponseList = returnResponseList + responseList if "errorCode" in responseJSON: print "\nYou encountered following Error: \n" print responseJSON print "\n" return "Error" else: headerLink= response.headers["Link"] while str(headerLink).find("rel=\"next\"") &gt; -1: linkItems = str(headerLink).split(",") nextCursorLink = "" for link in linkItems: if str(link).find("rel=\"next\"") &gt; -1: nextCursorLink = str(link) nextLink = str(nextCursorLink.split(";")[0]).strip() nextLink = nextLink[1:] nextLink = nextLink[:-1] url = nextLink response = requests.request("GET", url, headers=headers) responseJSON = json.dumps(response.json()) responseList = json.loads(responseJSON) returnResponseList = returnResponseList + responseList headerLink= response.headers["Link"] returnJSON = json.dumps(returnResponseList) return returnResponseList def DownloadSFUsers(): url = "https://"+orgName+".com/api/v1/users" responseJSON = GetPaginatedResponse(url) if responseJSON != "Error": userFile = open("Only-Okta_Users.csv", "wb") writer = csv.writer(userFile) writer.writerow(["login","type"]).encode('utf-8') for user in responseJSON: login = user[u"profile"][u"login"] type = user[u"credentials"][u"provider"][u"type…
has title: Export users with criteria - Python script
score: -4
has comment: http://stackoverflow.com/comment/88312775
type: Question
downvote count: 4
has comment: http://stackoverflow.com/comment/88312925
upvote count: 0
answer count: 1

http://stackoverflow.com/a/50697476
has body: You can use os.sep to split by a delimiter. The benefit of this method is if you move to a different system and your input paths change format, you will not need to modify your code. Note that, as per your example, we want to access the 4th component in your path when splitting by os.sep. Since indexing begins at 0, we index by [3]. import os x = r'C:\Company\ProjectList\ProjectName\Requriment' res = x.split(os.sep)[3] print(res) ProjectName
type: Answer
accepted answer of: http://stackoverflow.com/q/50697388
has comment: http://stackoverflow.com/comment/88404254
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/50697388
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88339578
has text: Thanks for the answer, I already did it by splitting in 100*100000 files. However it was looking for something faster like Bulk insert in MySQL
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50664039

http://stackoverflow.com/comment/88177202
has text: The double clashes are perfectly ok, that is standard representation of a path. On Windows there are some issues with letter drive maybe that is causing problem https://docs.python.org/3.6/library/os.path.html#os.path.join
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50583059
type: Comment

http://stackoverflow.com/comment/88676487
has text: What do you mean by `not quite working`? Anyway, don't do this `WhateverAttribute(default = {})`. Instead, if the type of the `default` is mutable, then do `WhateverAttribute(default=lambda: {})`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50614290

http://stackoverflow.com/a/50549713
has comment: http://stackoverflow.com/comment/88110276
upvote count: 1
score: 1
has body: ValueError: could not convert string to float I think this says it all. You need to have float as consistent datatype in your dataset. To convert a string in python to float: &gt;&gt;&gt; a = "123.345" &gt;&gt;&gt; float(a) &gt;&gt;&gt; 123.345 &gt;&gt;&gt; int(float(a)) &gt;&gt;&gt; 123
answers question: http://stackoverflow.com/q/50549681
has comment: http://stackoverflow.com/comment/88110324
has comment: http://stackoverflow.com/comment/88110440
downvote count: 0
has comment: http://stackoverflow.com/comment/88110523
has comment: http://stackoverflow.com/comment/88110540
type: Answer
has comment: http://stackoverflow.com/comment/88110807
has comment: http://stackoverflow.com/comment/88110389
has comment: http://stackoverflow.com/comment/88110295
has comment: http://stackoverflow.com/comment/88110287

http://stackoverflow.com/comment/88357086
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50672514
has text: Thanks Dux. I learn something new about the regex `\d{2}` great tip
score: 0

http://stackoverflow.com/comment/88150378
comment on: http://stackoverflow.com/q/50569748
has text: where did you try to call the "boxclass" method? Aren't you forgeting .show? (not familiar with pyqt)
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88108624
has text: I don't understand, what's wrong with what you've written?
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50548895

http://stackoverflow.com/q/50651736
tagged with: python
upvote count: 6
tagged with: django
downvote count: 1
type: Question
has body: we're using django 1.10, Celery 4.1.0 I'm trying to use apply_async. This is the task: from celery import Celery app = Celery('my_app', broker='redis://127.0.0.1:6379/2') @app.task def add(x, y): print(str(x+y)) raise status.HTTP_500_INTERNAL_SERVER_ERROR When calling it with 'delay' it runs the 'add' function but doesn't retry: add.delay(4, 4) I tried to run the task with 'apply_async' and 'retry' and 'retry_policy' but it doesn't seem to even run the task: add.apply_async((4, 4), retry=True, retry_policy={ 'max_retries': 3, 'interval_start': 0, 'interval_step': 0.2, 'interval_max': 0.2, } ) Am I missing something?
has comment: http://stackoverflow.com/comment/88318185
has answer: http://stackoverflow.com/a/54642920
tagged with: django-celery
has comment: http://stackoverflow.com/comment/88323842
score: 5
answer count: 1
has title: Django Celery apply_async doesn't work
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/88127491
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50558333
has text: You're going to want to use something like Nginx. There are plenty of tutorials for setting up django for production

http://stackoverflow.com/comment/88348887
type: QuestionComment
has text: That code doesn't demonstrate your problem, does it? (you seem to be writing everything to one file). Also, please indent your code!!
score: 1
comment on: http://stackoverflow.com/q/50669484
type: Comment

http://stackoverflow.com/comment/88300588
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50644196
type: AnswerComment
has text: The desired output is the final dataframe resulting from the loop: Green/Small, Blue/Small, Red/Medium and Yellow/Large. i would like to avoid looping

http://stackoverflow.com/a/50582978
has comment: http://stackoverflow.com/comment/88175617
has comment: http://stackoverflow.com/comment/88274587
score: 0
has comment: http://stackoverflow.com/comment/88175508
type: Answer
answers question: http://stackoverflow.com/q/50582179
has body: If the first bit managed to filter what you wanted with: sf.loc[(sf['Unnamed: 16']&gt;= start) &amp; (sf['Unnamed: 16']&lt;=end), 'CurrentMonth'] = sf['Unnamed: 16'] Then create a column like this sf['New column'] = values for new column I can't reproduce the problem as you haven't provided a useful dataset (images are not useful for this - see the instructions for how to create a minimal example https://stackoverflow.com/help/mcve
has comment: http://stackoverflow.com/comment/88175281
has comment: http://stackoverflow.com/comment/88212468

http://stackoverflow.com/q/50622985
type: UnansweredQuestion
has body: Right now, i'm reading from two files to take information from both files and combine them to one file.. The one file is with gps information.. which records a time every second, the other file is with data from a sensor recorded data every 5ms.. when I combine these two files, I take some data from the sensor, and the last bytes is with a timestamp (unix) from the sensor, AND here I have trouble, because the for a timestamp for each set of data, I have to take the time from the GPS and then plus with 5 ms, per dataset until I get the time from the GPS. Right now my code write the same time for all 200 samples per second piece_size_acc = 24 # 4 KiB piece_size_gps = 8 with open(r"C:\PATH\00000003.acc.bin", "rb") as in_file_acc, open(r"C:\PATH\00000003.gps.bin", "rb") as in_file_gps: while True: in_file_gps.seek(tempNumOfBytesRead + 60) tempNumOfBytesRead = tempNumOfBytesRead + 60 piece_gps = in_file_gps.read(piece_size_gps) tempNumOfBytesRead = tempNumOfBytesRead + 8 if piece_gps == b"": output_file.close() break # end of file for i in range(0,200): piece_acc = in_file_acc.read(piece_size_acc) if piece_acc == b"": output_file.close() break # end of file output_file.write(piece_acc) output_file.write(piece_gps) As u can see, the time, is 8 bytes long, between every 60-68bytes. Can I plus the time with 5 millisecond when reading the bytes or should I get it out in text and the plus it?
score: 1
type: Question
upvote count: 1
has title: Change the value in a file for every specific byte - python
favorite count: 0
has comment: http://stackoverflow.com/comment/88257973
tagged with: python
downvote count: 0
answer count: 0

http://stackoverflow.com/q/50547021
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50547597
has body: I'm running the chunk of code under 3. Word to Vectors Integration from this NLP tutorial. It uses Spacy's lexemes to calculate the most similar words to whatever word you give it - I'm using it to try to find the nearest synonyms to the given word. However, if you replace apple with a word like "look" you get a lot of related words, but not synonyms (examples: pretty, there, over, etc.). I was thinking of modifying the code to also filter by part of speech, so that I could just get verbs in the output and would be able to go from that. To do that, I'd need to use tokens so I can use token.pos_, since that function isn't available for lexemes. Does anyone know a way to take the output (list called "others" in the code) and change it from a lexeme to a token? I was reading over spacy's information document for lexemes here, but I haven't been able to find anything about transforming. I've also tried adding a section of code at the end to the other person's code: from numpy import dot from numpy.linalg import norm import spacy from spacy.lang.en import English nlp = English() parser = spacy.load('en_core_web_md') my_word = u'calm' #Generate word vector of the word - apple apple = parser.vocab[my_word] #Cosine similarity function cosine = lambda v1, v2: dot(v1, v2) / (norm(v1) * norm(v2)) others = list({w for w in parser.vocab if w.has_vector and w.orth_.islower() and w.lower_ != my_word}) print("done listing") # sort by similarity score others.sort(key=lambda w: cosine(w.vector, apple.vector)) others.reverse() for word in others[:10]: print(word.orth_) The part I added: b = "" for word in others[:10]: a = str(word) + ' ' b += a doc = nlp(b) print(doc) token = doc[0] counter = 1 while counter &lt; 50: token += doc[counter] counter += 1 print(token) This is the output error: 'token += doc[counter] TypeError: unsupported operand type(s) for +=: 'spacy.tokens.token.Token' and 'spacy.tokens.token.Token' &lt;spacy.lexeme.Lexeme object at 0x000002920ABFAA68&gt; &lt;spacy.lex…
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: converting from lexeme to token in Spacy
tagged with: nlp
tagged with: spacy
score: 1

http://stackoverflow.com/q/50544754
tagged with: django-staticfiles
favorite count: 0
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: css
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50545502
accepted answer: http://stackoverflow.com/a/50545502
downvote count: 0
has answer: http://stackoverflow.com/a/50545028
tagged with: django
has answer: http://stackoverflow.com/a/50557164
type: Question
has title: New to Django. Tried looking at tutorials on how to load css files and not working
has body: The website I see when I run the server has not CSS in it, but just the HTML. So far I read that you keep CSS files in a static folder under the project directory. I have an Html template that is in the templates folder and it works perfectly when I load it from the views.home . In the HTML file, I have {% load staticfiles %} at the top of the document, and yes I have checked my installed apps for 'django.contrib.staticfiles' in the settings. Also, in the HTML document, in the href attribute I've added {% static 'style/style.css' %} which is the name of the folder under the static folder. {% load staticfiles %} night_sky_2
upvote count: 2
answer count: 3
possible better answer: http://stackoverflow.com/a/50545028

http://stackoverflow.com/comment/88325083
has text: You are bang on. I actually just looked up the error and am starting to realise that I'm trying to encode a whole list as one, when I should be trying each element one by one. This is what the error is telling me. Will revert with detailed solution once I figure it out.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50657542

http://stackoverflow.com/comment/88402836
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50696744
has text: @KevinRoy Yes but then you get in the case of shared resources which becomes more complex. Not the best way to start with multiprocessing :)
score: 0

http://stackoverflow.com/comment/112375153
type: AnswerComment
has text: @Zombraz - you can use Dask or PySpark to convert multiple CSV files to a single Parquet file (or multiple Parquet files). See my answer for more details.
type: Comment
comment on: http://stackoverflow.com/a/50604507
score: 1

http://stackoverflow.com/q/50673363
tagged with: python
has body: Given a tensor of rank&gt;=1 T, I would like to randomly sample k entries from it, uniformly, along the 0-axis. EDIT: The sampling should be part of the computation graph as a lazy operation and should output different random entries every time it is called. For instance, given T of rank 2: T = tf.constant( \ [[1,1,1,1,1], [2,2,2,2,2], [3,3,3,3,3], .... [99,99,99,99,99], [100,100,100,100,100]] \ ) With k=3, a possible output would be: #output = \ # [[34,34,34,34,34], # [6,6,6,6,6], # [72,72,72,72,72]] How can this be achieved in tensorflow?
has title: In tensorflow, randomly (sub)sample k entries from a tensor along 0-axis
downvote count: 0
has answer: http://stackoverflow.com/a/50674002
tagged with: tensorflow
type: AnsweredQuestion
score: 7
type: Question
answer count: 1
favorite count: 0
upvote count: 7
accepted answer: http://stackoverflow.com/a/50674002

http://stackoverflow.com/a/50567628
score: -1
has comment: http://stackoverflow.com/comment/88145487
type: Answer
has body: Well, this is probably kind of limited, but you can go with the following: converted_expression = "(2.4**l2) + 8.0*([k3,k2][bool(l3&gt;=l4)])" The bool(...) part will return False or True which is auto-converted into 0 and 1 respectively as a list index.
downvote count: 1
upvote count: 0
has comment: http://stackoverflow.com/comment/88145749
answers question: http://stackoverflow.com/q/50567457

http://stackoverflow.com/a/73926974
score: 1
answers question: http://stackoverflow.com/q/50685409
downvote count: 0
has body: To get N evenly spaced elements from list 'x': x[::int(np.ceil( len(x) / N ))]
has comment: http://stackoverflow.com/comment/138018057
type: Answer
upvote count: 1

http://stackoverflow.com/q/50618945
type: Question
has comment: http://stackoverflow.com/comment/88247967
tagged with: python-2.7
has body: If I am generating request in php using rijndael 256 algorithm and ECB mode then it is working. Ex of php $enc_request = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this-&gt;_user_key, json_encode($request_params), MCRYPT_MODE_ECB)); My requirement to generate same request in python. from rijndael.cipher.crypt import new from rijndael.cipher.blockcipher import * import json import base64 var = {'controller':'user','action':'check'} plaintext =json.dumps(var) print(plaintext) key='werewrewrewrwerlkewrjewklrwelkrwelkr' rjn = new(key, MODE_ECB, blocksize=32) key = rjn.encrypt(plaintext) print base64.b64encode(key) Key is generating but blocksize is 32. How can we generate using block 256 in python.
has comment: http://stackoverflow.com/comment/88248750
score: 2
downvote count: 0
favorite count: 0
has title: How to send encrypted request in python using algorithm rijndael 256 and mode ECB?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88248596
answer count: 0
upvote count: 2
tagged with: python-requests

http://stackoverflow.com/a/50581105
score: 0
has comment: http://stackoverflow.com/comment/88171846
has body: You could use import_module from importlib in your tests.py: from importlib import import_module files = import_module("package.file") Also available for python 2.7 as far as I have seen. EDIT: This assumes that the top level structure 'app' is a package. i.e. has an __init__.py file
type: Answer
answers question: http://stackoverflow.com/q/50580443

http://stackoverflow.com/comment/88315727
comment on: http://stackoverflow.com/a/50652461
type: AnswerComment
has text: Thanks for that it works. I just need to figure out why it prints all lines in the list and not just those that contain the entry string
score: 0
type: Comment

http://stackoverflow.com/comment/88388327
type: Comment
type: QuestionComment
has text: Welcome to Stack Overflow! Use formatting tools to make your post more readable. It will get more attention if readable.
score: 0
comment on: http://stackoverflow.com/q/50689035

http://stackoverflow.com/comment/88140027
has text: The problem could lie in your decimal points. The value "2,25" is separated by a comma which in international convention is actually a 1000 separator. Try change your extreme values into "2.25" and "2.5" and retry (same for the BasicLevel)
comment on: http://stackoverflow.com/q/50564837
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88309741
comment on: http://stackoverflow.com/q/50649425
has text: What are you trying to do in the `chunk = ans[i:i+100]` line? It looks like you're ignoring everything before the last 100 elements of `ans`
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/50587834
favorite count: 0
tagged with: python-2.7
has body: I have some trouble using tf.train.shuffle_batch() on a large dataset. I'm using it like that : x_train, y_train = tf.train.shuffle_batch( [images["train"], labels["train"]], batch_size=self.batch_size, #I reduced it to 8 capacity=50000, enqueue_many=True, min_after_dequeue=0, num_threads=16, seed=self.seed, allow_smaller_final_batch=True, ) Where : images["train"].shape = (88179,64,64,3) #Training set of tiny-Imagenet labels["train"].shape = (88179,) #Related labels and it output me this error : ValueError: Cannot create a tensor proto whose content is larger than 2GB. Indeed I tried on a smaller dataset (CIFAR-10) where shapes are smaller (and 160 of batch_size) : images["train"].shape = (45000,32,32,3) #Training set of CIFAR-10 labels["train"].shape = (45000,) #Related labels and tf.train.shuffle_batch() work perfectly. I saw a lot of Questions on this issue but none where people use tf.train.shuffle_batch() (I saw one but without answer in fact : Tensorflow &gt; 2GB array as an input for tf.slice_input_producer) Does someone has an idea ? [CONFIG : TITAN X 12Go, 32Go RAM, tensorflow 1.4.1, python 2.7.15, CUDA 8.0]
tagged with: gpu
has comment: http://stackoverflow.com/comment/90973203
has title: Tensorflow tf.train.shuffle_batch() Cannot create a tensor proto whose content is larger than 2GB
answer count: 0
type: UnansweredQuestion
score: 5
tagged with: machine-learning
tagged with: python
upvote count: 5
tagged with: tensorflow
type: Question
linked to: http://stackoverflow.com/q/48404534
downvote count: 0

http://stackoverflow.com/comment/88203583
comment on: http://stackoverflow.com/q/50597251
has text: `items[0]`?....
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50565800
has comment: http://stackoverflow.com/comment/88142442
possible better answer: http://stackoverflow.com/a/50566890
linked to: http://stackoverflow.com/q/37864222
tagged with: python
has answer: http://stackoverflow.com/a/50566890
duplicate of: http://stackoverflow.com/q/41670103
linked to: http://stackoverflow.com/q/32557920
upvote count: 3
has answer: http://stackoverflow.com/a/50565951
linked to: http://stackoverflow.com/q/42465568
type: AnsweredQuestion
score: 3
duplicate of: http://stackoverflow.com/q/42465568
has comment: http://stackoverflow.com/comment/88144029
has body: I am working on Databricks using Python 2. I have a PySpark dataframe like: |Germany|USA|UAE|Turkey|Canada... |5 | 3 |3 |42 | 12.. Which, as you can see, consists of hundreds of columns and only one single row. I want to flip it in a way such that I get: Name | Views -------------- Germany| 5 USA | 3 UAE | 3 Turkey | 42 Canada | 12 How would I approach this? Edit: I have hundreds of columns so I can't write them down. I don't know most of them, but they just exist there. I can't use the columns names in this process. Edit 2: Example code: dicttest = {'Germany': 5, 'USA': 20, 'Turkey': 15} rdd=sc.parallelize([dicttest]).toDF() df = rdd.toPandas().transpose()
type: Question
linked to: http://stackoverflow.com/q/46453058
answer count: 2
downvote count: 0
tagged with: pyspark
accepted answer: http://stackoverflow.com/a/50565951
duplicate of: http://stackoverflow.com/q/46453058
favorite count: 0
has title: Flip a Dataframe
linked to: http://stackoverflow.com/q/41670103
tagged with: apache-spark

http://stackoverflow.com/a/50567753
score: 3
downvote count: 0
has body: You may need to consider carefully the geometry of your scene, however linear algebra may give you reasonable results. If we take a your world coordinates to fit the general form aX + bY +c then we can make a least-squares fit using numpy's lstsq function. world = numpy.array([ [0,0,0], [7,0,0], [0,5,0], [7,4,0]]) camera = numpy.array([ [582,344], [834,338], [586,529], [841,522]]) #Lose Z axis world = world[:,0:2] #Make a square matrix A = numpy.vstack([world.T, numpy.ones(4)]).T #perform the least squares method x, res, rank, s = numpy.linalg.lstsq(A, camera, rcond=None) #test results print(numpy.dot(A,x))
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88146379
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50562755
answers question: http://stackoverflow.com/q/50562755
type: Answer

http://stackoverflow.com/a/50634176
type: Answer
has body: You need to call xaxis.tick_bottom() for the current axes as shown below: import numpy as np import matplotlib.pyplot as plt recmat = np.random.random((100,100)) plt.matshow(recmat) ax = plt.gca() plt.colorbar() ax.xaxis.tick_bottom() plt.show()
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50634049
answers question: http://stackoverflow.com/q/50634049

http://stackoverflow.com/q/50548361
accepted answer: http://stackoverflow.com/a/50549204
type: Question
score: 0
answer count: 1
tagged with: libreoffice
tagged with: openoffice.org
tagged with: uno
has answer: http://stackoverflow.com/a/50549204
tagged with: python
type: AnsweredQuestion
has body: LibreOffice 5.3, python 3.53, VOID Linux This is more of an uno question than a python question. The code below does a simple update of 3 cells. 3 buttons configured on the sheet calling dowriteonce() dowritetwice() and dowritethrice(), and they all update and work like you might expect writing numbers and text to selected cells. Where the problem comes in, is that when a cell is edited in the UI by a user, any subsequent update of that cell by means of executing the function is blocked. So simply clicking cell C4 in the calc UI, prevents the writethrice() function from updating cell C4. If I delete the content and click another cell in the UI, say C5, then everything works normally again and C4 updates when the button is clicked. What I would like to do is relocate the UI edit-cursor to an unused cell prior to execution in order to prevent this. User copy-paste is going to leave the active cursor in unpredictable places and that will bork calculations if I can't isolate the cursor. So the question is, how do I move the UI edit cursor to a named cell via the UNO API, with Python? Or if it is easier, just deactivate it temporarily. Python: import socket import sys import re import uno import unohelper class ODSCursor(unohelper.Base): # predeclare class properties ctx=None desktop=None model=None activesheet=None counter=0 scooby="Scooby" # import namespaces def __init__(self): import socket import uno import unohelper import sys import re # initialize uno handle only once and get the first sheet @classmethod def sheet1(cls,*args): if cls.activesheet is not None: return (cls.activesheet) cls.ctx = uno.getComponentContext() cls.desktop = cls.ctx.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", cls.ctx) cls.model = cls.desktop.getCurrentComponent() # cls.activesheet = cls.model.Sheets.getByName("Sheet1") cls.activesheet = cls.model.Sheets.getByIndex(0) return (cls.activesheet) @classmethod def writeonce(self,*args): self.counter += 1 cell_b1 = self…
has title: Python UNO on LibreOffice Calc, rehoming a cursor

http://stackoverflow.com/q/50610248
score: 2
linked to: http://stackoverflow.com/q/17309288
downvote count: 0
favorite count: 0
duplicate of: http://stackoverflow.com/q/17309288
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/50610279
has title: VideoFileClip import Error: "ImportError: No module named requests"
upvote count: 2
has body: I am trying to import VidoFileClip from moviepy.editor. This is the code: from moviepy.editor import VideoFileClip This is the error: Traceback (most recent call last): File "E:\Spring2018\MastersProject\ProjectFiles\Alternate.py", line 7, in <module> from moviepy.editor import VideoFileClip File "C:\Python27\lib\site-packages\moviepy\editor.py", line 31, in <module> from .video.io.downloader import download_webfile File "C:\Python27\lib\site-packages\moviepy\video\io\downloader.py", line 7, in <module> import requests ImportError: No module named requests
answer count: 1
tagged with: moviepy
type: UnansweredQuestion

http://stackoverflow.com/comment/88292145
type: Comment
type: QuestionComment
has text: @ubuntu_noob I don't think so, see https://pandas.pydata.org/pandas-docs/stable/merging.html#set-logic-on-the-other-axes
score: 0
comment on: http://stackoverflow.com/q/50640070

http://stackoverflow.com/q/50612923
has comment: http://stackoverflow.com/comment/91393448
has body: I wonder how can I export the estimator and then import it for prediction from MNIST tutorial, Tensorflow's page. Thank you!
linked to: http://stackoverflow.com/q/46098863
upvote count: 1
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/50613631
type: AnsweredQuestion
score: 1
tagged with: mnist
has title: Tensorflow export estimators for prediction
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/50613631
answer count: 1
tagged with: python
favorite count: 0

http://stackoverflow.com/a/50579768
downvote count: 0
answers question: http://stackoverflow.com/q/50579671
has comment: http://stackoverflow.com/comment/88169042
type: Answer
has body: You can do it with a for loop that iterates over the two lists: list_1 = ['4', '6' ,'8', '8'] list_2 = ['a', 'b', 'c', 'd'] new_dict = {} for k, v in zip(list_1, list_2): if k in new_dict: new_dict[k] += ', ' + v else: new_dict[k] = v There might be efficiency problems for huge dictionaries, but it will work just fine in simple cases. Thanks to @Ev. Kounis and @bruno desthuilliers that pointed out a few improvements to the original answer. coldspeed's answer is more efficient than mine, I keep this one here because it is still correct and I don't see the point in deleting it.
has comment: http://stackoverflow.com/comment/88169245
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/88168970
has comment: http://stackoverflow.com/comment/88168874

http://stackoverflow.com/q/50596307
accepted answer: http://stackoverflow.com/a/50596351
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has body: I am trying to make groups of x days within groups of another column. For some reason the grouping behavior is changed when I add another level of grouping. See toy example below: Create a random dataframe with 40 consecutive dates, an ID column and random values: import numpy as np import pandas as pd df = pd.DataFrame( {'dates':pd.date_range('2018-1-1',periods=40,freq='D'), 'id': np.concatenate((np.repeat(1,10),np.repeat(2,30))), 'amount':np.random.random(40) } ) I want to group by id first and then make groups of let's say 7 consecutive days within these groups. I do: (df .groupby(['id',pd.Grouper(key='dates',freq='7D')]) .amount .agg(['mean','count']) ) And the output is: mean count id dates 1 2018-01-01 0.591755 7 2018-01-08 0.701657 3 2 2018-01-08 0.235837 4 2018-01-15 0.650085 7 2018-01-22 0.463854 7 2018-01-29 0.643556 7 2018-02-05 0.459864 5 There is something weird going on in the second group! I would expect to see 4 groups of 7 and then a last group of 2. When I run the same code on a dataframe with just the id=2 I do get what I actually expect: df2=df[df.id==2] (df2 .groupby(['id',pd.Grouper(key='dates',freq='7D')]) .amount .agg(['mean','count']) ) Output mean count id dates 2 2018-01-11 0.389343 7 2018-01-18 0.672550 7 2018-01-25 0.486620 7 2018-02-01 0.520816 7 2018-02-08 0.529915 2 What is going on here? Is it first creating a group of 4 in the id=2 group because the last group in id=1 group was only 3 rows? This is not what I want to do!
tagged with: datetime
tagged with: python
has title: Weird behavior with pandas Grouper method with datetime objects
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50596351
upvote count: 3
type: Question
score: 3
tagged with: group-by

http://stackoverflow.com/q/50636884
answer count: 1
favorite count: 0
type: UnansweredQuestion
has body: I'm using a ordered dict like this from django.utils.translation import ugettext as _ 'alumni': OrderedDict([ ('profession', { 'name': _('Occupation'), 'field': 'profession', 'key': 'profession', 'type': 'text' })]) And I've the translation on the file like msgid "Occupation" msgstr "Meslek" But the transaltion is not working. I'd tried it like this on shell and it seems to be working. In [1]: from django.utils import translation In [2]: translation.activate('tr') In [3]: translation.gettext('Occupation') Out[3]: 'Meslek' All other translations are working fine, Issue is only with the ones defined on dict.
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/64859950
has comment: http://stackoverflow.com/comment/91450089
score: 2
downvote count: 0
type: Question
upvote count: 2
has title: Django translations not getting translated on dictionary values
has comment: http://stackoverflow.com/comment/108251907

http://stackoverflow.com/q/50671181
upvote count: 5
score: 4
has title: How do I get certain values from a list in a for loop in Python?
has answer: http://stackoverflow.com/a/62396414
has answer: http://stackoverflow.com/a/50677074
has body: If I have a list: myList = ['car a', 5000, 'great value', 'car b', 8000, 'good value'] How can I do this in a for loop : (print(myList[0]) print(myList[3])) adding 3 till the end of the list. I tried: for carName in myList: carName = myList[0 + 3]&gt; # I am stuck here print carName Thanks for the help!
has answer: http://stackoverflow.com/a/50671255
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88352107
type: UnansweredQuestion
tagged with: python
answer count: 4
tagged with: list
has answer: http://stackoverflow.com/a/61554171
downvote count: 1
type: Question
tagged with: for-loop

http://stackoverflow.com/a/50613475
upvote count: 1
has comment: http://stackoverflow.com/comment/88237029
has comment: http://stackoverflow.com/comment/88236853
has comment: http://stackoverflow.com/comment/88237151
has comment: http://stackoverflow.com/comment/88236848
answers question: http://stackoverflow.com/q/50613188
downvote count: 0
has comment: http://stackoverflow.com/comment/88237097
has comment: http://stackoverflow.com/comment/88237057
type: Answer
has body: The JSON file should contain a list of strings. You should read the current contents of the file into a variable, append to the variable, then rewrite the file. with open("data.json", "r") as f: data = json.load(f) data.append(firstname + ' ' + lastname+ ' - ' + email) with open("data.json", "w") as f: json.dump(data, f)
has comment: http://stackoverflow.com/comment/88236907
score: 1
has comment: http://stackoverflow.com/comment/88237015

http://stackoverflow.com/comment/97481323
type: AnswerComment
score: 0
type: Comment
has text: I think you misunderstood a question. I've exported 3d camera from 3d application. I also rendered out the animation. The question is. How do you place a 3d card with a shader of rendered image, so that when viewed through a scanline renderer in Nuke, the images match.
comment on: http://stackoverflow.com/a/54402060

http://stackoverflow.com/comment/88238567
has text: Or change your regexp to `r'.* (.*?) (.*)'`
comment on: http://stackoverflow.com/q/50614223
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/88360011
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50670158
score: 0
has text: hi Christopher, i am using a proxy install that the company gave me (not sure i can write it here) after trying to import cx_Oracle and got the message: ModuleNotFoundError: No module named 'cx_Oracle' Thank you

http://stackoverflow.com/comment/88102519
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50545715
has text: I get a syntax error at, print("{n} = "{c}".format(n=name, c=count")
type: Comment

http://stackoverflow.com/q/50633582
score: 4
tagged with: tensorflow-estimator
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/50688663
has body: I see that tensorflow train_and_evaluate works a bit different as compared the traditional tf.estimator train followed by evaluate. train_and_evaluate creates multiple sessions based on the number of epochs while train only creates one session. I was wondering what are the key differences between train_and_evaluate and train followed by evaluate. Which one is recommended?.
downvote count: 0
has title: What is recommended? tensorflow train_and_evaluate or estimator.train, estimator.evaluate
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/88282810
has text: I already checked that and the answer uses Ubuntu Server 10.04. There's different conventions for MacOS that make a lot of solutions for Ubuntu/Linux-distributed OSs' generally separate.
comment on: http://stackoverflow.com/q/50636155
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88402386
type: QuestionComment
has text: @NishantPatel Yes, after that step it is correct. However the first time I convert it it is not.
score: 0
comment on: http://stackoverflow.com/q/50694693
type: Comment

regression
tags question: http://stackoverflow.com/q/50601916
tags question: http://stackoverflow.com/q/50691339
tags question: http://stackoverflow.com/q/50586912
tags question: http://stackoverflow.com/q/50612681
tag name: regression
type: Tag
tags question: http://stackoverflow.com/q/50552142
tags question: http://stackoverflow.com/q/50619818

http://stackoverflow.com/comment/100871083
comment on: http://stackoverflow.com/a/51716314
score: 1
has text: But what's the reason why?
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50632506
has answer: http://stackoverflow.com/a/50632571
has title: Convert GeoSeries to regular float type?
type: Question
tagged with: geopandas
tagged with: python
has answer: http://stackoverflow.com/a/50632852
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/50633034
has comment: http://stackoverflow.com/comment/88275736
accepted answer: http://stackoverflow.com/a/50633034
has body: I am trying to convert a column of a GeoDataFrame object containing numpy float64 datatypes into an array of regular float types. I'm wondering if there is a way to do this without iterating through the entire column? trajectory_features['points'][fid] = gdf[key] Is what I have to far, but when I try to serialize it to JSON it gives the error that the numpy data type float64 is not JSON serializable. gdf is the GeoDataFrame and trajectory_features is a 2 dimensional dictionary.
tagged with: numpy
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/88275791
possible better answer: http://stackoverflow.com/a/50632571
type: AnsweredQuestion

http://stackoverflow.com/comment/88295603
has text: Is there any other way to for incremental crawling ?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50621419

http://stackoverflow.com/comment/88392231
type: Comment
has text: One easy answer is to use numpy. Check out this: https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html Load your bools into a numpy array 'mybools', then test np.where(mybools == True), the returning array has the index positions of the bools that are true. Easy to check how many are true by checking length.
score: 0
comment on: http://stackoverflow.com/q/50690826
type: QuestionComment

http://stackoverflow.com/comment/88388740
has text: @ImportanceOfBeingErnest the purpose is not plotting, but I need round intervals for another set of calculations involving numpy arrays.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50688992

http://stackoverflow.com/comment/88209018
score: 1
has text: Show what you've tried already
comment on: http://stackoverflow.com/q/50599943
type: Comment
type: QuestionComment

http://stackoverflow.com/a/59619692
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50552059
upvote count: 1
has body: Before creating new environment you can specify: conda config --set shortcuts true After that, you can see shortcuts for your new environment.
score: 1

http://stackoverflow.com/comment/88247873
type: AnswerComment
has text: This was close. It also requires json.loads after the json.dumps. valid_json_string = json.loads(json_string)
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50600201

http://stackoverflow.com/q/50582821
linked to: http://stackoverflow.com/q/18659858
downvote count: 0
has comment: http://stackoverflow.com/comment/88176275
favorite count: 0
possible better answer: http://stackoverflow.com/a/50697671
has comment: http://stackoverflow.com/comment/88177899
has answer: http://stackoverflow.com/a/50697671
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50584423
tagged with: scientific-computing
upvote count: 3
has body: I am trying to get a "grid" of n-dimensional probability vectors---vectors in which every entry is between 0 and 1, and all entries add up to 1. I wish to have every possible vector in which coordinates can take any of a number v of evenly spaced values between 0 and 1. In order to illustrate this, what follows is a horribly inefficient implementation, for n = 3 and v = 3: from itertools import product grid_redundant = product([0, .5, 1], repeat=3) grid = [point for point in grid_redundant if sum(point)==1] now grid contains [(0, 0, 1), (0, 0.5, 0.5), (0, 1, 0), (0.5, 0, 0.5), (0.5, 0.5, 0), (1, 0, 0)]. This "implementation" is just terrible for higher dimensional and more fine-grained grids. Is there a good way to do this, perhaps using numpy? I could perhaps add a point on motivation: I would be perfectly happy if just sampling from a random distribution gave me sufficiently extreme points, but it does not. See this question. The "grid" I am after is not random, but systematically sweeps the simplex (the space of probability vectors.)
type: Question
tagged with: numpy
score: 3
has comment: http://stackoverflow.com/comment/88178113
has title: A grid over probability vectors
accepted answer: http://stackoverflow.com/a/50584423
answer count: 2
has comment: http://stackoverflow.com/comment/88176067

http://stackoverflow.com/a/50770495
type: Answer
answers question: http://stackoverflow.com/q/50690865
has comment: http://stackoverflow.com/comment/88548492
score: 0
has body: the thing is when I evaluate the model I just resize the image to 224*224, it is different from the training data processing(crop image to 224*224), so the probability distribution of validation set is kind of different from the training set(different manifolds), and originally I thought it is not a big deal and the changes in distribution would not be dramatic. after I revised that, there is a significant drop in the validation error

http://stackoverflow.com/comment/119589242
score: 0
type: Comment
type: QuestionComment
has text: The entire premise of this question is wrong. Colab instances are provisioned with a full CUDA toolkit. What version can vary depending on the hardware you wind up with. On any stock instance you can run nvcc to see which toolkit version you have been provisioned with
comment on: http://stackoverflow.com/q/50560395

http://stackoverflow.com/comment/88390887
type: Comment
comment on: http://stackoverflow.com/a/50690390
has text: @Joooeey That design is fine, it just adds another layer of inheritance between `Protector` and `GermanShepherd`. I didn't put that in because you don't have multiple types of dogs in your example, and I think my answer should stand unless you edit your question to have that extra layer as well.
type: AnswerComment
score: 0

http://stackoverflow.com/q/50696949
upvote count: 2
type: UnansweredQuestion
tagged with: python
has title: distance calculation whan Nan is the maximum possible distance
answer count: 0
score: 1
has body: I really tried my best to find a solution to my problem. Given that I have 2 customers with several attributes as given below; cust1 = [4.0, 75.0, 2.0, 155.0, 58.0, 3.0, 7.0, 4.0, 0.0, 4.0, 0.0, 1.0, 1.0, nan, 2.0, 1.0, 3.0, 0.0, 0.0, 2.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, nan, 13.0, 8260.0, 41.5, 91.0, 65.0, 4.8, 5.7, 7.4, 4.2, 301.0, 31.0, 91.0, 10.0, 196.0, 121.0, 139.0, 4.7, 10.0, 54.0, 72.0, 1.1, 225.0, 42.0, 0.69, 104.0, nan, 59.3, 13.0, 41.5, 100.0, 31.1, 65.0, 4.8, 139.0, 4.7, 11.0, 57.0, nan, nan, nan, nan, 11.0, 1.4, 138.0, 2.7, 9.0, 2.0, 1.0, nan, 2.0, 2.0, 2.0, 2.0, 2.0, 3.0, 1.0, 2.0, nan, 5.0, 5.0, 5.0, 3.0, 3.0, 2.0, 3.0, 3.0, 3.0, 1.0, 2.0, 3.0, 4.0, 2.0, 2.0, 2.0, 5.0, 5.0, 5.0, 5.0, 1.0, 2.0, 1.0, 1.0, 2.0, 2.0, 0.0, 2.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 2.0, 2.0, 1.0, 2.0, 1.0, 0.0, 1.0, 0.0, 0.0, 2.0, 1.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 2.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 2.0, 2.0, 0.0, 0.0, 1.0, 1.0, 1.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, 1.0, 2.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] cust2 = [4.0, 78.0, 2.0, 160.0, 62.0, 3.0, 5.0, 3.0, 0.0, 6.0, 0.0, 1.0, 1.0, nan, 24.0, 0.0, 2.0, 0.0, 0.0, 2.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, nan, 11.4, 7620.0, 35.4, 92.0, 106.0, 5.2, 5.4, 7.2, 4.5, 206.0, 40.0, 23.0, 6.0, 169.0, 102.0, 137.0, 6.0, 9.2, 76.0, 38.0, 3.5, 927.0, 83.0, 0.66, 84.0, nan, 64.2, 11.4, 35.4, 100.0, 32.2, 106.0, 5.2, 137.0, 6.0, 10.0, 62.6, nan, nan, nan, nan, 23.0, 1.5, 138.0, 3.4, 9.0, 2.0, 1.0, nan, 2.0, 2.0, 2.0, 2.0, 1.0, 4.0, 1.0, 2.0, nan, 5.0, 5.0, 4.0, 3.0, 3.0, 1.0, 3.0, 3.0, 3.0, 2.0, 2.0, 4.0, 5.0, 2.0, 3.0, 2.0, 5.0, 5.0, 5.0, 4.0, 1.0, 3.0, 1.0, 1.0, 2.0, 2.0, 0.0, 2.0, 0.0, 1.0, 0.0, 0.0, …
downvote count: 1
type: Question
tagged with: cosine-similarity
tagged with: distance
has comment: http://stackoverflow.com/comment/88402989
tagged with: euclidean-distance
has comment: http://stackoverflow.com/comment/88403531
tagged with: nan
favorite count: 0

http://stackoverflow.com/a/50607289
type: Answer
has comment: http://stackoverflow.com/comment/88225082
score: 24
answers question: http://stackoverflow.com/q/50607128
upvote count: 24
has body: output = {} for k, v in source.items(): # always start at the root. current = output # This is the part you're struggling with. pieces = k.split('_') # iterate from the beginning until the second to last place for piece in pieces[:-1]: if not piece in current: # if a dict doesn't exist at an index, then create one current[piece] = {} # as you walk into the structure, update your current location current = current[piece] # The reason you're using the second to last is because the last place # represents the place you're actually storing the item current[pieces[-1]] = v
downvote count: 0
has comment: http://stackoverflow.com/comment/88226996

http://stackoverflow.com/comment/88291129
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50638442
has text: @Priya oh, I was sure I read it well, look like I didn't :( . Thanks, that explain it. (Though I feel like if only those are *allowed* it shouldn't be possible to use others imo...)
score: 0

http://stackoverflow.com/q/50551196
has comment: http://stackoverflow.com/comment/88113411
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: maps
upvote count: 1
tagged with: markers
downvote count: 1
type: Question
has body: I am trying to use some basic functions of the library Mapview. here's the documentation. I just need to set the map on a certain city and then to create some markers (the coordinates will be given from another function). This is my code: from kivy.garden.mapview import MapView, MapMarker from kivy.app import App class MapViewApp(App): def build(self): map = MapView(zoom=11, lat=50.6394, lon=3.057, double_tap_zoom = True) marker_1 = MapMarker(lon=50.6394, lat=3.057) map.add_marker(marker_1) return map MapViewApp().run() However a problem occurs. The coordinates should point a city in France - Lille. It centers the map on Lille but the marker appears somewhere in Africa. How can it be fixed?
has title: Problems with markers in Mapview
has comment: http://stackoverflow.com/comment/88122176
has answer: http://stackoverflow.com/a/67180420
score: 0
answer count: 1
tagged with: kivy

http://stackoverflow.com/q/50589063
has body: I have a pandas Series containing some strings s = pd.Series(['a', 'b', 'c', 'd', 'a'], index=[1, 2, 3, 4, 5]) How can I get a serie of True/False based on equality of a string? For example I want to check the positions of all 'a' and from the example above I want to get as a result True, False, False, False, True
has title: How to get True/False mask from Pandas Series?
tagged with: mask
has comment: http://stackoverflow.com/comment/88187472
type: Question
linked to: http://stackoverflow.com/q/15315452
score: -1
has comment: http://stackoverflow.com/comment/88187528
upvote count: 2
tagged with: boolean
answer count: 2
downvote count: 3
tagged with: pandas
favorite count: 0
tagged with: series
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50589162
duplicate of: http://stackoverflow.com/q/15315452
tagged with: python
has answer: http://stackoverflow.com/a/50589109

http://stackoverflow.com/a/50656394
has comment: http://stackoverflow.com/comment/88330143
has body: Pygame itself does not have support for HTML/CSS rendering. Instead either you have to parse it yourself, and add support that way. Or use a supported toolkit such as PyQt Webview, pywebkitgtk or TkHtml. See here for some more options. OK so I misunderstood your question. So it looks like you are after this. So it looks like use html2text to get raw text. Also consider BeautifulSoup over this library since it is still being maintained. Example with BeautifulSoup: from bs4 import BeautifulSoup soup = BeautifulSoup(html) print soup.get_text() Then use one of the methods here to create a widget in your Pygame window and add the raw text to it. Also see the Pygame documentation on creating GUI. As a side note, not using Pygame would make the task easier and using a traditional GUI toolkit like Tkinter/PyQt/WxPython/PyGtk since they all have methods of getting text.
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50656365
has comment: http://stackoverflow.com/comment/88329304
score: 1
answers question: http://stackoverflow.com/q/50656365
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88329571
has comment: http://stackoverflow.com/comment/88329048
type: Answer
has comment: http://stackoverflow.com/comment/88330198

http://stackoverflow.com/q/50611571
type: UnansweredQuestion
has title: How to extract items within nested lists containing nested dictionaries in python
has comment: http://stackoverflow.com/comment/88233182
tagged with: nested
type: Question
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/41777880
has body: I have a nested item list containing complicated nested dictionaries as shown: y = [ { "page": 1, "pages": 304, "per_page": "1", "total": 304 }, [ { "adminregion": { "id": "", "value": "" }, "capitalCity": "Oranjestad", "id": "ABW", "incomeLevel": { "id": "HIC", "value": "High income" }, "iso2Code": "AW", "latitude": "12.5167", "lendingType": { "id": "LNX", "value": "Not classified" }, "longitude": "-70.0167", "name": "Aruba", "region": { "id": "LCN", "value": "Latin America &amp; Caribbean " } } ]] and I am trying to extract the "id" values and store them somewhere in a database. What I've tried so far is (not successful): print([i['id'] for i in y[1]]) and: for i in y[1]: for j in i: print(j) but no luck Thanks a million..
tagged with: list
score: 0
duplicate of: http://stackoverflow.com/q/41777880
has comment: http://stackoverflow.com/comment/88233304
has comment: http://stackoverflow.com/comment/88234202
linked to: http://stackoverflow.com/q/14048948
answer count: 0

http://stackoverflow.com/comment/88365047
has text: Then you should clarify your question, to say that you want to implement padding by reflection.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50677669

http://stackoverflow.com/comment/88129536
has text: so if it needs more than 15 threads, will it use them? need to make sure my [facebook video downloader](https://4fb.site/) doesnt run out of resources. now it uses heroku but time to move python app to my own server
score: 0
comment on: http://stackoverflow.com/q/50557795
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88256025
type: QuestionComment
has text: Please ensure the API key you have entered is not your real API key.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50622697

web
tags question: http://stackoverflow.com/q/50551399
tags question: http://stackoverflow.com/q/50693257
tags question: http://stackoverflow.com/q/50697834
type: Tag
tag name: web
tags question: http://stackoverflow.com/q/50673930
tags question: http://stackoverflow.com/q/50545613
tags question: http://stackoverflow.com/q/50657309

http://stackoverflow.com/q/50592213
has title: timestamp as variable in sql query
tagged with: python
has comment: http://stackoverflow.com/comment/88193847
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50592484
tagged with: mysql
type: Question
duplicate of: http://stackoverflow.com/q/902408
score: 0
has body: I want to use the timestamp-value as a variable for a MySQL-query in python. tsmin = 1527573750; tsmax = 1527574050; command = "SELECT * FROM #CMD# WHERE data.#CMD#.TimesTamp BETWEEN FROM_UNIXTIME(tsmin) AND FROM_UNIXTIME(tsmax)"; This gives this error: _mysql_exceptions.OperationalError: (1054, "Unknown column 'tsmin' in 'where clause'") When I use following command it works fine. command = "SELECT * FROM #CMD# WHERE data.#CMD#.TimesTamp BETWEEN FROM_UNIXTIME(1527573750) AND FROM_UNIXTIME(1527574050)" Anyone who can help me?
linked to: http://stackoverflow.com/q/902408
answer count: 1
accepted answer: http://stackoverflow.com/a/50592484

http://stackoverflow.com/comment/88312590
score: 0
comment on: http://stackoverflow.com/a/50648562
type: AnswerComment
type: Comment
has text: Please see https://docs.python.org/3/faq/windows.html for some hints getting set up but yes, cmd.exe. I use Linux for all my python stuff so I'm not the best person to ask for more details.

http://stackoverflow.com/comment/88189729
score: 0
has text: Thanks! All of these solutions really helped. :)
type: Comment
comment on: http://stackoverflow.com/q/50590106
type: QuestionComment

http://stackoverflow.com/comment/88130961
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50547543
has text: @wilmert The condition leverages broadcasting. Comparing arrays of shapes 5x1 and 4 results in the following: 1) operand 2 gets promoted to ndim 2 by inserting axes _on the left_ -> 1x4 2) 5x1 and 1x4 both get promoted to 5x4 by repeating along the enlarged axis (only conceptually, no data are actually copied) 3) the actual element-wise comparison is done resulting in a boolean 5x4 array.

http://stackoverflow.com/q/50600592
upvote count: 0
score: -2
has body: model.py class Employee(models.Model): employeeid=models.IntegerField(primary_key=True, editable=True) fullname=models.CharField(max_length=500) location=models.ForeignKey(Location, on_delete=models.CASCADE) phone=models.IntegerField('phone number') user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) def __unicode__(self): return self.fullname def __str__(self): return self.fullname admin.py class holidayAdmin(FilterUserAdmin): form = select2_modelform(holiday,attrs={'width': '250px'}) fields= ('type','start_date','end_date','employees','image_ref','note',) list_display = ('type','created_by','last_modified_by','start_date', 'end_date','note','employees') error ERRORS: : (admin.E109) The value of 'list_display[6]' must not be a ManyToManyField.
has answer: http://stackoverflow.com/a/50601171
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: how to disable the data of many to many field in admin site
downvote count: 2
type: Question

http://stackoverflow.com/comment/88185296
comment on: http://stackoverflow.com/q/50587961
type: QuestionComment
has text: `button.place(...)` is just an alias for `button.place_configure`. That is why the error message mentions `place_configure`.
type: Comment
score: 0

http://stackoverflow.com/a/50579001
has comment: http://stackoverflow.com/comment/88168374
type: Answer
has body: I believe need m2 = df['Code'].isin(['A1','A2','A3','A4','B1','B2','B4','C1']) #create helper column for unique categories df['Code_new'] = df['Code'].where(m2).ffill() df['Code_new'] = (df['Code_new'] + '_' + df['Code_new'].ne(df['Code_new'].shift()).cumsum().astype(str)) #check by start values and filter all columns without A m1 = df['Code_new'].str.startswith(tuple(['A1','A2','A3','A4'])).fillna(False) df'Numx','Numy' = df'Numx','Numy'.mask(df['Code_new'].duplicated() &amp; ~m1) #replace by forward filling only starting with C mask = df['Code_new'].str.startswith('C').fillna(False) df.loc[mask, ['Numx','Numy']] = df.loc[mask, ['Numx','Numy']].ffill() print (df) Code Numx Numy Code_new 0 A1 30.2 1.9 A1_1 1 A1 30.5 2.3 A1_1 2 30.6 2.5 A1_1 3 B1 35.6 2.2 B1_2 4 B1 NaN NaN B1_2 5 A2 45.5 3.1 A2_3 6 A2 46.1 3.4 A2_3 7 48.1 3.6 A2_3 8 B2 48.5 3.7 B2_4 9 B2 NaN NaN B2_4 10 NaN NaN B2_4 11 A3 30.5 2.3 A3_5 12 A3 30.6 2.5 A3_5 13 A3 35.6 2.2 A3_5 14 40.2 2.5 A3_5 15 B1 45.5 3.1 B1_6 16 NaN NaN B1_6 17 B4 48.1 3.6 B4_7 18 B4 NaN NaN B4_7 19 A2 42.2 5.4 A2_8 20 A2 40.1 6.5 A2_8 21 A1 48.5 8.5 A1_9 22 A1 42.2 2.2 A1_9 23 A1_9 24 B4 48.5 8.5 B4_10 25 B4 NaN NaN B4_10 26 C1 43.1 2.3 C1_11 27 C1 43.1 2.3 C1_11 28 43.1 2.3 C1_11 29 43.1 2.3 C1_11 30 D1 43.1 2.3 C1_11 31 43.1 2.3 C1_11 32 B2 45.1 3.2 B2_12
has comment: http://stackoverflow.com/comment/88168280
has comment: http://stackoverflow.com/comment/88168341
upvote count: 2
has comment: http://stackoverflow.com/comment/88168687
score: 2
has comment: http://stackoverflow.com/comment/88168577
accepted answer of: http://stackoverflow.com/q/50577760
has comment: http://stackoverflow.com/comment/88168643
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50577760
has comment: http://stackoverflow.com/comment/88173092
has comment: http://stackoverflow.com/comment/88175655

http://stackoverflow.com/a/50633746
answers question: http://stackoverflow.com/q/50552853
accepted answer of: http://stackoverflow.com/q/50552853
score: 5
upvote count: 5
downvote count: 0
has body: You can transform the data to tidy format and use FacetGrid df = df.melt(id_vars=['id', 'diagnosis']) df[:3] # id diagnosis variable value # 0 842302 M radius_mean 17.99 # 1 842517 M radius_mean 20.57 # 2 84300903 M radius_mean 19.69 cols = ['radius_mean', 'texture_mean', 'perimeter_mean', 'area_mean'] grid = sns.axisgrid.FacetGrid(df[df.variable.isin(cols)], col='variable', sharey=False) grid.map(sns.boxplot, 'diagnosis','value')
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/88171112
has text: if I execute it without the `.get` I get an error: `AttributeError: _Environ instance has no __call__ method`. I am also using Ubuntu 16.04.4 LTS.
comment on: http://stackoverflow.com/a/50579829
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88104567
comment on: http://stackoverflow.com/q/50546892
type: Comment
score: 1
has text: I'm not sure if I agree with the dupe you linked just because it's not clear to me if that question is asking about shebangs in general or about shebangs with `/usr/bin/env` specifically. Looks unclear to me.
type: QuestionComment

http://stackoverflow.com/a/50675922
has body: The example in your quote requires apiai (second line). A good starting point is looking for those libraries and how they work. They often have example code and/or references to examples. Take a look at https://github.com/dialogflow/dialogflow-nodejs-client or https://github.com/dialogflow/dialogflow-nodejs-client-v2 A quick online search for 'dialogflow node.js' gives tons of examples, either in Youtube form, Medium articles or oter instructables.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50643873

http://stackoverflow.com/comment/88326276
type: QuestionComment
has text: Did you intend to *destroy* your first class definition with this assignment `a = b(2)`?
comment on: http://stackoverflow.com/q/50657695
score: 0
type: Comment

http://stackoverflow.com/q/50696680
tagged with: pyspark
tagged with: dataframe
score: 0
has body: I have a PySpark dataframe of the form: +--------------------+ | col_name| +--------------------+ |[val1, val2, val3] | |[val1, val2, val3] | +--------------------+ I want to convert it to an RDD which is of a matrix form, so that I can ultimately convert it to a RowMatrix. However, when I use df.rdd, it gives me an RDD which has Row objects such as: [Row(col_name=DenseVector([val1, val2, val3])), Row(col_name=DenseVector([val1, val2, val3]))] How do I work around this, so that I have an RDD with just my DenseVector objects and not Row objects which have the DenseVectors., i.e. of the form: [DenseVector([val1, val2, val3]), DenseVector([val1, val2, val3])] How to achieve that?
tagged with: apache-spark
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
has title: PySpark: DataFrame to RDD[DenseVector] and not RDD[Row]
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88403113
tagged with: python
tagged with: rdd
has comment: http://stackoverflow.com/comment/88402929
has comment: http://stackoverflow.com/comment/88402909
duplicate of: http://stackoverflow.com/q/35720330
linked to: http://stackoverflow.com/q/37999657
has answer: http://stackoverflow.com/a/50696833
type: Question
linked to: http://stackoverflow.com/q/35720330
has comment: http://stackoverflow.com/comment/88402572

http://stackoverflow.com/comment/88363104
type: AnswerComment
comment on: http://stackoverflow.com/a/50676729
score: 0
type: Comment
has text: If I understand correctly he wants to keep only 1 one selected randomly in every row.

http://stackoverflow.com/a/50558501
has body: You can use pd.crosstab(df.ID, df.Names). Output: Names fire func_A rain tunc_B ID 1 0 1 0 1 2 1 0 1 0
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50558472
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50558472

http://stackoverflow.com/comment/88424351
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50690440
has text: How I can I modify above code to take care of col_E and col_D

http://stackoverflow.com/q/50667938
accepted answer: http://stackoverflow.com/a/50668000
has body: I am trying to find the difference between two times in Python. It is guaranteed that the times are on the same day. #For example s1 = '13:00' s2 = '12:58' The difference between these two times should be 2 mins. The output should be: 2 This is my code: from datetime import datetime s1 = '13:00' s2 = '12:58' FMT = '%H:%M' tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT) print(tdelta) But it returns: -1 day, 23:58:00 How can i fix this and return my time as: 2
linked to: http://stackoverflow.com/q/3096953
favorite count: 0
tagged with: python-3.x
has title: How to find the difference between two times in Python?
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/88345691
possible better answer: http://stackoverflow.com/a/50668311
has comment: http://stackoverflow.com/comment/88345666
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50668311
score: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88345686
has answer: http://stackoverflow.com/a/50668000
linked to: http://stackoverflow.com/q/45603232
answer count: 2
has comment: http://stackoverflow.com/comment/88345678
has comment: http://stackoverflow.com/comment/88345687

http://stackoverflow.com/q/50571812
type: AnsweredQuestion
has body: Im looking for a fast way to do this: def load(screen): x, y = (screen.get_size()[0], screen.get_size()[1]) list = [] out = [] for pln in range(x): for prn in range(y): liste.append(screen.get_at([pln, prn])) out.append(copy.deepcopy(list)) list = [] print ("finish") #print(len(out)) return copy.deepcopy((out)) screen is the object created with pygame.display.set_mode(*size*) here, I try to write the colors from get_at in a 2d-list. Is there a built-in function from Pygame to do this? I mean, this Code is far to slow...
has comment: http://stackoverflow.com/comment/88153339
type: Question
downvote count: 4
upvote count: 0
accepted answer: http://stackoverflow.com/a/50572072
answer count: 1
has title: Efficient loading of Pygamescreens to 2D-lists
has comment: http://stackoverflow.com/comment/88153424
has comment: http://stackoverflow.com/comment/88153523
has comment: http://stackoverflow.com/comment/88153448
tagged with: pygame
favorite count: 0
score: -4
has comment: http://stackoverflow.com/comment/88153364
tagged with: python
has answer: http://stackoverflow.com/a/50572072

http://stackoverflow.com/comment/88237828
comment on: http://stackoverflow.com/q/50575422
score: 0
type: Comment
type: QuestionComment
has text: Please email this question (including this VI screenshot) to support@enthought.com

http://stackoverflow.com/comment/88175229
has text: Thanks for your tips and i'll do it. I'm a newbie on stackoverflow and i'm glad to have so much kind help.
type: QuestionComment
comment on: http://stackoverflow.com/q/50559480
type: Comment
score: 0

resampling
tags question: http://stackoverflow.com/q/50559789
tags question: http://stackoverflow.com/q/50652046
tag name: resampling
type: Tag
tags question: http://stackoverflow.com/q/50661686

http://stackoverflow.com/comment/88259344
type: QuestionComment
has text: Both the code and the plot are definitely not from MATLAB, so I removed the tag.
comment on: http://stackoverflow.com/q/50624643
score: 0
type: Comment

http://stackoverflow.com/a/50584647
answers question: http://stackoverflow.com/q/50584596
has body: try this, l=['CAST','ARTICLES','SANITARY','JAN','CLAUSES','SPECIAL','ENDORSEMENT'] df['GOODS_DESC']=df['GOODS_DESC'].str.replace('|'.join(l),'').str.strip() Output: GOODS_DESC 0 IRON 1 CRATES 2 IRON 3 ANIMAL AND VEGETABLE 4 SETTLING AGENT 5 6 CONDITIONS WARRANTIES 7 CARGO ISM 8 QUANTITY DECLARED IRON CRATES
downvote count: 0
has comment: http://stackoverflow.com/comment/88178782
upvote count: 1
has comment: http://stackoverflow.com/comment/88178692
type: Answer
score: 1

http://stackoverflow.com/comment/88415793
comment on: http://stackoverflow.com/q/50686206
score: 0
type: Comment
type: QuestionComment
has text: Did you try to install from the rdkit channel? conda install -c https://conda.anaconda.org/rdkit rdkit

http://stackoverflow.com/a/50653376
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50653351
answers question: http://stackoverflow.com/q/50653351
has body: This occurs because the reverse() function is created as an attribute of the first_list object. Thus, reverse() is not a function you can call and provide first_list as an argument. It's important to know that everything in Python is an object, and every object has attributes. For example, if I create a list in the python interpreter, new_list = [1, 2, 3], and then do dir(new_list) (this shows the attributes of new_list), I get the following: &gt;&gt;&gt; new_list = [1, 2, 3] &gt;&gt;&gt; dir(new_list) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] And therein lies the reverse function for the object list.
type: Answer
upvote count: 2

http://stackoverflow.com/comment/88434085
has text: Also, there's a lot of variable overlap - " with open(list1, "r") as list1: " - "as list1" could be "as fd1" (so that you don't lose the original value of list1 that represents the file name)
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50672975
type: AnswerComment

http://stackoverflow.com/comment/88314551
comment on: http://stackoverflow.com/q/50651772
has text: Can we see your code? We can't help you otherwise.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/95962066
comment on: http://stackoverflow.com/a/50567397
score: 0
type: Comment
has text: This isn't working for me. The class that I am trying to make a singleton is being creating multiple times, depending on where else in my code it gets called. I realized that one of those calls is coming out of code that is called in a thread, which is why I tried this code, but it doesn't seem to have any different effect. Did this code work? Did anyone make changes to it?
type: AnswerComment

http://stackoverflow.com/q/50611888
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/88234268
tagged with: scrapy
type: Question
has title: Scrapy to follow links in a specific div
has comment: http://stackoverflow.com/comment/88234417
has comment: http://stackoverflow.com/comment/88234233
score: 0
has body: I tried to follow related links but I am not having any success. I am getting "Crawled 0 pages" with my scrapy script (brand new to scrapy). I am trying to crawl a series of pages that looks has a section like this: Find Listings A Segment-number-one Segment-number-two Segment-number-three And so on... When following the links, the next level has data that I want to parse out some data. When I parse the page directly, it pulls the data I want. However, I am not getting the script to follow each of the links above. My current script: class MySpider(CrawlSpider): name = "domain" allowed_domains = ["domain.com"] start_urls = ['http://URL/STATE-City1', 'http://URL/STATE-City2'] rules = (Rule(LinkExtractor(allow=r"/STATE-\w+/*?$"), callback='parse_contents'),) def parse_contents(self, response): for bus in response.css('div.resultWrapper'): yield { 'field1': bus.css('div.resultInner a::text').extract_first(), 'field2': bus.css('p.field2::text').extract_first(), 'field3': bus.css('span.field3::text').extract_first(), 'field4': bus.css('span.field4::text').extract(), 'field5' : bus.css('span.field5::text').extract(), } Thanks for any help. BCBB
has comment: http://stackoverflow.com/comment/88234382
type: UnansweredQuestion

http://stackoverflow.com/comment/88567370
type: AnswerComment
has text: Put the code in hastebin or pastebin so I can see the whole thing
comment on: http://stackoverflow.com/a/50690008
type: Comment
score: 0

http://stackoverflow.com/a/50632115
type: Answer
score: 0
has body: Pre-Answer Warning I am not a C/C++ programmer. It is possible there are bad C++ practices in here, so please use what you find in this answer with a grain of salt. The requirements to achieve this behavior are the following: We must get the directory of the custom executable We must set the PYTHONHOME environment variable to %executable_dir%\runtime We must set the PYTHONPATH environment variable to %executable_dir%\apps so that python knows where our python packages are living. This also clears out any system wide settings so that the distribution doesn't use other python environment settings I don't know if it's necessary, but I am adding the runtime directory at the front of the path We have to dynamically load the Py_Main function from the desired dll. Since we are not expecting the runtime to be on the path before execution, we must find the dll dynamically from %executable_dir%\runtime\python36.dll. The following source code works when I compiled in Visual Studio 2017, with no Python Header files and no dll specified in the Linker // source code for custom my_python_application1 // requires _CRT_SECURE_NO_WARNINGS flag to compile deprecated path operations #include "stdafx.h" #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;iostream&gt; #include "Windows.h" #include "Shlwapi.h" // #include "Python.h" // don't need this as we are dynamically loading the library of choice #pragma comment(lib, "Shlwapi.lib") __pragma(warning(disable:4996)) // # _CRT_SECURE_NO_DEPRECIATE wchar_t SWITCH[] = L"-m"; wchar_t APP[] = L"my_python_application1.main"; typedef int(__stdcall *py_main_function)(int, wchar_t**); int wmain(int argc, wchar_t **argv) { int newargc; newargc = argc + 2; // determine the path of the executable so we know the absolute path // of the python runtime and application directories wchar_t executable_dir[MAX_PATH]; if (GetModuleFileName(NULL, executable_dir, MAX_PATH) == 0) return -1; PathRemoveFileSpec(executable_dir); std::wstring executabl…
answers question: http://stackoverflow.com/q/50627930

http://stackoverflow.com/comment/88384990
type: Comment
comment on: http://stackoverflow.com/a/50683098
score: 0
type: AnswerComment
has text: I uninstalled them all then re-installed it and it worked. It just worked with rpc.firstmicroservice.mymethod() with firstmicroservice as the name. That's all I needed. Thank you all for your help !

http://stackoverflow.com/q/50551765
favorite count: 0
has comment: http://stackoverflow.com/comment/88117285
tagged with: python-multithreading
has comment: http://stackoverflow.com/comment/88116215
tagged with: python
tagged with: python-3.x
has body: I have a Tkinter GUI with multiple buttons each which call different functions using threads. I have to automate the clicking of the buttons in sequence. So I am using a single START button, which will click first button, wait for the respective function's execution to complete and then click the next button, and so on. I used threads as I needed to keep a Progressbar running while any function is running. I am also changing the color of the button text from Red (not run yet) to Blue (being run) to Green (finished execution). I know I need to use join() somewhere, but it's not working. This current code runs all the button invoke() methods at once, and not in a sequence. import tkinter as tk from tkinter import ttk from threading import Thread def sample_function(): for i in range(1,10000) : print(i) def run_function(name, func,btn_variable): # Disable all buttons btn_variable.configure(style = 'blue.TButton') processing_bar.start(interval=10) print(name, 'started') func() processing_bar.stop() print(name, 'stopped') btn_variable.configure(style = 'green.TButton') def run_thread(name, func,btn_variable): Thread(target=run_function, args=(name, func,btn_variable)).start() def prepare_clicked(): run_thread('prepare', sample_function,prepare_btn) prepare_btn.configure(style = 'green.TButton') def social_clicked(): run_thread('social', sample_function,social_btn) social_btn.configure(style = 'green.TButton') def anomaly_clicked(): run_thread('anomaly', sample_function,anomaly_btn) anomaly_btn.configure(style = 'green.TButton') def scoring_clicked(): run_thread('scoring', sample_function,scoring_btn) scoring_btn.configure(style = 'green.TButton') def dashboard_clicked(): run_thread('dashboard', sample_function,dashboard_btn) dashboard_btn.configure(style = 'green.TButton') def start_all(): prepare_btn.invoke() anomaly_btn.invoke() social_btn.invoke() scoring_btn.invoke() dashboard_btn.invoke() window = tk.Tk() #window = tk.Toplevel() topFrame = tk.Frame(window) bottomFra…
tagged with: tkinter
tagged with: multithreading
upvote count: 1
has answer: http://stackoverflow.com/a/50615603
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/50615603
type: Question
has title: Tkinter: Scheduling Sequential Threads executed via button clicks
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/88278304
score: 0
type: AnswerComment
type: Comment
has text: Thanks DyZ. However, this does not work either... For example, if I show df1, there is no changes...
comment on: http://stackoverflow.com/a/50634075

http://stackoverflow.com/comment/88374672
comment on: http://stackoverflow.com/q/50669030
score: 0
type: Comment
type: QuestionComment
has text: @hcheung I put the cs on 26, then mosi = 6, miso = 16, and sclk = 11, and that didn't work. I then realized that some of the pins were labeled with mosi, miso, and sclk, so I tried cs = 26, mosi = 10, miso = 9, and sclk = 11, and that didn't work either. I really have no ideas what pins are actually usable for what, so do you have any suggestions for what pins I should use for the other 3?

http://stackoverflow.com/q/50659491
has title: How to combine two 2D array into the following in Python?
tagged with: numpy
possible better answer: http://stackoverflow.com/a/50659535
answer count: 2
tagged with: arrays
score: 0
has body: Suppose I have 2 2D array as follows: A = [[1, 2], [3, 4]] B = [[5, 6, 7], [8, 9, 8], [7, 6, 5]] Is there a numpy function to combine A and B into C as follows? C = [[1, 2, 0, 0, 0], [3, 4, 0, 0, 0], [0, 0, 5, 6, 7], [0, 0, 8, 9, 8], [0, 0, 7, 6, 5]] Thanks
tagged with: matrix
has comment: http://stackoverflow.com/comment/88328950
tagged with: python
has answer: http://stackoverflow.com/a/50659535
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88328965
has answer: http://stackoverflow.com/a/50659544
accepted answer: http://stackoverflow.com/a/50659544
has comment: http://stackoverflow.com/comment/88334151

http://stackoverflow.com/a/50616822
score: 0
type: Answer
has body: You can use tf.nn.dropout method. Dropout randomly 'drops'(or 'kill') connection between nodes. Say, you want to kill 70% of connections. then you can do like, ... fc_0 = tf.nn.relu(tf.matmul(x, W_fc0) + b_fc0) fc_0 = tf.nn.dropout(fc_0, keep_prob=0.3) fc_1 = tf.nn.relu(tf.matmul(fc_0, W_fc1) + b_fc1) fc_1 = tf.nn.dropout(fc_1, keep_prob=0.3) ...
accepted answer of: http://stackoverflow.com/q/50616680
answers question: http://stackoverflow.com/q/50616680
type: AcceptedAnswer

http://stackoverflow.com/comment/88408846
has text: my questions is just about performance between scala and python, I care about it because I need to implement the function in spark, I know how to use spark in both scala and python, thanks anyway.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50698160
type: Comment

http://stackoverflow.com/comment/88171447
has text: Add as first line in .py file: `# coding: utf-8`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50580918
score: 0

http://stackoverflow.com/comment/88201958
comment on: http://stackoverflow.com/q/50596400
score: 0
type: Comment
type: QuestionComment
has text: @Megalng ok but it happend to me with the module "arcpy" too.

http://stackoverflow.com/q/50636901
type: Question
has comment: http://stackoverflow.com/comment/88283952
has comment: http://stackoverflow.com/comment/107692054
has comment: http://stackoverflow.com/comment/88336447
downvote count: 0
has comment: http://stackoverflow.com/comment/88325249
favorite count: 0
has comment: http://stackoverflow.com/comment/88285593
has comment: http://stackoverflow.com/comment/88294788
has comment: http://stackoverflow.com/comment/88285567
has comment: http://stackoverflow.com/comment/88285261
has comment: http://stackoverflow.com/comment/88285653
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88284345
has body: I am using MacOS HighSierra, django 1.11, and python 2.7.14. Whenever I set up the views and run the server, polls/1 returns a 404 error. I am following the official django course. The page says this - Page not found (404) Request Method: GET Request URL: http://localhost:8000/polls/1 Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^polls/ ^$ [name='index'] ^polls/ ^(?P&lt;question_id&gt;[0-9]+)/$, [name='detail'] ^polls/ ^(?P&lt;question_id&gt;[0-9]+)/results/$, [name='results'] ^polls/ ^(?P&lt;question_id&gt;[0-9]+)/vote/$, [name='vote'] ^admin/ The current path, polls/1, 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.
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88323391
score: 2
has comment: http://stackoverflow.com/comment/88285659
answer count: 0
has comment: http://stackoverflow.com/comment/88284010
has title: 404 error when setting up views in django 1.11 polls app
has comment: http://stackoverflow.com/comment/88285549
has comment: http://stackoverflow.com/comment/88323364

fonts
tags question: http://stackoverflow.com/q/50644295
type: Tag
tags question: http://stackoverflow.com/q/50598680
tag name: fonts

http://stackoverflow.com/comment/88213211
comment on: http://stackoverflow.com/a/50602026
has text: @JonProgrammer: you also need to specify `required=False` in the form then, since otherwise, default is *never* used.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88220073
has text: Ok, it seems I have more issues with my code. `()` executing a function. This is why my __init__ didn't do anything. I understand that now. The second problem is when I remove `()` in `self.ui.pushButton.clicked.connect(MyApp.combine_funcs(self.converter, self.showMessage))` I get an error `converter() takes 1 positional argument but 2 were given`. Converter function takes only `self` argument. What 2 arguments am I sending?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50604773
score: 0

http://stackoverflow.com/comment/88286463
type: AnswerComment
has text: @Joe your first suggestion on running in the cmd window worked as well calling the process from a cmd terminal using python script.py thanks so much. So far I’m seeing a bunch of error messages involving my bad code and other request rejection events from the backend lol
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50632443

http://stackoverflow.com/q/50566369
tagged with: backtrace
upvote count: 2
tagged with: exception
tagged with: python
score: 2
type: AnsweredQuestion
has body: In an except block I want to raise the same exception but without the stack trace and without the information that this exception has been raised as direct cause of another exception. (and without modifying sys.tracebacklimit globally) Additionally I have a very clumsy exception class which parses and modifies the message text so I can't just reproduce it. My current approach is try: deeply_nested_function_that_raises_exception() except ClumsyExceptionBaseClass as exc: cls, code, msg = exc.__class__, exc.code, exc.msg raise cls("Error: %d %s" % (code, msg)) What I'm doing here is de-composing the exception information, re-assemble a new exception with a message which will be parsed and split into error code and message in the constructor and raise it from outside the except block in order to forget all trace information. Is there a more pythonic way to do this? All I want is get rid of the noisy (and useless in my case) trace back while keeping the information contained in the exception object..
has answer: http://stackoverflow.com/a/50777738
type: Question
has comment: http://stackoverflow.com/comment/88142944
has comment: http://stackoverflow.com/comment/88143481
tagged with: traceback
has title: How to re-raise the same exception without the traceback?
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88143063
accepted answer: http://stackoverflow.com/a/50777738
favorite count: 0

http://stackoverflow.com/a/50671422
type: Answer
has comment: http://stackoverflow.com/comment/88352788
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/88352898
has comment: http://stackoverflow.com/comment/88352699
downvote count: 0
answers question: http://stackoverflow.com/q/50671382
has body: You could try something like this: df.groupby('userID').apply(lambda x: x['name'].tolist()) Example: Given a df: userID name 0 U1001 a 1 U1001 b 2 U1001 c 3 U1002 d 4 U1002 e 5 U1003 f &gt;&gt;&gt; df.groupby('userID').apply(lambda x: x['name'].tolist()) userID U1001 [a, b, c] U1002 [d, e] U1003 [f] dtype: object

http://stackoverflow.com/q/50678078
has title: Use arguments of one function as arguments for other function
type: Question
has comment: http://stackoverflow.com/comment/88365903
has answer: http://stackoverflow.com/a/50678250
linked to: http://stackoverflow.com/q/277922
tagged with: arguments
tagged with: python
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50678237
tagged with: keyword
type: UnansweredQuestion
tagged with: keyword-argument
has body: Suppose I have the following function def f(x,y,**kwargs): if 'z' in kwargs: z = kwargs['z'] else: z = 0 print(x + y + z) which takes two arguments and an optional keyword argument. I now want to get a function g that works just as f but for which the value of z is predetermined. Hence, I could do the following def g(x,y): z = 3 f(x,y, z = 3) But what can I do if I do not know the number of non-keyword arguments that f takes. I can get the list of these arguments by args = inspect.getargspec(f)[0] But, if I now define g as g(args): z = 3 f(args, z=z) this of course does not work as only one mandatory argument is passed to f. How do I get around this? That is, if I have a function that takes keyword arguments, how do I define a second function exactly the same expect that the keyword arguments take predeterminde values?

http://stackoverflow.com/q/50569419
tagged with: python-decorators
favorite count: 0
has comment: http://stackoverflow.com/comment/88149455
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50569518
accepted answer: http://stackoverflow.com/a/50569518
has body: I'm trying to document a decorator, but am not sure where the doc string should go. Technically, it's the inner wrapper that contains the parameters I want to document, but a user is going to be applying the outer function name as the decorator. For example, def change_case(func): """Does the doc string go here """ def _wrapper(s, case=None): """Or, does the doc string go here? """ if case == 'Upper': s = s.upper() elif case == 'Lower': s = s.lower() return func(s) return _wrapper @change_case def echo(s): return s echo('Test', case='Upper') In the above, does the doc string go after change_case() or _wrapper(). I'm leaning towards the former.
type: Question
has comment: http://stackoverflow.com/comment/88149030
downvote count: 2
score: 5
upvote count: 7
has title: Where to put the doc string for a decorator
answer count: 1
tagged with: decorator
tagged with: docstring
linked to: http://stackoverflow.com/q/1782843
has comment: http://stackoverflow.com/comment/88149636
tagged with: python

http://stackoverflow.com/q/50638907
score: 0
has comment: http://stackoverflow.com/comment/88287806
has body: I am pulling data from a csv file and have it printing out three letter country codes from each row of data. How do I make python identify the number of occurrences of each unique country code from the outputted data? Here is what I have that is printing the country codes. import csv with open('2017CountryData.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') for row in readCSV: countries = row[1] print(countries)
has title: Identifying and counting distinct outputs in python from csv file
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50638996
linked to: http://stackoverflow.com/q/2600191
has comment: http://stackoverflow.com/comment/88287873
type: Question
answer count: 1

http://stackoverflow.com/comment/88189651
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50587012
score: 0
has text: It might be more clever to somehow incorporate what you additionally want to see in your solution directly into the optimization problem. For now you are asking how to get different solutions, when there is only one unique solution (the minimum).

http://stackoverflow.com/comment/88385228
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50648127
has text: No this should be done simply by the order of the respective commands. E.g. if you call `plt.close()` and after that `ax.set_whatever` it will simply not work. Also mind which frame is really the last one.

http://stackoverflow.com/comment/88198712
type: Comment
type: QuestionComment
has text: ...`else 0`. remove `var =`, you've already got that at the beginning of the line.
comment on: http://stackoverflow.com/q/50594778
score: 4

mechanicalsoup
tag name: mechanicalsoup
tags question: http://stackoverflow.com/q/50628120
tags question: http://stackoverflow.com/q/50664029
type: Tag
tags question: http://stackoverflow.com/q/50592760
tags question: http://stackoverflow.com/q/50660786
tags question: http://stackoverflow.com/q/50667997

file
tags question: http://stackoverflow.com/q/50631741
type: Tag
tags question: http://stackoverflow.com/q/50686655
tags question: http://stackoverflow.com/q/50633385
tags question: http://stackoverflow.com/q/50694428
tags question: http://stackoverflow.com/q/50546631
tags question: http://stackoverflow.com/q/50659391
tags question: http://stackoverflow.com/q/50567281
tags question: http://stackoverflow.com/q/50569253
tag name: file
tags question: http://stackoverflow.com/q/50645349
tags question: http://stackoverflow.com/q/50565297
tags question: http://stackoverflow.com/q/50691116
tags question: http://stackoverflow.com/q/50642307
tags question: http://stackoverflow.com/q/50633762
tags question: http://stackoverflow.com/q/50557727
tags question: http://stackoverflow.com/q/50632664
tags question: http://stackoverflow.com/q/50649754
tags question: http://stackoverflow.com/q/50629892
tags question: http://stackoverflow.com/q/50683675
tags question: http://stackoverflow.com/q/50552512
tags question: http://stackoverflow.com/q/50607037
tags question: http://stackoverflow.com/q/50574021
tags question: http://stackoverflow.com/q/50681662
tags question: http://stackoverflow.com/q/50573900
tags question: http://stackoverflow.com/q/50654624
tags question: http://stackoverflow.com/q/50678334
tags question: http://stackoverflow.com/q/50583261
tags question: http://stackoverflow.com/q/50561552

http://stackoverflow.com/comment/88225871
has text: What makes you think it's a `Python` package?
score: 4
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50607994

http://stackoverflow.com/comment/88174776
type: AnswerComment
has text: Also, can you tell me how can I add a username(use of substitution ) in my template?
comment on: http://stackoverflow.com/a/50579198
type: Comment
score: 0

http://stackoverflow.com/a/50706270
has body: This was hard to answer for a couple reasons: You keep using the word "implement", but I'm pretty sure you mean "call" instead. I'm going to assume that here, since conditionally implementing something is rarely needed. Your use of the class here is confusing. It isn't actually needed in this case, so it's just complicating things. I'm going to reduce it down to just: def DATA(): X.append(Y) Since that does the same thing as your existing code. To ask for user input, use input. input waits until the user presses Enter, then returns the typed text. You can use it here to wait for Enter to be pressed: x = [] y = [1,2,3,4] def data(): x.append(y) print("x before Enter is pressed:") print(x) input("Type Enter to continue...") data() #Call DATA similar to your original code print("x after Enter is pressed:") print(x) A couple extra notes: Function and variables names should be in lower case. Uppercase is reserved for class names, and even in those cases, only the first letter is uppercase. Ideally, you shouldn't be mutating global variables like x and y. They should be passed into the function, then the result should be returned.
score: 0
accepted answer of: http://stackoverflow.com/q/50685786
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50685786
type: Answer

http://stackoverflow.com/comment/88350077
type: AnswerComment
has text: Can you explain why this is needed? What happens vs. just doing the reshape(15,15,1) ?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50670160

http://stackoverflow.com/q/50660400
tagged with: python
tagged with: tensorflow
type: Question
has body: I have 2 2d tensors of the same size (let's say shape =[80,90]). I want to get the value of the variable whose absolute value is bigger elementwise. In python I would do something like this: mask = np.abs(a)&gt;np.abs(b) c = a*mask + b*~mask How do I do this in tensorflow while still being able to calculate gradients? I know I can do this: mask = tf.abs(a) &gt; tf.abs(b) but then: c= tf.cast(mask, tf.float32) * a + tf.cast(~mask, tf.float32) * b doesn't pass gradients as the cast operation doesn't pass gradients.
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50662027
has answer: http://stackoverflow.com/a/50660452
type: UnansweredQuestion
has title: getting the higher value out of two tensors elementwise in tensorflow

pca
tag name: pca
tags question: http://stackoverflow.com/q/50613294
tags question: http://stackoverflow.com/q/50671503
tags question: http://stackoverflow.com/q/50614069
type: Tag
tags question: http://stackoverflow.com/q/50654620
tags question: http://stackoverflow.com/q/50667849

http://stackoverflow.com/a/50588108
has body: Use apply: df['ranks'] = df['ranks'].apply(lambda x: x[0]['rank']) df['search_volume'] = df['search_volume'].apply(lambda x: x[0]['search_volume']) BONUS This one will work in your case, to make it a one-liner: df'ranks', 'search_volume' = df'ranks', 'search_volume'.applymap(lambda x: x[0].values()[0])
downvote count: 0
answers question: http://stackoverflow.com/q/50588059
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/comment/88120816
comment on: http://stackoverflow.com/q/50555000
score: 0
has text: Just look for the `min()` of `abs(score-user_score)`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50611171
tagged with: matplotlib
has title: Plot graph with multiple attributes similar to "hue" in Seaborn
score: 12
type: Question
upvote count: 12
downvote count: 0
tagged with: python-2.7
tagged with: pandas
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50680532
accepted answer: http://stackoverflow.com/a/50680532
has body: I have the following sample data set called df, where stage time is how many days to get there: id stage1_time stage_1_to_2_time stage_2_time stage_2_to_3_time stage3_time a 10 30 40 30 70 b 30 c 15 30 45 d I wrote the following script to get a scatter plot of stage1_time against a CDF: import pandas as pd import matplotlib.pyplot as plt import numpy as np import scipy.stats as stats dict = {'id': id, 'stage_1_time': [10, 30, 15, None], 'stage_1_to_2_time': [30, None, 30, None], 'stage_2_time' : [40, None, 45, None],'stage_2_to_3_time' : [30, None, None, None],'stage_3_time' : [70, None, None, None]} df = pd.DataFrame(dict) #create eCDF function def ecdf(df): n = len(df) x = np.sort(df) y = np.arange(1.0, n+1) / n return x, y def generate_scatter_plot(df): x, y = ecdf(df) plt.plot(x, y, marker='.', linestyle='none') plt.axvline(x.mean(), color='gray', linestyle='dashed', linewidth=2) #Add mean x_m = int(x.mean()) y_m = stats.percentileofscore(df.as_matrix(), x.mean())/100.0 plt.annotate('(%s,%s)' % (x_m,int(y_m*100)) , xy=(x_m,y_m), xytext=(10,-5), textcoords='offset points') percentiles= np.array([0,25,50,75,100]) x_p = np.percentile(df, percentiles) y_p = percentiles/100.0 plt.plot(x_p, y_p, marker='D', color='red', linestyle='none') # Overlay quartiles for x,y in zip(x_p, y_p): plt.annotate('%s' % int(x), xy=(x,y), xytext=(10,-5), textcoords='offset points') #Data to plot stage1_time = df['stage_1_time'].dropna().sort_values() #Scatter Plot stage1_time_scatter = generate_scatter_plot(pd.DataFrame({"df" : stage1_time.as_matrix()})) plt.title('Scatter Plot of Days to Stage1') plt.xlabel('Days to Stage1') plt.ylabel('Cumulative Probability') plt.legend(('Days to Stage1', "Mean", 'Quartiles'), loc='lower right') plt.margins(0.02) plt.show() Output: Currently I have number of days it took all who reached stage1 plotted against its cumulative probability, however what I am trying to achieve is that the scatter has three colors when I plot: those who reached stage1 and …
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/88434767
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50695038
has text: Thank you @Aran-Fey, the problem comes when I use "return", not "print", in the codes. I edited the question just now.

http://stackoverflow.com/a/50769555
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/50649827
answers question: http://stackoverflow.com/q/50649827
type: AcceptedAnswer
has body: Same problem as you Bob. Here is my workaround (not a complete fix but it does the job) : Copy/paste the entire sites-packages folder from the anaconda (or miniconda => works for me too) to the default python interpreter and switch to this default python.exe interpreter inside your project (Settings -> Project Interpreter). For example overwrite the folder C:\Miniconda3\Lib\site-packages to C:\Users\ YOUR_ACCOUNT\venv\Lib\site-packages After that run AND debug modes are both available. Hope this help !
upvote count: 1

http://stackoverflow.com/comment/88209395
score: 0
has text: Can you post the entire stacktrace?
comment on: http://stackoverflow.com/q/50597101
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50595536
has body: I came up with this short code without the use of any external libraries: array = [[0, 4],[2, 3],[4, 1],[0, 8],[3, 2],[4, 5],[6, 1],[0, 3],[1, 7],[2, 9]] temp = 0 out = [array[0]] for i in range(1,len(array)): if array[i][0] != 0: array[i][0] += temp out.append(array[i]) else: temp = array[i-1][0] print(out) which yields: [out]: [[0, 4], [2, 3], [4, 1], [7, 2], [8, 5], [10, 1], [11, 7], [12, 9]]
upvote count: 1
has comment: http://stackoverflow.com/comment/88200471
answers question: http://stackoverflow.com/q/50595150
type: AcceptedAnswer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/50595150
type: Answer

http://stackoverflow.com/comment/89136179
has text: There is one more scenario, I need to discuss. Suppose, df1_master has data AD in col_A, and that same data is not in A1col of df2_newValues, I want ouput in such a way that in output df it shows "#AD " in col_A instead of "AD"
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50690440

http://stackoverflow.com/a/50581583
has comment: http://stackoverflow.com/comment/88174251
has body: The problem here is that you try to open cv2.VideoCapture(1) both in the display(self) and in the capture(self). Set frame as self.frame in display(self) and use it in capture(self). Like this: def capture(self): time.sleep(2) #set the delay you want in frame now_time = strftime("%Y-%m-%d %H:%M:%S", gmtime()) img_location = './timelapse_focus/'+FolderName+'/'+ now_time +'.jpg' cv2.imwrite(img_location, self.frame) def display(self): # Create a VideoCapture object and read from input file # If the input is the camera, pass 0 instead of the video file name # Check if camera opened successfully camera = cv2.VideoCapture(1) if (camera.isOpened()== False): print("Error opening video stream or file") # Read until video is completed while(camera.isOpened()): # Capture frame-by-frame ret, self.frame = self.camera.read() if ret == True: # Display the resulting frame cv2.imshow('Frame',self.frame) # Press &lt;q&gt; on keyboard to exit if cv2.waitKey(25) &amp; 0xFF == ord('q'): break # Break the loop else: break # When everything done, release the video capture object camera.release() # Closes all the frames cv2.destroyAllWindows() for i in range (1,5): cv2.waitKey(1) This is only for capturing one frame each time you call capture(self). Otherwise you need to add a while loop and the method in a Thread in order not to crash your GUI.
type: Answer
has comment: http://stackoverflow.com/comment/88174698
has comment: http://stackoverflow.com/comment/88173895
score: 0
has comment: http://stackoverflow.com/comment/88173721
has comment: http://stackoverflow.com/comment/88172434
has comment: http://stackoverflow.com/comment/88173528
answers question: http://stackoverflow.com/q/50581260
has comment: http://stackoverflow.com/comment/88176654

http://stackoverflow.com/a/72553347
type: Answer
has body: The accepted answer requires an DB call, and specifically checks 1 field. In a more realistic scenario, you would be checking some subset of fields to be equal - likely ignoring PK's, creation timestamps, amongst other things. A more robust solution would be something like: class MyModel(Model): some_field_that_is_irrelevant_to_equivalence = models.CharField() some_char_field = models.CharField() some_integer_field = models.IntegerField() _equivalent_if_fields_equal = ( 'some_char_field', 'some_integer_field', ) def is_equivalent(self, other: 'MyModel') -> bool: """Returns True if the provided `other` instance of MyModel is effectively equivalent to self. Keyword Arguments: -- other: The other MyModel to compare this self to """ for field in self._equivalent_if_fields_equal: try: if getattr(self, field) != getattr(other, field): return False except AttributeError: raise AttributeError(f"All fields should be present on both instances. `{field}` is missing.") return True
score: 0
answers question: http://stackoverflow.com/q/50620564

http://stackoverflow.com/comment/88272844
type: Comment
comment on: http://stackoverflow.com/q/50620422
score: 0
type: QuestionComment
has text: No. My small matrix here is a trivial example of what I want to do. In practice these matrices are big. I am not interested in they diagonalisation algorithm but rather what data structure to use to achieve my goal.

http://stackoverflow.com/comment/103163485
has text: It fails with all-equal input like `[1, 1, 1, 1]` and outputs `2` instead of `1`.
comment on: http://stackoverflow.com/a/50638625
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88250392
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50617821
has text: that gives the mean value for 1-3,4-7,8-15,>16 separately Is there any way I could get the mean value for all the value of a single product(1-3+4-7+8-15+>16 )
type: AnswerComment

http://stackoverflow.com/q/50554698
type: Question
has body: I need a way to extract flags from a string and insert it into a dictionary. For example, this string: "--test arg1 arg2 --test2" would be {"test":"arg1 arg2", "test2":None}. It should also work with - instead of --, so "--test -test2 --test3 arg arg arg" I tried to use argparse, but I stopped using it as I didn't that it would call SystemExit. I also tried to use shlex.split(content), but it requires arguments to be in '', so I would still have to use a loop to change that. Is there some module that can do this? I looked on pip and couldn't find something like this. But I know something has to exist like this. Thanks! Edit: second example should parse to {"test":None, "test2":None, "test3": "arg arg arg"}
has comment: http://stackoverflow.com/comment/88120383
has answer: http://stackoverflow.com/a/50554808
has comment: http://stackoverflow.com/comment/88120284
has comment: http://stackoverflow.com/comment/88120392
answer count: 3
has comment: http://stackoverflow.com/comment/88120309
has title: Easy way to extract flags from a string
downvote count: 0
has comment: http://stackoverflow.com/comment/88120357
has comment: http://stackoverflow.com/comment/88120291
has comment: http://stackoverflow.com/comment/88120206
favorite count: 0
accepted answer: http://stackoverflow.com/a/50554808
possible better answer: http://stackoverflow.com/a/50554810
has answer: http://stackoverflow.com/a/50554810
tagged with: python
has comment: http://stackoverflow.com/comment/88120375
score: 2
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/50554901

http://stackoverflow.com/a/50651928
type: Answer
downvote count: 0
score: 1
has body: Or the way you started could end up something like below: import requests from bs4 import BeautifulSoup base_url="http://cbcs.fastvturesults.com/student/1sp15me00{}" data = [] for page in range(1,10,1): d = {} r = requests.get(base_url.format(page)) soup = BeautifulSoup(r.content,"html.parser") items = soup.find(class_="text-muted") if items: d["Name"] = items.previous_sibling d["USN"] = items.text.replace("(","").replace(")","") data.append(d) print(data) Output: [{'Name': 'Agnello Fernandes A ', 'USN': '1sp15me001'}, {'Name': 'Ajay Kumar V ', 'USN': '1sp15me002'}, {'Name': 'Ajay Rajendiran ', 'USN': '1sp15me003'}, {'Name': 'Amit Singh Yadav ', 'USN': '1sp15me004'}, {'Name': 'Ankit Mahato ', 'USN': '1sp15me006'}, {'Name': 'Antony Levin Fernandez D ', 'USN': '1sp15me008'}, {'Name': 'Ashish S ', 'USN': '1sp15me009'}]
answers question: http://stackoverflow.com/q/50650342
upvote count: 1

http://stackoverflow.com/comment/88373450
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50681949
score: 1
has text: use `argparse` module to take input from command line

http://stackoverflow.com/a/50620875
accepted answer of: http://stackoverflow.com/q/50596612
answers question: http://stackoverflow.com/q/50596612
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
has body: Even though your initial problem looks solved, here are several bits of suggestions: It is more typical for one address (view) to display a form and another address to showswhat the result is when form is completed. File write operation looks more secure as a separate function. You need to close the file, or better use with. You do nothing on GET, so the function can be simplified. Here is the code with these ideas in mind: from flask import Flask, request, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('timer.html') @app.route("/result", methods= ['POST']) def result(): timer = request.form['timer_input'] log_message = "Water every {} days".format(timer) screen_message = "Sure, will water every {} days!".format(timer) save(log_message) return screen_message def save(text, filepath='timer.txt'): with open("timer.txt", "w") as f: f.write(text) app.run() templates/timer.html: Set frequencies (e.g. 2 = every 2 days):
upvote count: 1

http://stackoverflow.com/q/50672945
tagged with: chess
tagged with: fen
type: UnansweredQuestion
has title: generating FEN string from reed sensor chess board and only getting next best move from stockfish engine
downvote count: 1
type: Question
has body: I am building a chess playing robot, so after getting an 8x8 matrix of 1's and 0's from the reed switch sensors, how do I convert this matrix to a FEN string so that I can send this to the Stockfish engine? Also, I am having a lot of trouble in writing a Python script that can send the FEN string as input through UCI protocol and get the next best move. As of now, I don't really care about move validation/checking for check mate/promotion. I just want to get the next move. I have already gone through a lot of links about UCI protocol/API, Stockfish engine working, and programming with python, etc., but none of them have really helped me out. I would appreciate anyone's help!
score: -1
has answer: http://stackoverflow.com/a/51241281
upvote count: 0
answer count: 1
favorite count: 0
tagged with: python

http://stackoverflow.com/q/50620954
has comment: http://stackoverflow.com/comment/88251837
has answer: http://stackoverflow.com/a/59329910
tagged with: pycharm
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/137911002
downvote count: 3
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/88253736
has answer: http://stackoverflow.com/a/71405983
has answer: http://stackoverflow.com/a/76315475
linked to: http://stackoverflow.com/q/74303807
has answer: http://stackoverflow.com/a/69899161
has answer: http://stackoverflow.com/a/72281022
has comment: http://stackoverflow.com/comment/139287983
has comment: http://stackoverflow.com/comment/123558123
type: Question
has title: Process finished with exit code -1073741819 (0xC0000005) Pycharm
linked to: http://stackoverflow.com/q/70872411
has answer: http://stackoverflow.com/a/53706693
upvote count: 50
has answer: http://stackoverflow.com/a/69586586
favorite count: 0
score: 47
has body: I'm completly stuck on this. I keep getting error message Process finished with exit code -1073741819 (0xC0000005) I'm using pycharm with pyqt5.6 and qt5.6.2 and the problem started when I upgraded to these versions. I've tried searching as much as I can, but have not been able to find an answer. Can anyone help please?
has answer: http://stackoverflow.com/a/69898192
has answer: http://stackoverflow.com/a/50642745
has answer: http://stackoverflow.com/a/73217682
tagged with: python
answer count: 10

http://stackoverflow.com/comment/88266163
type: AnswerComment
type: Comment
has text: Do you have any suggestions for converting column headers into string?
comment on: http://stackoverflow.com/a/50627575
score: 0

http://stackoverflow.com/q/50584072
tagged with: neural-network
score: -1
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/50584637
tagged with: keras
favorite count: 0
has title: how to make a complicated output of a neural network keras
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50584640
has comment: http://stackoverflow.com/comment/88177753
has body: I would like to combine 2 neural networks which are showing probabilities of classes. One says that it is a cat on the image. The second says that the cat has a collar. How to use softmax activation function on the output of the neural network? Please, see the picture to understand the main idea:
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88178143

http://stackoverflow.com/q/50588274
tagged with: tensorflow
has body: I am trying to build a custom variational autoencoder network, where in I'm initializing the decoder weights using the transpose of the weights from the encoder layer, I couldn't find something native to tf.contrib.layers.fully_connected so I used tf.assign instead, here's my code for the layers: def inference_network(inputs, hidden_units, n_outputs): """Layer definition for the encoder layer.""" net = inputs with tf.variable_scope('inference_network', reuse=tf.AUTO_REUSE): for layer_idx, hidden_dim in enumerate(hidden_units): net = layers.fully_connected( net, num_outputs=hidden_dim, weights_regularizer=layers.l2_regularizer(training_params.weight_decay), scope='inf_layer_{}'.format(layer_idx)) add_layer_summary(net) z_mean = layers.fully_connected(net, num_outputs=n_outputs, activation_fn=None) z_log_sigma = layers.fully_connected( net, num_outputs=n_outputs, activation_fn=None) return z_mean, z_log_sigma def generation_network(inputs, decoder_units, n_x): """Define the decoder network.""" net = inputs # inputs here is the latent representation. with tf.variable_scope("generation_network", reuse=tf.AUTO_REUSE): assert(len(decoder_units) &gt;= 2) # First layer does not have a regularizer net = layers.fully_connected( net, decoder_units[0], scope="gen_layer_0", ) for idx, decoder_unit in enumerate([decoder_units[1], n_x], 1): net = layers.fully_connected( net, decoder_unit, scope="gen_layer_{}".format(idx), weights_regularizer=layers.l2_regularizer(training_params.weight_decay) ) # Assign the transpose of weights to the respective layers tf.assign(tf.get_variable("generation_network/gen_layer_1/weights"), tf.transpose(tf.get_variable("inference_network/inf_layer_1/weights"))) tf.assign(tf.get_variable("generation_network/gen_layer_1/bias"), tf.get_variable("generation_network/inf_layer_0/bias")) tf.assign(tf.get_variable("generation_network/gen_layer_2/weights"), tf.transpose(tf.get_variable("inference_network/inf_layer_0/weights"))) return net # x_recon It is wrapp…
type: UnansweredQuestion
downvote count: 0
has title: "ValueError: Trying to share variable $var, but specified dtype float32 and found dtype float64_ref" when trying to use get_variable
score: 7
favorite count: 0
type: Question
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/52246377
tagged with: machine-learning
upvote count: 7

http://stackoverflow.com/a/50630994
has comment: http://stackoverflow.com/comment/88298821
type: Answer
has comment: http://stackoverflow.com/comment/88275233
upvote count: 3
has comment: http://stackoverflow.com/comment/88272210
score: 3
has comment: http://stackoverflow.com/comment/88295987
has comment: http://stackoverflow.com/comment/88273991
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50630910
downvote count: 0
has comment: http://stackoverflow.com/comment/139008899
has comment: http://stackoverflow.com/comment/88272345
has comment: http://stackoverflow.com/comment/88297678
has body: You can turn your column names to datetime, and then sort them: df.columns = pd.to_datetime(df.columns, format='%b %y') df = df[sorted(df.columns)] &gt;&gt;&gt; df 2018-01-01 2018-02-01 2018-03-01 Flavor Vanilla 10.0 16.0 0.0 Chocolate 20.0 20.0 16.0 If you want your original string column names back simply add: df.columns = df.columns.strftime('%b %y') &gt;&gt;&gt; df Jan 18 Feb 18 Mar 18 Flavor Vanilla 10.0 16.0 0.0 Chocolate 20.0 20.0 16.0 An alternative is to do it all in one line using sorted with a key (credit to @SpghttCd for the idea): df[sorted(df.columns, key = lambda x: pd.to_datetime(x, format='%b %y'))]
accepted answer of: http://stackoverflow.com/q/50630910

http://stackoverflow.com/a/50632751
type: Answer
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50632256
has body: def divide_two_cols(df,tuple_list): for x,y,z in tuple_list: calc = df[x] /df[y] calc.replace(np.inf, 0, inplace=True) calc.fillna(value = 0, inplace = True) df[str(z)] = calc return df divide_two_cols(df, tuple_list_2 + tuple_list_3 + tuple_list_4 + ...)
accepted answer of: http://stackoverflow.com/q/50632256

http://stackoverflow.com/comment/132420757
has text: The inner loop **did** run. It performed zero iterations.
type: Comment
comment on: http://stackoverflow.com/q/50591233
score: 0
type: QuestionComment

http://stackoverflow.com/q/50693331
has comment: http://stackoverflow.com/comment/88396242
has title: How to speed up my python progrm
has answer: http://stackoverflow.com/a/50693377
type: UnansweredQuestion
score: 0
tagged with: python
tagged with: live-streaming
has body: def dehaze(img, light_intensity, windowSize, t0, w,s1,s2,siz,size1,dark_channel): global outimg for y in range(s1,siz): for x in range(s2,size1): t = 1.0 - (w * img.item(y, x, dark_channel) / light_intensity) outimg.itemset((y,x,0), max(0, min(((img.item(y,x,0) - light_intensity) / max(t, t0) + light_intensity), 255))) outimg.itemset((y,x,1), max(0, min(((img.item(y,x,1) - light_intensity) / max(t, t0) + light_intensity), 255))) outimg.itemset((y,x,2), max(0, min(((img.item(y,x,2) - light_intensity) / max(t, t0) + light_intensity), 255))) I implemented a program in python , i want to process live video it in a real time. But the above function is taking 1.5 sec to process one frame. Can anyone help me how can i get my desire output? I will be thankful if someone can help me.
type: Question
answer count: 1

http://stackoverflow.com/q/50602931
type: Question
score: 0
has title: Why getAttribute() not giving result in selenium?
answer count: 2
possible better answer: http://stackoverflow.com/a/50834705
has answer: http://stackoverflow.com/a/50603448
favorite count: 0
has comment: http://stackoverflow.com/comment/88215423
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50834705
has body: I was trying to scrap yellow pages Australia page. I searched for all the Piazza Restaurants in Australia. Now I want to fetch the email of every restaurant which is the value of data-email(an attribute of an anchor tag). Below is my code and I used getAttribute() on the anchor tag, but it is always giving me this error. TypeError: 'NoneType' object is not callable This is my code import csv from bs4 import BeautifulSoup import requests from selenium import webdriver from selenium.webdriver.common.by import By url = "https://www.yellowpages.com.au/search/listings?clue=Pizza+Restaurants&amp;locationClue=Sydney+CBD%2C+NSW&amp;lat=&amp;lon=" driver=webdriver.Chrome(executable_path="/usr/local/share/chromedriver") driver.get(url) pageSource=driver.page_source bsObj=BeautifulSoup(pageSource,'lxml') items=bsObj.find('div',{'class':'flow-layout outside-gap-large inside-gap inside-gap-large vertical'}).findAll('div',class_='cell in-area-cell find-show-more-trial middle-cell') for item in items: print(item.find('a',class_='contact contact-main contact-email ').getAttribute("data-email"))
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88215886
accepted answer: http://stackoverflow.com/a/50603448
has comment: http://stackoverflow.com/comment/88215636
tagged with: web-scraping
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/88287845
comment on: http://stackoverflow.com/q/50638492
has text: tried using NLS_LANG = 'UTF8' ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90301269
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51019597
type: Comment
has text: These code does not work on my computer as i have no admin rights

http://stackoverflow.com/q/50690999
favorite count: 0
type: Question
tagged with: semantic-segmentation
tagged with: python
answer count: 1
tagged with: conv-neural-network
upvote count: 1
tagged with: tensorflow
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51810785
has title: How to learn using my dataset on deeplab v3 plus
has body: In deeplab v3p, although I trained my data sets, it did not work. Why is it? My environment is the bellow: OS Platform and Distribution: Ubuntu 16.04 lts TensorFlow installed from: conda TensorFlow version: 18 Bazel version: no CUDA/cuDNN version: cuda 9 cudnn 7 GPU model and memory: titan x (2 cards), 64gb memory Exact command to reproduce: - I did the following work: a) generate simple dataset: The training image arranges two figures (circle and rect) randomly and draws color randomly. The label image is set to 0RGB(0, 0, 0) for the background, 1 RGB (1,1,1) for the rect, 2RGB(2, 2, 2) for the circle and 255 RGB (255, 255, 255) for the line as the segmentation. https://camo.qiitausercontent.com/2be21942628a85c46fd8ffb99e05b257b4b0c980/68747470733a2f2f71696974612d696d6167652d73746f72652e73332e616d617a6f6e6177732e636f6d2f302f39353633362f62653262306638632d333933322d363434322d336132342d6534306333613466653865612e706e67 https://camo.qiitausercontent.com/323d4f21d792138ebb52f994dc42cc0b5d3ab30d/68747470733a2f2f71696974612d696d6167652d73746f72652e73332e616d617a6f6e6177732e636f6d2f302f39353633362f34656633633261332d633533372d316134632d653633342d3165663632643734623166392e706e67 b) convert to tf.record In the build_voc2012_data.py, I changed file path from origin datasets to my datasets. Then, I ran it and created tf.record. c) training In the segmentation_dataset.py, I added DATASETS INFORMATION. _MYDATASETS_INFORMATION = DatasetDescriptor( splits_to_sizes={ 'train': 10000, 'trainval': 1000, 'val': 1000, }, num_classes=3, ignore_label=255, ) _DATASETS_INFORMATION = { 'cityscapes': _CITYSCAPES_INFORMATION, 'pascal_voc_seg': _PASCAL_VOC_SEG_INFORMATION, 'ade20k': _ADE20K_INFORMATION, 'mydata': _MYDATASETS_INFORMATION } Then, I started training. python train.py --logtostderr --train_split=trainval --model_variant=xception_65 --atrous_rates=6 --atrous_rates=12 --atrous_rates=18 --output_stride=16 --decoder_output_stride=4 --train_crop_size=513 --train_crop_size=513 --train_batch…
score: 1

http://stackoverflow.com/comment/88104197
has text: Wow, ok, no. I am not using the manual. Just some books. It's hard to put together what some of these books are saying into actual, working code.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50546654

http://stackoverflow.com/comment/88237128
comment on: http://stackoverflow.com/q/50612394
type: QuestionComment
type: Comment
score: 0
has text: "Ignoring exception in command move", you hadn't post that in your code.

http://stackoverflow.com/a/50596833
has comment: http://stackoverflow.com/comment/88204342
accepted answer of: http://stackoverflow.com/q/50596813
has body: I get a bit different output from your sample data, last and 3.rd row from end is merge correctly, also left join does not sorting by merging columns: data = pd.merge(survey,rel_attr, left_on = 'Choice', right_on = 'Type',how='left') print (data) ID CustomerType Choice ... Warranty Manufacture Type 0 1.0 Durability OEM ... 4.0 4.0 OEM 1 2.0 Price OEM ... 4.0 4.0 OEM 2 3.0 Durability OEM ... 4.0 4.0 OEM 3 4.0 Durability OEM ... 4.0 4.0 OEM 4 5.0 Durability OEM ... 4.0 4.0 OEM 5 6.0 ManufacturerCredibility OEM ... 4.0 4.0 OEM 6 7.0 Warranty OEM ... 4.0 4.0 OEM 7 8.0 ManufacturerCredibility OEM ... 4.0 4.0 OEM 8 9.0 Durability OEM ... 4.0 4.0 OEM 9 10.0 Price OEM ... 4.0 4.0 OEM 10 11.0 Durability TPN ... 1.0 1.0 TPN 11 12.0 Warranty OEM ... 4.0 4.0 OEM 12 13.0 Durability TPN ... 1.0 1.0 TPN [13 rows x 8 columns] If sorting it seems use inner join (default): data = pd.merge(survey,rel_attr, left_on = 'Choice', right_on = 'Type') #same as #data = pd.merge(survey,rel_attr, left_on = 'Choice', right_on = 'Type',how='inner') print (data) ID CustomerType Choice ... Warranty Manufacture Type 0 1.0 Durability OEM ... 4.0 4.0 OEM 1 2.0 Price OEM ... 4.0 4.0 OEM 2 3.0 Durability OEM ... 4.0 4.0 OEM 3 4.0 Durability OEM ... 4.0 4.0 OEM 4 5.0 Durability OEM ... 4.0 4.0 OEM 5 6.0 ManufacturerCredibility OEM ... 4.0 4.0 OEM 6 7.0 Warranty OEM ... 4.0 4.0 OEM 7 8.0 ManufacturerCredibility OEM ... 4.0 4.0 OEM 8 9.0 Durability OEM ... 4.0 4.0 OEM 9 10.0 Price OEM ... 4.0 4.0 OEM 10 12.0 Warranty OEM ... 4.0 4.0 OEM 11 11.0 Durability TPN ... 1.0 1.0 TPN 12 13.0 Durability TPN ... 1.0 1.0 TPN [13 rows x 8 columns]
has comment: http://stackoverflow.com/comment/88203928
answers question: http://stackoverflow.com/q/50596813
type: AcceptedAnswer
score: 0
type: Answer

http://stackoverflow.com/comment/88257604
comment on: http://stackoverflow.com/a/50577656
has text: Sure, you can see the script in main question and I saved it as Mtopo.py in desktop. To run it I use following command: **sudo mn --custom /home/bob/Desktop/Mtopo.py --topo=mytopo --mac** if you want more details, let me know what those are. @dside
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/88146032
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50543479
type: Comment
has text: I'm not sure I understand your question. I would simply eliminate duplicates, e.g. by changing `sorted(nums)` to `sorted(set(nums))`.

http://stackoverflow.com/q/50544151
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88099653
has comment: http://stackoverflow.com/comment/88099562
has comment: http://stackoverflow.com/comment/88099549
has comment: http://stackoverflow.com/comment/88099414
has comment: http://stackoverflow.com/comment/88099754
type: Question
has comment: http://stackoverflow.com/comment/88099571
answer count: 1
has body: models.py from __future__ import unicode_literals from django.core.urlresolvers import reverse from django.db import models from django.utils.text import slugify class Post(models.Model): title = models.CharField(max_length = 120) image = models.ImageField(null=True,blank=True) draft = models.BooleanField(default=False) publish = models.DateField(auto_now=False, auto_now_add=False) Updated = models.DateTimeField(auto_now=True,auto_now_add=False) Timestamp = models.DateTimeField(auto_now=False,auto_now_add=True) def __unicodde__(self): return self.Title def __str__(self): return self.title def get_absolute_url(self): #return 'posts/%s/' %(self.id) return reverse('posts:detail', kwargs={'id':self.id}) class Meta: ordering = ["-Timestamp","Updated"] forms.py from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = [ "title", "Content", "image", "draft", "publish", ] and terminal : jayu@broadwell-gt2:~/Desktop/trydjango19$ python manage.py migrate Operations to perform: Apply all migrations: admin, contenttypes, posts, auth, sessions Running migrations: Rendering model states... DONE Applying posts.0002_auto_20180526_0745...Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) /migration.py", line 123, in apply operation.database_forwards(self.app_label, schema_editor, old_state, proje…
score: 0
has title: TypeError: expected string or buffer when trying to migrate database
has comment: http://stackoverflow.com/comment/88101206
has comment: http://stackoverflow.com/comment/88099416
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50545938

http://stackoverflow.com/q/50569140
has comment: http://stackoverflow.com/comment/88149590
has body: I use celery for doing snmp requests with easysnmp library which have a C interface. The problem is lots of time is being wasted on I/O. I know that I should use eventlet or gevent in this kind of situations, but I don't know how to handle patching a third party library when it uses C extensions.
type: UnansweredQuestion
tagged with: python
tagged with: gevent
tagged with: celery
has title: using c extension library with gevent
type: Question
has comment: http://stackoverflow.com/comment/88175169
has answer: http://stackoverflow.com/a/50585353
answer count: 1
tagged with: eventlet
score: 0

http://stackoverflow.com/q/50576913
has comment: http://stackoverflow.com/comment/88163606
has comment: http://stackoverflow.com/comment/88163632
has comment: http://stackoverflow.com/comment/88163631
has comment: http://stackoverflow.com/comment/88163673
type: Question
has comment: http://stackoverflow.com/comment/88162962
has comment: http://stackoverflow.com/comment/88163565
answer count: 1
has body: I am loading data from a JSON file, which is in float format like 13.4567. The problem is that when I load it in Pandas, when I print that field I get the scientific notation like 1.34567e+06. Is there a way to set the field as regular float with 4 digits precision,as in the JSON source file, when I create the dataframe? Or do I have to massage the data after create the datafile? This is the code used to load the JSON: with open('myjson.json') as f: loaded_file = json.load(f) df = pd.DataFrame.from_dict(json_normalize(loaded_file), orient='column') print(df.result) The data file looks like this: [ { "info" : { "timestamp" : "2018-01-22 00:04:00.637000", "commit_hash" : "234234fdsfk3" }, "action" : { "time_sec" : 14.7584, "diff" : 12345.375, } }, { "info" : { "timestamp" : "2018-01-22 01:04:00.543000", "commit_hash" : "23eqdasfdsfk3" }, "action" : { "time_sec" : 12.3456, "diff" : 543546.2234, } } ]
has comment: http://stackoverflow.com/comment/88163611
has title: Pandas - set numeric value from a JSON as float with 4 digits precision
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/88163317
has comment: http://stackoverflow.com/comment/88163414
has comment: http://stackoverflow.com/comment/88163337
type: UnansweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50601386
has comment: http://stackoverflow.com/comment/88163568
has comment: http://stackoverflow.com/comment/88163299

http://stackoverflow.com/q/50647042
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
has title: TypeError: object supporting the buffer API required in flask api
type: AnsweredQuestion
has body: i have this code which i want to convert the password into md5 class UserLogin(Resource): def post(self): # Parse the arguments parser = reqparse.RequestParser() parser.add_argument('username') parser.add_argument('password') args = parser.parse_args() _user = args['username'] _userPassword = args['password'] _h = hashlib.md5(_userPassword.encode()) conn = mysql.connect() cursor = conn.cursor() cursor.execute('''select * from user where username = %s &amp;&amp; password = %s''', (_user, _h)) data = cursor.fetchall() return jsonify(data) but the error says: h = hashlib.md5(_userPassword.encode()) AttributeError: 'NoneType' object has no attribute 'encode' and when i remove the encode() from hashlib, the error return is:_h = hashlib.md5(_userPassword) TypeError: object supporting the buffer API required please help me. im using python3.6
downvote count: 0
score: 1
type: Question
tagged with: flask
has answer: http://stackoverflow.com/a/50647158
accepted answer: http://stackoverflow.com/a/50647158
tagged with: api

http://stackoverflow.com/a/50660983
score: 13
answers question: http://stackoverflow.com/q/50658884
has comment: http://stackoverflow.com/comment/88334937
downvote count: 0
has body: Despite the fact, that the answer of @MSeifert makes this answer quite obsolete, I'm still posting it, because it explains in more detail why the numba-version was slower than the numpy-version. As we will see, the main culprit are the different memory access patterns for numpy and numba. We can reproduce the behavior with much a simpler function: import numpy as np import numba as nb def just_sum(x2): return np.sum(x2, axis=1) @nb.jit('double[:](double[:, :])', nopython=True) def nb_just_sum(x2): return np.sum(x2, axis=1) x2=np.random.random((2048,2048)) And now the timings: &gt;&gt;&gt; %timeit just_sum(x) 2.33 ms ± 71.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) &gt;&gt;&gt; %timeit nb_just_sum(x) 33.7 ms ± 296 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) that means numpy is about 15 times faster! When compiling the numba code with annotations (e.g. numba --annotate-html sum.html numba_sum.py) we can see, how the sum is performed by numba (see the whole listing of the summation in the appendix): initialize the result-column add the whole first column to the result-column add the whole second column to the result-column and so on What is the problem of this approach? The memory layout! The array is stored in the row-major-order and thus reading it column-wise leads to much more cache-misses than reading it row-wise (which is what the numpy does). There is a great article which explains the possible cache effects. As we can see, the sum-implementation of numba is yet not very mature. However, from the above consideration the numba-implementation could be competitive for column-major-order (i.e. transposed matrix): &gt;&gt;&gt; %timeit just_sum(x.T) 3.09 ms ± 66.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) &gt;&gt;&gt; %timeit nb_just_sum(x.T) 3.58 ms ± 45.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) and it really is. As the code of @MSeifert has shown, the main advantage of numba is, that with its help we can red…
type: Answer
upvote count: 13
has comment: http://stackoverflow.com/comment/88356725
has comment: http://stackoverflow.com/comment/88392974

http://stackoverflow.com/q/50661184
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/50661381
tagged with: beautifulsoup
has title: How To Delay Python Requests Library To Allow Data To Populate
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88332600
has comment: http://stackoverflow.com/comment/88332576
has comment: http://stackoverflow.com/comment/88332595
has body: I am attempting to get the data from a webpage that is using .aspx. I am able to get all of my data but one value, because it appears it takes a few moments to load after the HTML loads. My code currently looks like this: import requests # Requesting HTML import bs4 as bs # Parsing HTML url_two = "https://www.walottery.com/Scratch/Explorer.aspx?id=1463" r_two = requests.get(url_two) soup = bs.BeautifulSoup(r_two.text, "lxml") print(soup.find("strong", {"class": "ticket-explorer-detail-info-printed"})) However, when I print the value is N/A. If you "inspect element" on the webpage, you can see the data change from what I pasted above to this: 2,428,400. How can I cause a slight delay so that my requests library allows me to get the calculated value, rather than "N/A"?
has answer: http://stackoverflow.com/a/50661381
tagged with: python-requests
has comment: http://stackoverflow.com/comment/88332444
type: Question
possible better answer: http://stackoverflow.com/a/50661366
has answer: http://stackoverflow.com/a/50661366
has comment: http://stackoverflow.com/comment/88332551

http://stackoverflow.com/q/50614741
type: AnsweredQuestion
has title: Create a Dataframe with lists of different sizes
has comment: http://stackoverflow.com/comment/88239403
type: Question
downvote count: 4
upvote count: 0
accepted answer: http://stackoverflow.com/a/50615496
has body: Changed to explain it better: A = ['one',None,None,None] B = [None,'two',None,None], C = [None,None,'three','Four'] If i create a Dataframe I would get: df = pd.DataFrame({'A': A, 'B':B, 'C':C }) df A B C 0 one None None 1 None two None 2 None None three 3 None None Four But I want a DataFrame similar to the Expected Output below Expected Output: A B C 0 one two three 1 None None four
tagged with: pandas
has comment: http://stackoverflow.com/comment/88239674
has comment: http://stackoverflow.com/comment/88239365
answer count: 1
has comment: http://stackoverflow.com/comment/88239317
favorite count: 0
has comment: http://stackoverflow.com/comment/88239404
has comment: http://stackoverflow.com/comment/88240438
has comment: http://stackoverflow.com/comment/88239544
has comment: http://stackoverflow.com/comment/88239354
score: -4
has answer: http://stackoverflow.com/a/50615496
tagged with: python
has comment: http://stackoverflow.com/comment/88239332

http://stackoverflow.com/q/50678605
has answer: http://stackoverflow.com/a/50678690
has title: Need to check json value is empty python
tagged with: python
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88366647
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/50678690
score: -1
has body: I have json result as like as below I want to check and exit the script if anyone of the 'Route' key value is empty. Value = [{"Route":[[{"Name":"abc.com","ResourceRecords":[{"Value":"1.1.1.1"}],"TTL":600,"Type":"A"}]]}, {"Route":[[{"Name":"xyz.com","ResourceRecords":[{"Value":"1.1.2.3"}],"TTL":600,"Type":"A"}]]}, {"Route":[[{"Name":"qaz,com","ResourceRecords":[{"Value":"1.1.2.4"}],"TTL":600,"Type":"A"}]]}]
type: Question
upvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/a/50690343
has body: Sorry i suppose i was too fast answering this question. I moved pdf.writer and pdf.reader to the begining of for loops as it seems to block code (stream for writing pdf).
answers question: http://stackoverflow.com/q/50690201
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50690201

http://stackoverflow.com/q/50661971
has body: I'm trying to understand python's asyncio library, and am somewhat surprised by the behavior of the following example: import asyncio import time from aiohttp import web _lock_table = {'locked': False} async def process(text): # wait while we're blocked while _lock_table['locked']: await asyncio.sleep(1) _lock_table['locked'] = True # hold the lock for three seconds # simulates "processing something" await asyncio.sleep(3) # release the lock _lock_table['locked'] = False async def request_handler(request): text = request.query.get('text') start_time = time.time() await process(text) end_time = time.time() return web.Response( body='text: {}, request time: {}'.format(text, end_time - start_time), content_type='text/html' ) app = web.Application() app.router.add_route('GET', '/', request_handler) web.run_app(app) If I start the above program and open up two requests to http://0.0.0.0:8080 I see that both requests take around three seconds to complete. Why is this? Shouldn't the second request be blocked by the first one that acquires the lock?
tagged with: python-asyncio
tagged with: python
has answer: http://stackoverflow.com/a/50670736
tagged with: aiohttp
upvote count: 2
type: UnansweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/88344862
has comment: http://stackoverflow.com/comment/88351591
has comment: http://stackoverflow.com/comment/88338040
has title: Python asyncio: blocking and race conditions
type: Question
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88349796
favorite count: 0

http://stackoverflow.com/comment/88327439
has text: Make sure the main.py file is in the search path of the interpreter.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50658677
type: Comment

http://stackoverflow.com/a/50566967
has comment: http://stackoverflow.com/comment/88149680
answers question: http://stackoverflow.com/q/50566870
type: Answer
has body: You can use predefined mean function df.mean(axis=1)
score: 0

http://stackoverflow.com/q/50582168
linked to: http://stackoverflow.com/q/49099163
accepted answer: http://stackoverflow.com/a/50582784
tagged with: pandas
favorite count: 0
has body: I want to get the names of the columns which have same values across all rows for each column. My data: A B C D 0 1 hi 2 a 1 3 hi 2 b 2 4 hi 2 c Desired output: ['B', 'C'] Code: import pandas as pd d = {'A': [1,3,4], 'B': ['hi','hi','hi'], 'C': [2,2,2], 'D': ['a','b','c']} df = pd.DataFrame(data=d) I've been playing around with df.columns and .any(), but can't figure out how to do this.
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/50582784
type: AnsweredQuestion
has title: Pandas: Get all columns that have constant value
has answer: http://stackoverflow.com/a/50582310
possible better answer: http://stackoverflow.com/a/50582195
score: 23
has answer: http://stackoverflow.com/a/50582195
downvote count: 1
upvote count: 24
type: Question
has answer: http://stackoverflow.com/a/50582251
has comment: http://stackoverflow.com/comment/88175606

http://stackoverflow.com/a/50586511
type: Answer
has body: The example illustrates a Scrollview of Stacklayout with Labels. Please refer to the example for details. The following Scrollview APIs were used in the example. ScrollView layout.bind(minimum_height=layout.setter('height')) bar_color Color of horizontal / vertical scroll bar, in RGBA format. bar_color is a ListProperty and defaults to [.7, .7, .7, .9]. bar_inactive_color Color of horizontal / vertical scroll bar (in RGBA format), when no scroll is happening. bar_inactive_color is a ListProperty and defaults to [.7, .7, .7, .2]. bar_width Width of the horizontal / vertical scroll bar. The width is interpreted as a height for the horizontal bar. bar_width is a NumericProperty and defaults to 2. effect_cls Class effect to instantiate for X and Y axis. effect_cls is an ObjectProperty and defaults to DampedScrollEffect. scroll_type Sets the type of scrolling to use for the content of the scrollview. Available options are: [‘content’], [‘bars’], [‘bars’, ‘content’]. [‘content’] Content is scrolled by dragging or swiping the content directly. [‘bars’] Content is scrolled by dragging or swiping the scoll bars. [‘bars’, ‘content’] Content is scrolled by either of the above methods. scroll_type is an OptionProperty and defaults to [‘content’]. Example main.py from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen from kivy.properties import ObjectProperty from kivy.uix.label import Label from kivy.clock import Clock class MenuScreen(Screen): pass class SettingsScreen(Screen): container = ObjectProperty(None) def __init__(self, **kwargs): super(SettingsScreen, self).__init__(**kwargs) Clock.schedule_once(self.setup_scrollview, 1) def setup_scrollview(self, dt): self.container.bind(minimum_height=self.container.setter('height')) self.add_text_inputs() def add_text_inputs(self): for x in range(30): self.container.add_widget(Label(text="Label {}".format(x), size_hint_y=None, height=40)) def new_message(self): msg = self.display.text print(msg) class Sc…
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50584908
has comment: http://stackoverflow.com/comment/107393839
answers question: http://stackoverflow.com/q/50584908
has comment: http://stackoverflow.com/comment/122503774
type: AcceptedAnswer
downvote count: 0

fillna
tags question: http://stackoverflow.com/q/50562571
type: Tag
tag name: fillna

http://stackoverflow.com/q/50597721
has title: How to use zeep to make SOAP requests in python
has body: here is my xml: <?xml version="1.0"?> <soapenv:Envelope> <soapenv:Header xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <wsse:Security soap:mustUnderstand="1" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"> <wsse:UsernameToken wsu:Id="UsernameToken-1" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"> <wsse:Username>USERNAME</wsse:Username> <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">1234</wsse:Password> </wsse:UsernameToken> </wsse:Security> </soapenv:Header> <soapenv:Body xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> david </soapenv:Body> </soapenv:Envelope> here is my demo: wsdl = '' client = Client( wsdl, wsse=UsernameToken('USERNAME', '1234')) response = client.service.get_method( EMAIL='david') it raised VadlidationError: ValidationError: Missing element OPRID (root.OPRID) I don't know why, please give me some help, thanks.
downvote count: 0
answer count: 1
favorite count: 0
tagged with: zeep
tagged with: soap
tagged with: python
has answer: http://stackoverflow.com/a/56257286
score: 2
upvote count: 2
type: UnansweredQuestion
tagged with: python-requests
type: Question

http://stackoverflow.com/comment/88227430
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50601068
score: 0
has text: The second is equivalent to `a[[[0],[1]], [0,1], :]`. `np.array([[0],[1]])` is (2,1), which broadcasts with a (2,) array to produce a `(2,2)` indexing selection. Another way to think of it is, `all planes`, `first 2 rows of each`, `all columns`.

http://stackoverflow.com/q/50564165
has title: Turn python sqlalchemy class into raw SQL (create table with foreign key)
score: 1
has body: I have a python app and I use sqlalchemy and posgreSQL. I have already some data in the DB and do not want to recreate it, so I want to add a table to the DB and keep all data (earlier I used alembic for that, but I want to use raw SQL this time). This is my new table, which I want to add to the DB in python: # User payed data class UserPayData(Base): __tablename__ = 'userspaydata' id = Column(Integer, primary_key=True) account_owner = Column(Text, nullable=False) IBAN = Column(Text, nullable=False) # Foreign Keys belongs_to_user_id = Column(Integer, ForeignKey('users.id')) payment_belongs_to_user_relation = relationship("User", back_populates="payment_belongs_to_user_addresses") def __init__(self, account_owner=None, IBAN=None): self.account_owner = account_owner self.IBAN = IBAN def get(self, id): if self.id == id: return self else: return None def __repr__(self): return '&lt;%s(%r, %r, %r)&gt;' % (self.__class__.__name__, self.id, self.account_owner, self.IBAN) Here is the relevant part from the users table: # Project class User(UserMixin, Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) # etc... # Foreign Key payment payment_belongs_to_user_addresses = relationship('UserPayData', back_populates="payment_belongs_to_user_relation") This is the raw SQL which I want to execute: CREATE TABLE 'userspaydata' ( account_owner TEXT NOT NULL, IBAN TEXT NOT NULL, belongs_to_user_id INT references users(id) ); I have found many examples and some are different. I have a few questions: Do I have to create a primary key aswell? AFAIK, if the primary key is not defined by me it will be automatically ID INT Relationships do not need to be defined on the DB level, they are defined on the app level or am I wrong? If I am wrong, how I define the relationship in raw SQL? I have not submitted the SQL query yet, is the syntax correct?
favorite count: 0
accepted answer: http://stackoverflow.com/a/50568021
upvote count: 2
has answer: http://stackoverflow.com/a/50566765
answer count: 2
tagged with: python
downvote count: 1
possible better answer: http://stackoverflow.com/a/50566765
tagged with: sqlalchemy
has answer: http://stackoverflow.com/a/50568021
tagged with: postgresql
type: Question
type: AnsweredQuestion
tagged with: sql

http://stackoverflow.com/comment/88329934
score: 1
comment on: http://stackoverflow.com/q/50659967
type: Comment
type: QuestionComment
has text: df.groupby('id').fruit.apply(','.join)

http://stackoverflow.com/comment/88169743
has text: Also, you have comma in your last column, which is a default separator.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50579629
score: 0

http://stackoverflow.com/comment/88390703
type: Comment
comment on: http://stackoverflow.com/q/50673733
score: 0
has text: @eis - I have planned to make this a desktop application. There is going to be a window on my screen that displays words (that can't be copied by cntrl + C) which I wish to analyze with "said" program and take that text as input.
type: QuestionComment

http://stackoverflow.com/q/50659884
score: -1
has comment: http://stackoverflow.com/comment/88337736
type: Question
answer count: 2
upvote count: 0
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/88329854
has title: LableEncoder() error (sklearn)
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50660761
has body: How to deal with LableEncoder() in python 3.0 (Anaconda)? When I run my data am getting an error like '&lt;' not supported between instances of 'str' and 'float'. Below is the code used: from sklearn.preprocessing import LabelEncoder var_mod = ['Gender','Married','Dependents','Education','Self_Employed', 'Property_Area','Loan_Status'] le = LabelEncoder() for i in var_mod: df[i] = le.fit_transform(df[i]) df.dtypes
has comment: http://stackoverflow.com/comment/88329823
type: UnansweredQuestion
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/50673914
tagged with: dataframe

http://stackoverflow.com/comment/88170927
has text: Can you please help me write the correct sequence for extracting all the data columns? (from all the 1000s of rows present in the file). Please ask me any further details that you'd require for the same.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50580254
type: AnswerComment

http://stackoverflow.com/a/50601166
accepted answer of: http://stackoverflow.com/q/50599850
type: Answer
has comment: http://stackoverflow.com/comment/88211868
has comment: http://stackoverflow.com/comment/88238440
upvote count: 4
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50599850
downvote count: 0
has comment: http://stackoverflow.com/comment/88246707
score: 4
has body: This is somewhat subtle - it depends on an undocumented property of the tee function along with an intentionally vague property of the garbage collector. The sample Python code would store all the items from the point where the iterators were created until they're consumed by each iterator, but one might easily imagine that the iterators would have a cleanup effect that would drop their claim on data in the queue. But even so, del removes your name; it doesn't guarantee the object's destruction. Such a cleanup would thus work but not necessarily at the time you expect it. Knowing whether this happens would require reading the source code for tee. It does have weak reference support for the individual iterators, suggesting one way this optimization could have been done. The CPython code for tee_next is reasonably simple; it holds a reference to a teedataobject, which is a batch of up to 57 items, also forming a singly linked list. Thus the normal reference counting semantics apply at that batch level. So basically, for CPython, up to 56 items are kept in memory even after they've been consumed by all the iterators, but no more than that because the reference count handling is immediate. As long as the tee iterators exist, any number of items between them can be held, but they do not read ahead from the source iterator; at least one tee iterator must have fetched the items via teedataobject_getitem. So the basic verdict is: yes, del will work in CPython, but using tee means you're temporarily storing batches of 57 items, not 1. Repeating this method could cause an arbitrary number of such windows - except tee iterators are copyable, and will share their underlying list. This is the interpretation specifically of one version (4243df51fe43) of CPython. Implementations will differ in e.g. PyPy, IronPython, Jython, or other versions of CPython. For instance, PyPy's tee (version cadf868) uses a similar linked list with one item per link, so doesn't batch up the way this CP…

http://stackoverflow.com/comment/88274215
type: AnswerComment
has text: I don't know if there's such a ready-made setup already, but you can build one from the pieces in tf.data.
type: Comment
comment on: http://stackoverflow.com/a/50611284
score: 0

http://stackoverflow.com/comment/88322199
comment on: http://stackoverflow.com/q/50655959
score: 0
type: Comment
type: QuestionComment
has text: Django use `fieldname__in==[1, 2, 3, 4]`, SQLAlchemy use `Table.fieldname.in_([1, 2, 3, 4])`. But I think `Field('a') in [1, 2, 3, 4]` is a better solution, because it is more like normal python code.

http://stackoverflow.com/q/50667244
has comment: http://stackoverflow.com/comment/88344774
tagged with: python
type: AnsweredQuestion
has title: Unable to catch elements of a global list (Polygon inheritance)
has answer: http://stackoverflow.com/a/50667462
has answer: http://stackoverflow.com/a/50667511
has comment: http://stackoverflow.com/comment/88344468
has body: I am trying to catch elements of the sides list I declared on the top of the Polygon class but I am having problem in the sideLenght method that is besically a list of lists (I dont understand why). I am therefore unable to create calculate the perimeter of my triangle. Here is what how I start : t=Triangle() t.sideLength() t.findPeri() everything works well until I am calling the findPeri() method. Here is what I get in return: t.findPeri() what i get is the below: TypeError: unsupported operand type(s) for +: 'int' and 'list' What's really going on here? and How can I sort this out? My whole code is below: class Polygon: sides= [] def __init__(self, num_of_sides): self.n= num_of_sides self.num_of_sides= int(input('Enter the number of sides: ')) def sideLength(self): """This method appends all sides of the polygon into a list""" for i in range(self.n): side = int(input('Enter the length the side: ' + str(i+1) + ' : ')) Polygon.sides.append(self.side) print Polygon.side class Triangle(Polygon): def __init__(self): Polygon.__init__(self,3) def findPeri(self): print 'The toatal area of your perimeter is: ',sum(Polygon.sides)
possible better answer: http://stackoverflow.com/a/50667480
type: Question
has answer: http://stackoverflow.com/a/50667480
has comment: http://stackoverflow.com/comment/88344770
has comment: http://stackoverflow.com/comment/88344857
tagged with: class
tagged with: python-2.7
score: 0
answer count: 3
accepted answer: http://stackoverflow.com/a/50667462

http://stackoverflow.com/a/50626043
upvote count: 9
has comment: http://stackoverflow.com/comment/114839020
answers question: http://stackoverflow.com/q/50625818
has comment: http://stackoverflow.com/comment/88262562
score: 9
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88263202
type: Answer
has body: You mention you have tried get_date() and it didn't work, but that's actually the right function. import tkinter as tk from tkinter import ttk from tkcalendar import Calendar, DateEntry def calendar_view(): def print_sel(): print(cal.selection_get()) top = tk.Toplevel(root) cal = Calendar(top, font="Arial 14", selectmode='day', cursor="hand1", year=2018, month=2, day=5) cal.pack(fill="both", expand=True) ttk.Button(top, text="ok", command=print_sel).pack() def dateentry_view(): def print_sel(): print(cal.get_date()) top = tk.Toplevel(root) ttk.Label(top, text='Choose date').pack(padx=10, pady=10) cal = DateEntry(top, width=12, background='darkblue', foreground='white', borderwidth=2) cal.pack(padx=10, pady=10) ttk.Button(top, text="ok", command=print_sel).pack() root = tk.Tk() s = ttk.Style(root) s.theme_use('clam') ttk.Button(root, text='Calendar', command=calendar_view).pack(padx=10, pady=10) ttk.Button(root, text='DateEntry', command=dateentry_view).pack(padx=10, pady=10) root.mainloop() If you want to get the date every time it is changed you can use an event binding. From the documentation: Virtual Events A <<CalendarSelected>> event is generated each time the user selects a day with the mouse. So you can bind the function that gets the date to the <<CalendarSelected>> event: def dateentry_view(): def print_sel(e): print(cal.get_date()) top = tk.Toplevel(root) ttk.Label(top, text='Choose date').pack(padx=10, pady=10) cal = DateEntry(top, width=12, background='darkblue', foreground='white', borderwidth=2) cal.pack(padx=10, pady=10) cal.bind("<<DateEntrySelected>>", print_sel)
accepted answer of: http://stackoverflow.com/q/50625818

http://stackoverflow.com/comment/88217926
score: 0
has text: Sorry, my fault...I mean that when I call animation.FuncAnimation inside while True (second example) the code never back again to say(5). So say(5) call only is called one time at the beginning of the process and never again. Because the script is running ani again and again @ImportanceOfBeingErnest
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50601939

http://stackoverflow.com/q/50652963
favorite count: 0
type: UnansweredQuestion
has title: Django Foreign Key to JSON
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50653034
has body: I am having hardtime on displaying One field with multiple field (foreign key). Please check the example below for the correct format. My database table: Phonebook Object: http://prntscr.com/jps9lc and ContactNumber Object: http://prntscr.com/jps9rr Correct format for return example: { "id": 19, "name": "Name here", "email": "zz@zz.zz", "address": "ajot", "note": "ajot", "contact_number": [ "454572", "27", "752752" ] } models.py class PhoneBook(models.Model): name = models.CharField(max_length=50, unique= True) address = models.CharField(max_length=100, default='address') email = models.CharField(max_length=50, default='email') note = models.CharField(max_length=100, default='note') def __str__(self): return self.name class ContactNumber(models.Model): contact_name = models.ForeignKey(PhoneBook, related_name="contact_numbers") contact_number= models.CharField(max_length=30, unique= True) def __str__(self): return self.contact_number views.py def phonebook_detail(request): phonebook_id=request.GET['id'] phonebooklist = PhoneBook.objects.all() data = PhoneBook.objects.get(id=phonebook_id) print(data) #result is combined all contact numbers seperated by comma(,) number_data = ContactNumber.objects.get(contact_name_id=data) return JsonResponse({"message":"success", "id":data.id, "name":data.name, "address":data.address, "email": data.email, "note":data.note, "contact_number": number_data #It should the correct format of contact_number in the example },safe=False)
downvote count: 0
score: 1
tagged with: http://stackoverflow.com/tag/json
type: Question
answer count: 1
upvote count: 1

http://stackoverflow.com/comment/88158005
type: Comment
has text: Thanks a lot! I admit I would personally never even think that there was a delay on that and a need to handle it this way. I really appreciate the effort you made, thanks again!
comment on: http://stackoverflow.com/a/50574148
type: AnswerComment
score: 2

http://stackoverflow.com/a/50611478
has body: Consider using tensor.from_numpy() https://pytorch.org/tutorials/beginner/former_torchies/tensor_tutorial.html
answers question: http://stackoverflow.com/q/50611420
score: 0
type: Answer

http://stackoverflow.com/q/50614931
has comment: http://stackoverflow.com/comment/88239770
answer count: 1
has comment: http://stackoverflow.com/comment/88239716
tagged with: pandas
downvote count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
has body: Need help with the following please. Suppose we have a dataframe: dictionary ={'Category':['a','a','a','a','a','a','a','a','b','b','b','b','b','b','b'], 'val1':[11,13,14,17,18,21,22,25,2,8,9,13,15,16,19], 'val2':[1,0,5,1,4,3,5,9,4,1,5,2,4,0,3]} df=pd.DataFrame(dictionary) 'val1' is always increasing within the same value in 'category', i.e first and last rows of a category are min and max values of that category. There are too many rows per category, and I want to make a new dataframe that includes min and max values of each category and contains equally spaced e.g. 5 rows (incluing min and max) from each category. I think numpy's linspace should be used to create an array of values for each category (e.g. linspace(min, max, 5)) then something similar to excel's 'lookup' function should be used to get the closest values of 'val1' from df. Or maybe there are some other better ways... Many thanks for the help.
score: 1
tagged with: dataframe
has answer: http://stackoverflow.com/a/50615419
accepted answer: http://stackoverflow.com/a/50615419
has title: Reduce the dataframe rows and lookup
type: Question
upvote count: 2

http://stackoverflow.com/comment/88192073
comment on: http://stackoverflow.com/q/50589333
score: 0
type: QuestionComment
has text: it was declared off topic there
type: Comment

http://stackoverflow.com/a/50580695
has body: You can use the multiprocessing module from multiprocessing import Process def A(): print("A") def B(): print("B") def runAll(fns): proc = [] for fnName in fns: fn = globals()[fnName] p = Process(target=fn) p.start() proc.append(p) for p in proc: p.join() Then you call them like so: runAll(['A','B']) If the functions are not defined in the same module then replace the globals line (globals()...) with: fn = getattr(module, fnName) Try it here: Repl.it As a side note, allowing users to invoke arbitrary functions is a bad idea (security-wise). You could instead explicitly only accept actions from a list of predefined strings.
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88173517
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50580612
has comment: http://stackoverflow.com/comment/88171496
has comment: http://stackoverflow.com/comment/88171371
answers question: http://stackoverflow.com/q/50580612
type: Answer

http://stackoverflow.com/comment/88359635
comment on: http://stackoverflow.com/q/50645301
score: 0
has text: @AmaroVita No, not really, because `update_or_create` also isn't a method of the model itself, but of the manager of the model. And the manager also isn't accessible by `self` so this doesn't work
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88203143
has text: Thank you so much! This was what i was looking for :)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50596423

http://stackoverflow.com/comment/88134876
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50561455
has text: Just leave it blank `result=pool.map(check_values, fake_data)`
score: 0

http://stackoverflow.com/q/50576341
linked to: http://stackoverflow.com/q/50478410
has comment: http://stackoverflow.com/comment/88187154
answer count: 4
tagged with: subprocess
has answer: http://stackoverflow.com/a/50591854
has comment: http://stackoverflow.com/comment/88245510
upvote count: 1
tagged with: ibm-midrange
type: Question
has comment: http://stackoverflow.com/comment/88266359
has title: How to call an RPG program from Python
has answer: http://stackoverflow.com/a/50629510
has comment: http://stackoverflow.com/comment/88307175
has body: How do you call an RPG program from IBM's Python for PASE? I tried os.system, subprocess.popen/call but they didn't work. Update I found something on IBM's site. I tried the below; it does not give me any error but the RPG program does not execute (meaning it does not give expected result). from itoolkit import * from itoolkit.lib.ilibcall import * itool = iToolKit() itransport = iLibCall() itool.add(iCmd('CALL', 'CALL TEMPLIB/TEMPPGM')) itool.call(itransport)
has answer: http://stackoverflow.com/a/50629520
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/50584391
favorite count: 0
has comment: http://stackoverflow.com/comment/88185509
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/88289731
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50638138
has text: See the answers from me and @amulya349

http://stackoverflow.com/q/50625363
score: 11
has comment: http://stackoverflow.com/comment/88307541
has answer: http://stackoverflow.com/a/73357412
has comment: http://stackoverflow.com/comment/88307468
favorite count: 0
has answer: http://stackoverflow.com/a/70436368
has answer: http://stackoverflow.com/a/50651549
answer count: 5
has answer: http://stackoverflow.com/a/72711756
tagged with: python
has comment: http://stackoverflow.com/comment/88307485
possible better answer: http://stackoverflow.com/a/70436368
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88308896
has body: This problem is old as the world. There are discussions and solutions available. It all boils down to update the rules file and give permissions. So I have followed the recipe. But I still have the same problem. here are screenshots showing I follow instructions. Versions: Python 2.7.12 (default, Dec 4 2017, 14:50:18) usb.__version__ '1.0.2' Error: Traceback (most recent call last): File "/media/psf/Home/All-Projects-on-femto/LaserLab/Software/usb_4108.py", line 19, in &lt;module&gt; dev.set_configuration() File "/usr/local/lib/python2.7/dist-packages/usb/core.py", line 869, in set_configuration self._ctx.managed_set_configuration(self, configuration) File "/usr/local/lib/python2.7/dist-packages/usb/core.py", line 102, in wrapper return f(self, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/usb/core.py", line 147, in managed_set_configuration self.managed_open() File "/usr/local/lib/python2.7/dist-packages/usb/core.py", line 102, in wrapper return f(self, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/usb/core.py", line 120, in managed_open self.handle = self.backend.open_device(self.dev) File "/usr/local/lib/python2.7/dist-packages/usb/backend/libusb1.py", line 786, in open_device return _DeviceHandle(dev) File "/usr/local/lib/python2.7/dist-packages/usb/backend/libusb1.py", line 643, in __init__ _check(_lib.libusb_open(self.devid, byref(self.handle))) File "/usr/local/lib/python2.7/dist-packages/usb/backend/libusb1.py", line 595, in _check raise USBError(_strerror(ret), ret, _libusb_errno[ret]) USBError: [Errno 13] Access denied (insufficient permissions) Rules. file (location /etc/udev/rules.d/99-usbftdi.rules) # For FTDI FT232 &amp; FT245 USB devices with Vendor ID = 0x0403, Product ID = 0xabc SYSFS{idProduct}=="4108", SYSFS{idVendor}=="0683", RUN+="/sbin/modprobe -q ftdi-sio product=0x4108 vendor=0x0683" #SYSFS{idProduct}=="2450", SYSFS{idVendor}=="0683", RUN+="/sbin/modprobe -q ftdi-sio product=0x2450 vendor=0x0683" SYSFS{idVendor…
downvote count: 1
accepted answer: http://stackoverflow.com/a/50651549
type: Question
has answer: http://stackoverflow.com/a/74270022
upvote count: 12
has comment: http://stackoverflow.com/comment/127458103
tagged with: ubuntu-16.04
tagged with: usb
has title: USBError: [Errno 13] Access denied (insufficient permissions)

http://stackoverflow.com/q/50655608
favorite count: 0
possible better answer: http://stackoverflow.com/a/50655688
has answer: http://stackoverflow.com/a/50655951
has answer: http://stackoverflow.com/a/50655665
has answer: http://stackoverflow.com/a/50655688
has answer: http://stackoverflow.com/a/50655690
tagged with: python
answer count: 4
type: AnsweredQuestion
type: Question
score: 9
accepted answer: http://stackoverflow.com/a/50655951
upvote count: 9
has title: Formatting a string with a namedtuple
has body: I'm wondering if there is a way to use the variablelist of a namedtuple to format a string efficiently like so: TestResult = collections.namedtuple('TestResults', 'creation_time filter_time total_time') test = TestResult(1, 2, 3) string_to_format = '{creation_time}, {filter_time}, {total_time}'.format(test) instead of just writing: string_to_format = '{}, {}, {}'.format(test.creation_time, test.filter_time, test.total_time) If there is a way to do this, would it be considered pythonic? Thank you for your answers
downvote count: 0

http://stackoverflow.com/comment/88175835
has text: Why does your input have all the ranges starting with 5 instead of 5/8/10 like your output ranges start?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50582390
score: 0

http://stackoverflow.com/comment/88177323
type: Comment
comment on: http://stackoverflow.com/a/50583059
has text: Yup just noticed. This doesnt happen on my Ubuntu instance.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88200055
score: 0
type: Comment
type: QuestionComment
has text: As a side note: I'm pretty sure that `colspec` didn't exist in any of the old versions of HTML that allowed unclosed tags, so your code is generating invalid markup. Also, is there a reason you don't want to use an HTML document generator, instead of creating the text manually?
comment on: http://stackoverflow.com/q/50595357

http://stackoverflow.com/comment/88396751
comment on: http://stackoverflow.com/q/50693203
type: Comment
type: QuestionComment
has text: Related question: [Find all letters of a string in another string](//stackoverflow.com/q/49975213)
score: 1

http://stackoverflow.com/comment/88352057
comment on: http://stackoverflow.com/q/50671172
score: 0
type: Comment
type: QuestionComment
has text: Please [edit](https://stackoverflow.com/posts/50671172/edit) your question with arrays & code as text, not images.

http://stackoverflow.com/q/50547222
has comment: http://stackoverflow.com/comment/88105764
has comment: http://stackoverflow.com/comment/88105210
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88105326
favorite count: 0
has title: Error when importing local csv file to python
tagged with: http://stackoverflow.com/tag/csv
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/88105159
type: AnsweredQuestion
downvote count: 3
has body: I tried to import .csv file from my computer to python, but both codes didn't work. What is wrong? First try: import csv with open('chicago.csv') as chicago_data: csvReader = csv.reader(chicago_data) for row in csvReader: print(row) Second try: import csv with open('chicago.csv') as chicago_data: csvReader = csv.reader(chicago_data, delimiter=',') for row in csvReader: print(row[0])
tagged with: import
type: Question
has answer: http://stackoverflow.com/a/50547746
accepted answer: http://stackoverflow.com/a/50547746

http://stackoverflow.com/comment/88276823
comment on: http://stackoverflow.com/q/50633189
score: 0
type: QuestionComment
type: Comment
has text: @juanpa.arrivillaga Okay, I'll read into that. Thanks in advance. But I still don't get why it is interferring with what is *outside* the function.

http://stackoverflow.com/a/50570473
has comment: http://stackoverflow.com/comment/88150887
has comment: http://stackoverflow.com/comment/88150655
has comment: http://stackoverflow.com/comment/88150807
accepted answer of: http://stackoverflow.com/q/50570334
has comment: http://stackoverflow.com/comment/88150956
upvote count: 2
type: Answer
has body: Use collections.deque You should use collections.deque for this task and use the in-place method deque.rotate designed specifically for this purpose. Using a list for this task would require expensive copying operations, while deque is optimised for fast addition and removal of elements from the beginning and end of a queue. See TimeComplexity for more details. from collections import deque A = deque([1, 9, 7]) for i in range(len(A)): print(A) A.rotate() deque([1, 9, 7]) deque([7, 1, 9]) deque([9, 7, 1]) Why your code does not work The reason your code does not work is because you are modifying the same object rather than a copy. The following will work: def rotation(N): A = [] for i in range(len(N)): N = N[:] N.append(N.pop(0)) A.append(N) return A K = [1,9,7] r = rotation(K) print(r) [[9, 7, 1], [7, 1, 9], [1, 9, 7]] Further explanation If you modify the same object, A will consist of 3 lists with each list pointing to the same object and will therefore be guaranteed to be identical. Remember each list is just a bunch of pointers. If each pointer points to one object, changing it 3 times means the final assignment will be used for all the sublists.
has comment: http://stackoverflow.com/comment/88150838
score: 2
has comment: http://stackoverflow.com/comment/88150782
answers question: http://stackoverflow.com/q/50570334
has comment: http://stackoverflow.com/comment/88150750
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/50594451
has body: You could use numpy.add.at with a bit of manipulation to get the indices ready. np.add.at(img, tuple(inds[:, [1, 0]].T), 1) If you have larger inds arrays, this approach should remain fast... (though Paul Panzer's solution is faster)
score: 5
type: Answer
answers question: http://stackoverflow.com/q/50594318
upvote count: 5
downvote count: 0

http://stackoverflow.com/a/50560982
has body: Using the ast module I am able to read your dictionary. import ast with open(filename, "r") as infile: print(ast.literal_eval(infile.read())) Output: {'album_type': 'single', 'name': 'One More Day', 'uri': 'spotify:album:6ifJabSFs9iUQEDBdCmCz3', 'external_urls': {'spotify': 'https://open.spotify.com/album/6ifJabSFs9iUQEDBdCmCz3'}, 'release_date': '2018-05-04', 'popularity': 55, 'genres': [], 'label': 'Wall Recordings', ' href': 'https://api.spotify.com/v1/albums/6ifJabSFs9iUQEDBdCmCz3', 'tracks': {'items': [{'is_local': False, 'name': 'One More Day', 'external_urls': {'spotify': 'https://open.spotify.com/track/3vPoCfS2Ao2pjOvKZ63ybx'}, 'uri': 'spotify:track:3vPoCfS2Ao2pjOvKZ63ybx', 'explicit': True, 'preview_url': 'https://p.scdn.co/mp3- preview/f0f8d1144626032fcbabb2c22efcae3642e0a235? cid=efb520d351794bbb8daa0d009fffcef4', 'track_number': 1, 'disc_number': 1, 'href': 'https://api.spotify.com/v1/tracks/3vPoCfS2Ao2pjOvKZ63ybx', 'artists': [{'name': 'Afrojack', 'external_urls': {'spotify': 'https://open.spotify.com/artist/4D75GcNG95ebPtNvoNVXhz'}, 'uri': 'spotify:artist:4D75GcNG95ebPtNvoNVXhz', 'href': 'https://api.spotify.com/v1/artists/4D75GcNG95ebPtNvoNVXhz', 'type': 'artist', 'id': '4D75GcNG95ebPtNvoNVXhz'}, {'name': 'Jewelz &amp; Sparks', 'external_urls': {'spotify': 'https://open.spotify.com/artist/50kceDjknh0CjwOko7kx7V'}, 'uri': 'spotify:artist:50kceDjknh0CjwOko7kx7V', 'href': 'https://api.spotify.com/v1/artists/50kceDjknh0CjwOko7kx7V', 'type': 'artist', 'id': '50kceDjknh0CjwOko7kx7V'}], 'duration_ms': 197645, 'type': 'track', 'id': '3vPoCfS2Ao2pjOvKZ63ybx', 'available_markets': ['AD', 'AR', 'AT', 'AU', 'BE', 'BG', 'BO', 'BR', 'CA', 'CH', 'CL', 'CO', 'CR', 'CY', 'CZ', 'DE', 'DK', 'DO', 'EC', 'EE', 'ES', 'FI', 'FR', 'GB', 'GR', 'GT', 'HK', 'HN', 'HU', 'ID', 'IE', 'IL', 'IS', 'IT', 'JP', 'LI', 'LT', 'LU', 'LV', 'MC', 'MT', 'MX', 'MY', 'NI', 'NL', 'NO', 'NZ', 'PA', 'PE', 'PH', 'PL', 'PT', 'PY', 'RO', 'SE', 'SG', 'SK', 'SV', 'TH', 'TR', 'TW', 'US', 'UY', 'VN', 'Z…
type: Answer
answers question: http://stackoverflow.com/q/50559529
score: 0

http://stackoverflow.com/comment/88192586
has text: You have 'Middle' in the dataframe and 'middle' in the code sample.
comment on: http://stackoverflow.com/q/50591609
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88228092
type: AnswerComment
comment on: http://stackoverflow.com/a/50606425
type: Comment
has text: if event == 'Event 1': if indivcombo == 'Individual 1': get_all[20] = individual.get() + "\n" if indivcombo == 'Individual 2': get_all[21] = individual.get() + "\n"
score: 0

http://stackoverflow.com/q/50677749
has comment: http://stackoverflow.com/comment/88365109
upvote count: 2
has comment: http://stackoverflow.com/comment/88386524
type: Question
has comment: http://stackoverflow.com/comment/88365752
has title: Pygame - Crashing when trying to shoot
tagged with: atom-editor
score: 2
answer count: 1
has body: I am trying to learn Python and wanted to practice with Pygame. I am currently using Python 3.6.5 and running the code in Atom 1.27.2 and installed the atom-runner package. I have been following the KidsCanCode tutorial for Pygame on Youtube. I wanted to change the code around so I am not just copying the tutorial. At the moment everything works until I try to spawn a bullet from my ship. The bullet is supposed to go from the left to right, spawning from the ship on the left side of the screen. Once the program loads all ships are moving as expected with collisions working, however when I hit space bar the game crashes with the following error: TypeError: add() argument after * must be an iterable, not int I thought it has to do with my player.shoot function but if I remove the function and try to spawn the bullet under... if event.key == pg.K_SPACE: It still doesn't work. I have the code similar to the code on the video but it still doesn't seem to work. Maybe it has to do with my .rect positions for the bullet, but at this point I am not really sure. Any help would be appreciated. import pygame as pg import random import os WIDTH = 1200 HEIGHT = 700 FPS = 60 #-----define colors----- WHITE = (255,255,255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) # set up assets folders game_folder = os.path.dirname(__file__) img_folder = os.path.join(game_folder, 'graphics') pg.init() pg.mixer.init() screen = pg.display.set_mode((WIDTH, HEIGHT)) pg.display.set_caption('First Game') clock = pg.time.Clock() # ------Load graphics------------- player_img = pg.image.load(os.path.join(img_folder, 'blueship1.png')).convert() enemy1_img = pg.image.load(os.path.join(img_folder, 'enemy1.png')).convert() # ------------ Sprite for the player--------- class Player(pg.sprite.Sprite): def __init__(self): pg.sprite.Sprite.__init__(self) self.image = pg.transform.scale(player_img, (80, 60)) self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.rect.…
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/65493168
type: UnansweredQuestion
tagged with: python
tagged with: pygame

http://stackoverflow.com/comment/88110243
type: Comment
has text: You seem to want the `headers` local variable to automatically reflect the updated token - why? Things look like they work perfectly as they are: 1) `headers` are retrieved before the fetch using the then-current token, 2) the token is updated every two seconds, affecting new downloads. Since you are returning `headers`, you get the "old" value (in fact the value used for that download, which looks correct to me) - if you wanted to return the new current value, you could return `self._get_headers()` instead.
score: 0
comment on: http://stackoverflow.com/q/50548263
type: QuestionComment

http://stackoverflow.com/comment/88354530
has text: @jmh I’m pretty sure I downloaded it directly from Python.org (probably wasn’t the best choice
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50667214

http://stackoverflow.com/q/50571748
has title: Tensorflow No gradients provided for any variable tf.to_double
answer count: 1
downvote count: 0
has body: I have a function that takes in two Tensorflow vectors and a scalar threshold, and returns a Tensorflow operation. The following version throws a "ValueError: No gradients provided for any variable". def mse(expected, probs, threshold): preds = tf.to_double(probs &gt;= threshold) loss_vect = tf.square(expected - preds) loss = -tf.reduce_mean(loss_vect) return loss However if I remove the first line, resulting in the following version of the function, no error is thrown. def mse(expected, probs, threshold): loss_vect = tf.square(expected - probs) loss = -tf.reduce_mean(loss_vect) return loss The context in which I call the function is below. The function above is passed in as loss_func. For act_func, I pass in a function that returns a tf.sigmoid operation. class OneLayerNet(object): def __init__(self, num_feats, num_outputs, act_func, threshold, loss_func, optimizer, batch_size=8, epochs=100, eta=0.01, reg_const=0): self.batch_size = batch_size self.epochs = epochs self.eta = eta self.reg_const = reg_const self.x = tf.sparse_placeholder(tf.float64, name="placeholderx") # num_sents x num_feats self.y = tf.placeholder(tf.float64, name="placeholdery") # 1 x num_sents self.w = tf.get_variable("W", shape=[num_feats, num_outputs], initializer=tf.contrib.layers.xavier_initializer(), dtype=tf.float64) self.b = tf.Variable(tf.zeros([num_outputs], dtype=tf.float64)) self.probs = act_func(self.x, self.w, self.b) self.loss = loss_func(self.y, self.probs, threshold) self.optimizer = optimizer(self.eta, self.loss) self.session = tf.Session() self.session.run(tf.global_variables_initializer()) From other answers, I understand that the ValueError I'm getting means that the path from my weight vector w and my optimizer is broken. I'm wondering why the path breaks when I add the tf.to_double call.
favorite count: 0
has answer: http://stackoverflow.com/a/50572131
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/50572131

instagram
tags question: http://stackoverflow.com/q/50599818
tag name: instagram
type: Tag

http://stackoverflow.com/q/50611148
answer count: 1
downvote count: 0
favorite count: 0
has body: I am trying to use multi threading to speed up the process. I am using the wordnetlemmatizer to lemmatize the words and those words can be further used by sentiwordnet to calculate the sentiment of the text. My Sentiment analysis function where I am using the WordNetLemmatizer is as follows: import nltk from nltk.corpus import sentiwordnet as swn def SentimentA(doc, file_path): sentences = nltk.sent_tokenize(doc) # print(sentences) stokens = [nltk.word_tokenize(sent) for sent in sentences] taggedlist = [] for stoken in stokens: taggedlist.append(nltk.pos_tag(stoken)) wnl = nltk.WordNetLemmatizer() score_list = [] for idx, taggedsent in enumerate(taggedlist): score_list.append([]) for idx2, t in enumerate(taggedsent): newtag = '' lemmatized = wnl.lemmatize(t[0]) if t[1].startswith('NN'): newtag = 'n' elif t[1].startswith('JJ'): newtag = 'a' elif t[1].startswith('V'): newtag = 'v' elif t[1].startswith('R'): newtag = 'r' else: newtag = '' if (newtag != ''): synsets = list(swn.senti_synsets(lemmatized, newtag)) score = 0 if (len(synsets) &gt; 0): for syn in synsets: score += syn.pos_score() - syn.neg_score() score_list[idx].append(score / len(synsets)) return SentiCal(score_list) After running 4 threads, I am getting the following error for the first 3 threads and the last thread is working perfectly. AttributeError: 'WordNetCorpusReader' object has no attribute '_LazyCorpusLoader__args' I have already tried importing the NLTK package locally as given in this NLTK issue and tried the solution given on this page.
tagged with: python
linked to: http://stackoverflow.com/q/27433370
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50614899
upvote count: 3
has comment: http://stackoverflow.com/comment/88239563
tagged with: multithreading
tagged with: wordnet
type: AnsweredQuestion
score: 3
has title: Multi Threading in NLTK WordNetLemmatizer?
accepted answer: http://stackoverflow.com/a/50614899
type: Question
tagged with: nltk

http://stackoverflow.com/a/50611284
answers question: http://stackoverflow.com/q/50602085
score: -2
has comment: http://stackoverflow.com/comment/88274215
has body: All of these warning have instructions for updating. Follow the instructions: switch to tf.data for preprocessing.
type: Answer
has comment: http://stackoverflow.com/comment/88236299
downvote count: 3
upvote count: 1

http://stackoverflow.com/comment/88264201
comment on: http://stackoverflow.com/q/50626810
type: QuestionComment
has text: Why would you expect that output? `a` is the value `1` one-hot-encoded in five features, so `[0., 1., 0., 0., 0.]` (since data type is `tf.float32` by default), then `b` is twice that tensor, hence the result.
score: 0
type: Comment

http://stackoverflow.com/q/50560174
downvote count: 0
score: 1
type: Question
tagged with: dataframe
has body: I have two dataframes and each have a column called Song. However sometimes the songs are spelled differently. How can I used difflib (or something similar) to get the Song spelling of one dataframe in a new column of the other dataframe? ex: Dataframe1 Song Artist like a virgi madonna Dataframe2 Song Rank like a virgin 2 Result Song Artist SongAlt like a virgin Madonna like a virgi
tagged with: sentence-similarity
upvote count: 1
has title: Similarity between 2 dataframe columns
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: similarity
tagged with: python
has answer: http://stackoverflow.com/a/50560212

http://stackoverflow.com/a/50635846
has comment: http://stackoverflow.com/comment/88281728
score: 1
accepted answer of: http://stackoverflow.com/q/50635554
has body: Create a dictionary to hold functions that correspond to 'conditions' import operator, functools operations = {'AND':operator.and_, 'OR':operator.or_, 'XOR':operator.xor} Write a recursive function that will recurse when 'conditions' is a key in a rule, otherwise iterate over the rules and accumulate 'decisions' in a list. Use functools.reduce to apply the condition to the decisions. def f(d): func = operations.get(d['condition'], None) if func is None: return decisions = [] for rule in d['rules']: if 'condition' in rule: decision = f(rule) else: decision = rule['decision'] decisions.append(decision) return functools.reduce(func, decisions) if func is None: return was meant to be the base case but I'm not so sure it's needed - if that happens the dict is messed up and it probably should raise a ValueError I think this has an implicit base case (if there is such a thing) - it relies on the for rule in d['rules']: loop to run out of items. If the conditions limited to 'AND' and 'OR' you can use all and any. ops = {'AND':all, 'OR':any} def g(d): func = ops.get(d['condition'], None) if func is None: return decisions = [] for rule in d['rules']: if 'condition' in rule: decision = f(rule) else: decision = rule['decision'] decisions.append(decision) return func(decisions)
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50635554

http://stackoverflow.com/q/50575064
linked to: http://stackoverflow.com/q/852414
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: orm
tagged with: django
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50575212
tagged with: django-models
has body: I have a listTextField in my modal called technology. I want to filter objects based on an array, if every array value is present in the technology field. tech = ['a','b',....] #dynamic list mentors_list = Mentor.objects.filter( **{"technology__contains" : value for value in tech}) #this doesn't work Mentor class has (among other fields) : class Mentor(Meta): technology = ListTextField( base_field=models.CharField(max_length=20), size=10, max_length=(10 * 11)) Basically i want all objects in mentor_list whose technology field must contain all the values from tech array ( but may contain some extra values ).
answer count: 1
downvote count: 0
favorite count: 0
tagged with: filter
has answer: http://stackoverflow.com/a/50575212
has title: Django filter objects based on list values

http://stackoverflow.com/a/50605513
upvote count: 3
type: Answer
downvote count: 1
score: 2
answers question: http://stackoverflow.com/q/50597714
has body: Using awk and shuf to delete 4 blocks out of 6 blocks where each block is 3 lines long: $ cat tst.awk BEGIN { RS=""; ORS="\n\n" } NR==FNR { next } FNR==1 { cmd = sprintf("shuf -i 1-%d -n %d", NR-FNR, numToDel) oRS=RS; RS="\n" while ( (cmd | getline line) &gt; 0 ) { badNrs[line] } RS=oRS close(cmd) } !(FNR in badNrs) $ awk -v numToDel=4 -f tst.awk file file 1 2 3 10 11 12 Just change numToDel=4 to numToDel=100 for your real input. The input file used to test against above was generated by: $ seq 18 | awk '1; !(NR%3){print ""}' &gt; file which produced: $ cat file 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

http://stackoverflow.com/a/50696529
accepted answer of: http://stackoverflow.com/q/50696446
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50696446
upvote count: 8
has comment: http://stackoverflow.com/comment/88402443
type: Answer
score: 8
has body: Just move the import out of the loop. You are correct in that this is causing Python some extra work each iteration. A Python import statement does two things: Check if the referenced module is already loaded, and if not, load it. Bind (assign) one or more names. So each loop iteration Python checks if the module is already loaded (roughly equivalent to checking 'Levenshtein._levenshtein' in sys.modules), then sets the name distance. Provided nothing else in the loop sets the name distance to anything else, you can safely move the import out of the loop and save yourself those checks as well. If there is such code, then refactor it to not use the same name, and move the import out of the loop.

http://stackoverflow.com/q/50623188
tagged with: image
type: Question
answer count: 2
favorite count: 0
tagged with: python
tagged with: python-cryptography
has answer: http://stackoverflow.com/a/51001790
tagged with: http://stackoverflow.com/tag/png
has comment: http://stackoverflow.com/comment/88271190
has body: The encrypted picture should be decrypted by the xor the key using the first byte 0x89 if the of the PNG file and switching the place of the pictures
type: UnansweredQuestion
score: 0
tagged with: encryption
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50725432
has title: How to decrypt the file in the encryption code

http://stackoverflow.com/q/50559200
type: AnsweredQuestion
tagged with: matplotlib
type: Question
accepted answer: http://stackoverflow.com/a/50559902
score: 5
upvote count: 5
answer count: 3
tagged with: pandas
downvote count: 0
has body: This code gives plot of candlesticks with moving averages but the x-axis is in index, I need the x-axis in dates. What changes are required? import numpy as np import pandas as pd import matplotlib.pyplot as plt from mpl_finance import candlestick2_ohlc #date format in data-&gt; dd-mm-yyyy nif = pd.read_csv('data.csv') #nif['Date'] = pd.to_datetime(nif['Date'], format='%d-%m-%Y', utc=True) mavg = nif['Close'].ewm(span=50).mean() mavg1 = nif['Close'].ewm(span=13).mean() fg, ax1 = plt.subplots() cl = candlestick2_ohlc(ax=ax1,opens=nif['Open'],highs=nif['High'],lows=nif['Low'],closes=nif['Close'],width=0.4, colorup='#77d879', colordown='#db3f3f') mavg.plot(ax=ax1,label='50_ema') mavg1.plot(color='k',ax=ax1, label='13_ema') plt.legend(loc=4) plt.subplots_adjust(left=0.09, bottom=0.20, right=0.94, top=0.90, wspace=0.2, hspace=0) plt.show() Output:
favorite count: 0
has title: candlestick plot from pandas dataframe, replace index by dates
has answer: http://stackoverflow.com/a/51852989
possible better answer: http://stackoverflow.com/a/58227461
tagged with: candlestick-chart
has answer: http://stackoverflow.com/a/50559902
has answer: http://stackoverflow.com/a/58227461
has comment: http://stackoverflow.com/comment/89548192
tagged with: python

http://stackoverflow.com/q/50663299
type: Question
has title: pandas dataframe replace function
accepted answer: http://stackoverflow.com/a/50663392
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/88336679
has body: I want to replace "?" with NaN in Python. The following code does not work, and I am not sure what is the reason. import pandas as pd; import numpy as np; col_names = ['BI_RADS', 'age','shape','margin','density','severity'] dataset = pd.read_csv('mammographic_masses.data.txt', names = col_names) dataset.replace("?", np.NaN) After executing the above code, I still get those question marks in the dataset. The format of the dataset looks like the followings: 5,67,3,5,3,1 4,43,1,1,?,1 5,58,?,5,3,1 4,28,1,1,3,0 5,74,1,5,?,1
favorite count: 0
has comment: http://stackoverflow.com/comment/88336634
has answer: http://stackoverflow.com/a/50663392
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88336709
has comment: http://stackoverflow.com/comment/88336712
downvote count: 1
has comment: http://stackoverflow.com/comment/88336764

http://stackoverflow.com/a/50597406
answers question: http://stackoverflow.com/q/50597251
score: 0
type: Answer
has body: fetchall return you a list of tuples. You do not need map also. You can directly access the element using index. Ex: def query(conn): x = conn.cursor() x.execute ("SELECT Amount from Expenses") for item in x.fetchall(): #items = int(item[0]) --&gt;Use index to access the element. print "The amount is %s" % (item[0])
has comment: http://stackoverflow.com/comment/88204732
has comment: http://stackoverflow.com/comment/88205097

http://stackoverflow.com/comment/88255095
score: 0
comment on: http://stackoverflow.com/q/50622609
type: Comment
type: QuestionComment
has text: What is the `type` or `class` of your `x` attribute ?

http://stackoverflow.com/a/50565691
type: Answer
has body: Try the following:- import re content = """Generator London ABC / FI9 Phone +758 00 000000000 E-Mail london.abcd@gen.in Fax Generate order no 546465438 Generate order date 29.04.2018 Country of Use Page 1/ 3 Generator London ABC / FI9 Phone +758 91 702 122222 E-Mail london.abcd@gen.in Fax Generate order no 4504967662 Generate order date 29.01.2018 Country of Use Page 2/ 3 Payment terms: 30 days - 2 %, 45 days net Supplier Generator London ABC / 3I9 Phone +758 91 702 122222 E-Mail london.abcd@gen.in Fax +07023400800 1234 XI54545454 ZI41 8263 8815 1100 +2939 218932 000 Total Profit Total Budget ... """ print re.findall(r'Fax\s[\+0-9\s]+((?:(?!Fax).)*?)Total', content , re.DOTALL|re.M) Here we have updated regex for Fax with [+0-9\s], so that it will consider '+', '0-9' digits and \s for any space in the number. Hope this will help.
answers question: http://stackoverflow.com/q/50565419
score: 0
upvote count: 1
downvote count: 1

http://stackoverflow.com/a/50626465
type: AcceptedAnswer
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50625699
type: Answer
answers question: http://stackoverflow.com/q/50625699
has comment: http://stackoverflow.com/comment/88264779
has body: You could use a combination of string.split() and string.strip() to first extract each lines individually. string = email_content lines = string.split('\r\n') lines_stripped = [] for line in lines: line = line.strip() if line != '': lines_stripped.append(line) This gives you an array like this: ['Demand: $41,225 (-47%)', 'Orders: 515 (-53%)', 'Units: 849 (-59%)', 'AOV: $80 (12%)', 'AUR: $49 (30%)', 'Orders with Promo Code: 3%', 'Average Discount: 21%'] You can also achieve the same result in a more compact (pythonic) way: lines_stripped = [line.strip() for line in string.split('\r\n') if line.strip() != ''] Once you have this array, you use regexes as you correctly guessed to extract the values. I recommend https://regexr.com/ to experiment with your regex expressions. After some quick experimenting, r'([\S\s]*):\s*(\S*)\s*\(?(\S*)\)?' should work. Here is the code that produces a dict from your lines_stripped we created above: import re regex = r'([\S\s]*):\s*(\S*)\s*\(?(\S*)\)?' matched_dict = {} for line in lines_stripped: match = re.match(regex, line) matched_dict[match.groups()[0]] = (match.groups()[1], match.groups()[2]) print(matched_dict) This produces the following output: {'AOV': ('$80', '12%)'), 'AUR': ('$49', '30%)'), 'Average Discount': ('21%', ''), 'Demand': ('$41,225', '-47%)'), 'Orders': ('515', '-53%)'), 'Orders with Promo Code': ('3%', ''), 'Units': ('849', '-59%)')} You asked for Units, Orders and Demand, so here is the extraction: # Remove the dollar sign before converting to float # Replace , with empty string demand_string = matched_dict['Demand'][0].strip('$').replace(',', '') print(int(demand_string)) print(int(matched_dict['Orders'][0])) print(int(matched_dict['Units'][0])) As you can see, Demand is a little bit more complicated because it contains some extra characters python can't decode when converting to int. Here is the final output of those 3 prints: 41225 515 849 Hope I answered your question ! If you have more questions about regex, …
has comment: http://stackoverflow.com/comment/88264961
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/88264063
has comment: http://stackoverflow.com/comment/88264160

http://stackoverflow.com/q/50658852
type: Question
score: 0
tagged with: pandas
has title: How to add leading 0's to different values in same column in pandas?
answer count: 1
has body: I have a column that has values of length 5,6,8, or 9. The column should just have values of length 6 or 9. I need to add leading 0's if the value is of length 5 or 8. There is another column which can identfy if the value should be 6 or 9 digits (indicator). An indicator value of 'Red' means 6 digits, and an indicator of 'Green' means 9 digits. df['digits'] = df[df['indicator'] == 'red']['digits'].apply(lambda x: "{:006d}".format(x)) df['digits'] = df[df['indicator'] == 'green']['digits'].apply(lambda x: "{:009d}".format(x)) id indicator digits 0 red 54324 1 red 654345 2 green 533345678 3 green 56438594 expected result: id indicator digits 0 red 054324 # 0 added to this value 1 red 654345 2 green 533345678 3 green 056438594 # 0 added to this value I am getting an error of ValueError: Unknown format code 'd' for object of type 'float'. Any ideas why? What did I miss?
tagged with: python
has answer: http://stackoverflow.com/a/50658914
tagged with: pandas-apply
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50658914

http://stackoverflow.com/comment/88360719
has text: sry mate was kinda busy the first level is sorted
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50674100

http://stackoverflow.com/q/50669431
tagged with: python
has title: How to access individual elements of a Tensorflow tensor?
has comment: http://stackoverflow.com/comment/88354460
score: 0
has comment: http://stackoverflow.com/comment/88352095
tagged with: tensorflow
has body: I am writing a model in Keras, where the output of one of the layers gives me the coordinates of a mask that I want to apply on the image input. The problem is that I could not find any way to do this, methods such as tf.slice() do not work if you are not inside a session. I want to do equivalent to this: x=dense(2)(x) A=np.zeros((224,224, 3)) or K.zeros((224,224,3)) x=int(x) A[x[0],x[1],:]=1 where x comes from previous layers and is reassigned in the layer shown (dense layer from keras), the output is two numbers representing the position in the picture, then I create A which is a mask to be multiplied with the input (input not shown), and I need both, make the output of the layer an integer, and then use it to add ones to the mask A at position (x[0],x[1]) (and other ones too, but just having one is enough to know the method.
has comment: http://stackoverflow.com/comment/88353232
type: UnansweredQuestion
answer count: 0
has comment: http://stackoverflow.com/comment/88354570
tagged with: keras
has comment: http://stackoverflow.com/comment/88351105
has comment: http://stackoverflow.com/comment/88354425
has comment: http://stackoverflow.com/comment/88354214
type: Question

http://stackoverflow.com/comment/88926112
type: AnswerComment
has text: `ax.ishold()` is another deprecated `matplotlib` function which `baseplot` uses (though this one doesn't break the script).
type: Comment
comment on: http://stackoverflow.com/a/50928480
score: 0

http://stackoverflow.com/q/50684894
has title: Doc2vec most_similar method returns similarity score higher than 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88396698
tagged with: python
tagged with: gensim
answer count: 0
has comment: http://stackoverflow.com/comment/88427375
has comment: http://stackoverflow.com/comment/88385230
has comment: http://stackoverflow.com/comment/88493174
has body: I have trained doc2vec model by following this tutorial for 500.000 documents. https://github.com/abtpst/Doc2Vec/blob/master/trainDoc2Vec.py However, when I try to find most_similar documents for a given document, the results have similarity higher than 1. As you can see in the code and the outputs, docvecs.similarity returns 0.246 and docvecs.most_similar return 9.996 for similarity between same two documents. You can see the code and the output below: from gensim.models import doc2vec def myhash(obj): return hash(obj) % (2 ** 32) model = doc2vec.Doc2Vec(hashfxn=myhash) model = doc2vec.Doc2Vec.load("d2v.model") tag1 = "012020171590" tag2 = "0109201716181" print(tag1 in model.docvecs.doctags) print(tag2 in model.docvecs.doctags) print(model.docvecs.similarity(tag1, tag2)) print(model.docvecs.most_similar(tag1)) Output: True True 0.24682570854972158 [('0109201716181', 9.996172904968262), ('0120201611372', 9.853036880493164), ('010120166996', 9.613503456115723), ('012020173027', 8.97104263305664), ('01202017423', 8.886014938354492), ('01002009541', 8.783470153808594), ('00002004106', 8.682585716247559), ('0109201616963', 8.671405792236328), ('011020171931', 8.659266471862793), ('011020175199', 8.573907852172852)] Library and System Versions: Linux-4.9.0-6-amd64-x86_64-with-debian-9.4 Python 3.5.3 (default, Jan 19 2017, 14:11:04) NumPy 1.14.3 SciPy 1.1.0 gensim 3.4.0 FAST_VERSION 1
type: Question
has comment: http://stackoverflow.com/comment/88427535
tagged with: doc2vec
score: 0
has comment: http://stackoverflow.com/comment/88385264
has comment: http://stackoverflow.com/comment/88396707
tagged with: python-3.x

http://stackoverflow.com/comment/88240888
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50615482
score: 0
has text: dist is a list of references to a list containing 3 zeros. Try `[[0]*3 for i in range(3)]`

http://stackoverflow.com/comment/88169518
type: QuestionComment
score: 0
has text: @Moberg, `not` is the indeed the reason this is confusing. Why don't you make it as the answer?
comment on: http://stackoverflow.com/q/50580064
type: Comment

http://stackoverflow.com/comment/88291632
has text: No error message, it just doesn't print anything from main(). It's supposed to print a series of strings which progressively converge to "methinks it is like a weasel". In eclipse, it shows that the code is still being processed but it does not output anything that it is supposed to
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50640450

http://stackoverflow.com/comment/88212571
comment on: http://stackoverflow.com/q/50585305
type: Comment
type: QuestionComment
score: 0
has text: I cannot explain why `f2.__module__ = "my_module"` does not work for you. Similar questions: https://stackoverflow.com/q/47903710/407651, https://stackoverflow.com/q/22096187/407651, https://stackoverflow.com/q/30856279/407651.

http://stackoverflow.com/q/50658159
score: 0
has body: I want to migrate my pyspark code from 1.6 to 2.x. In 1.6 I was using syntax input_df.repartition(number_of_files) \ .write.mode(file_saveMode) \ .format(file_format) \ .option("header", "true") \ .save(nfs_path) And was getting output in below format. part-00000 part-00001 . . I ran the same code in pyspark2.2, it gave me different part file names part-00000-2feefae7-47d7-4f1a-ade6-7dbd07f42f54-c000.csv part-00001-2feefae7-47d7-4f1a-ade6-7dbd07f42f54-c000.csv Then I change the code as per 2.x input_df.repartition(number_of_files) \ .write.mode(file_saveMode) \ .option("header", "true") \ .csv(nfs_path) But still the same result part-00000-2feefae7-47d7-4f1a-ade6-7dbd07f42f54-c000.csv Can anyone help why this is happening?
has title: I am facing issue with pyspark2.2 csv writer output
has comment: http://stackoverflow.com/comment/88329401
tagged with: apache-spark-2.2
tagged with: python
answer count: 0
type: UnansweredQuestion
type: Question
tagged with: pyspark
has comment: http://stackoverflow.com/comment/88329269

http://stackoverflow.com/comment/88294881
type: Comment
has text: For printing products variant i use **** but it shows error could you help me ?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50639664

http://stackoverflow.com/comment/88158924
type: Comment
has text: Thanks! That error disappeared but now I get another error: `Unhandled error in Deferred: 2018-05-28 17:23:28 [twisted] CRITICAL: Unhandled error in Deferred: Temporarily disabling observer LegacyLogObserverWrapper(<bound method PythonLoggingObserver.emit of <twisted.python.log.PythonLoggingObserver object at 0x10bc07a90>>) due to exception: [Failure instance: Traceback: <type 'exceptions.RuntimeError'>: maximum recursion depth exceeded while calling a Python object`
comment on: http://stackoverflow.com/a/50574755
type: AnswerComment
score: 0

http://stackoverflow.com/q/50636598
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50636709
type: Question
answer count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/88284003
has answer: http://stackoverflow.com/a/50636613
downvote count: 3
accepted answer: http://stackoverflow.com/a/50636613
has body: I'm trying to figure out why the .replace function in python isn't functioning correctly. I have spent the entire day yesterday searching for an answer but alas have not found one. I'm trying to open and read a file, copy it into a list, count the number of lines in the list and remove all the punctuation (ie , . ! ? etc). I can do everything except remove the punctuation (and I must use the .replace function instead of importing a module). with open('Small_text_file.txt', 'r') as myFile: #adding lines from file to list contents = myFile.readlines() fileList= [] # punctuation = ['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'"] for i in contents: fileList.append(i.rstrip()) print('The Statistics are:\n','Number of lines:', len(fileList)) #first part of question for item in fileList: fileList = item.replace(',', "") fileList = item.replace('.', "") print(fileList) The "Small text file" is: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus condimentum sagittis lacus? laoreet luctus ligula laoreet ut. Vestibulum ullamcorper accumsan velit vel vehicula? Proin tempor lacus arcu. Nunc at elit condimentum, semper nisi et, condimentum mi. In venenatis blandit nibh at sollicitudin. Vestibulum dapibus mauris at orci maximus pellentesque. Nullam id elementum ipsum. Suspendisse Running the code returns the following: The Statistics are: Number of lines: 6 Nullam id elementum ipsum Suspendisse So the code DOES remove the comma and period characters but it also removes the preceding 5 lines of the text and only prints the very last line. What am I doing wrong here?
score: -3
has title: Python .replace() function not working correctly
type: AnsweredQuestion
upvote count: 0
possible better answer: http://stackoverflow.com/a/50636709
favorite count: 0

http://stackoverflow.com/comment/88202451
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50596612
has text: Where are you seeing error messages? What specifically isn't working?

http://stackoverflow.com/a/50590127
type: Answer
answers question: http://stackoverflow.com/q/50589489
upvote count: 2
has body: Here is one take. Of course, I have no idea what this is doing. You should be in a much better position to add comments / sensible variable names, as others have pointed out. Still, here is what you could do. First, run a code formatter to make the code more human-friendly. def f(x): ans = 0.000140092 ans = ans * ((1 + zs) ** (3 / 2)) ans = ans * ((x + 1) ** (3 / 2)) ans = ans * XHI return ans * ( (9 / 2) * (np.log(1 - np.sqrt(b)) - np.log(np.sqrt(b) + 1)) + ( 1 / 35 * (1 / (b - 1)) * ( 10 * (b ** (9 / 2)) + 18 * (b ** (7 / 2)) + 42 * (b ** (5 / 2)) + 210 * (b ** (3 / 2)) - 315 * (b ** (1 / 2)) ) - ( (9 / 2) * (np.log(1 - np.sqrt(a)) - np.log(np.sqrt(a) + 1)) + ( 1 / 35 * (1 / (a - 1)) * ( 10 * (a ** (9 / 2)) + 18 * (a ** (7 / 2)) + 42 * (a ** (5 / 2)) + 210 * (a ** (3 / 2)) - 315 * (a ** (1 / 2)) ) ) ) ) ) Right away you see some symemtry. This chunk 10 * (b ** (9 / 2)) + 18 * (b ** (7 / 2)) + 42 * (b ** (5 / 2)) + 210 * (b ** (3 / 2)) - 315 * (b ** (1 / 2)) is a dot product of some weights and a b raised to a vector of powers. If b were scalar, we could write it as np.dot(weights, np.sqrt(b) ** powers). Maybe we would even score some optimization points from using integral powers. Putting thigs together, we can get something like this: weights = np.array([10, 18, 42, 210, -315]) powers = np.array([9, 7, 5, 3, 1]) def log_term(x): return (9 / 2) * (np.log(1 - np.sqrt(x)) - np.log(np.sqrt(x) + 1)) def dot_term(x): return (1 / 35) * 1 / (x - 1) * np.dot(np.sqrt(x)[..., None] ** powers, weights) def integrate(x): return log_term(x) + dot_term(x) factor1 = integrate(b) - integrate(a) factor2 = 0.000140092 * ((1 + zs) ** (3 / 2)) * XHI factor = factor1 * factor2 def f(x): return factor * ((x + 1) ** (3 / 2)) With better variable names and comments this could almost be readable. Side comment. Both in your original code and in this version, you define x in the body of your script. You also define several variables as a function of x, such as a and b. Python scoping rules …
score: 2
downvote count: 0

http://stackoverflow.com/comment/88343319
type: AnswerComment
comment on: http://stackoverflow.com/a/50666432
type: Comment
has text: Please accept one of the ans that helped you. Thanks
score: 0

http://stackoverflow.com/a/50692627
has comment: http://stackoverflow.com/comment/88401286
type: Answer
has comment: http://stackoverflow.com/comment/88402076
accepted answer of: http://stackoverflow.com/q/50692568
has comment: http://stackoverflow.com/comment/88401225
answers question: http://stackoverflow.com/q/50692568
has comment: http://stackoverflow.com/comment/88401799
score: 4
has body: You just need to write back out to a file, you can open it in the same line as f1 and then use f2.write() to write a new line to it: def label_change(): label_old = input("Enter label u wanna change: ") label_new = input("Enter new one: ") with open("aud.txt","r") as f1, open("aud2.txt", "w") as f2: for i in f1.readlines(): r = i.split("|") label = r[0] desc = r[1] adr = r[2] if label_old == label: label = label_new f2.write(label + "|" + desc + "|" + adr) In order to write to the same file, you can save the contents to a list and the write: def label_change(): label_old = input("Enter label u wanna change: ") label_new = input("Enter new one: ") contents = [] with open("aud.txt","r") as f1: for i in f1.readlines(): r = i.split("|") label = r[0] desc = r[1] adr = r[2] if label_old == label: label = label_new contents.append(label + "|" + desc + "|" + adr) with open("aud.txt", "w") as f1: for line in contents: f1.write(line)
has comment: http://stackoverflow.com/comment/88401703
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88185637
type: Comment
type: QuestionComment
score: 1
has text: It would really help for us to see your data
comment on: http://stackoverflow.com/q/50587899

http://stackoverflow.com/a/50635091
type: Answer
has comment: http://stackoverflow.com/comment/88887090
accepted answer of: http://stackoverflow.com/q/50581883
has comment: http://stackoverflow.com/comment/88901047
score: 5
answers question: http://stackoverflow.com/q/50581883
upvote count: 5
has comment: http://stackoverflow.com/comment/88848837
has comment: http://stackoverflow.com/comment/88876297
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88849132
has body: Is there an easier, more direct way to do it, without having to export it to a .pb file, then freeze it and so on? Yes, as you pointed out in the updated question, it is possible to freeze the graph and use toco_convert in python api directly. It needs the graph to be frozen and the input and output shapes to be determined. In your question, there is no freeze graph step since there are no variables. If you have variables and run toco without converting those to constants first, toco will complain! Now all I have to do is find a way to adapt this to the iris classification model. Any suggestions? This one is slightly trickier and needs more work. Basically, you need to load the graph and figure out the input and output tensor names and then freeze the graph and call toco_convert. For finding the input and output tensor names in this case (where you have not defined the graph), you have to poke around the graph generated and determine them based on input shapes, names, etc. Here is the code that you can append at the end of your main function in premade_estimator.py to generate the tflite graph in this case. print("\n====== classifier model_dir, latest_checkpoint ===========") print(classifier.model_dir) print(classifier.latest_checkpoint()) debug = False with tf.Session() as sess: # First let's load meta graph and restore weights latest_checkpoint_path = classifier.latest_checkpoint() saver = tf.train.import_meta_graph(latest_checkpoint_path + '.meta') saver.restore(sess, latest_checkpoint_path) # Get the input and output tensors needed for toco. # These were determined based on the debugging info printed / saved below. input_tensor = sess.graph.get_tensor_by_name("dnn/input_from_feature_columns/input_layer/concat:0") input_tensor.set_shape([1, 4]) out_tensor = sess.graph.get_tensor_by_name("dnn/logits/BiasAdd:0") out_tensor.set_shape([1, 3]) # Pass the output node name we are interested in. # Based on the debugging info printed / saved below, pulled out the # name …

http://stackoverflow.com/comment/88300146
type: QuestionComment
comment on: http://stackoverflow.com/q/50643780
score: 1
has text: Side-note: `if bool(n) == True:` is an incredibly unPythonic (and slow) way to spell `if n:`. Similarly, `elif bool(n) == False:` is better as `elif not n:` (and in this case, you didn't need to test it at all the second time; since the only options are truthy or falsy, the even better spelling here would be `else:`). You should never compare anything to `True` or `False` (final recommendation [here](https://www.python.org/dev/peps/pep-0008/#programming-recommendations)), and explicit conversion to `bool` is almost never necessary and slower than you might think.
type: Comment

http://stackoverflow.com/a/52691604
score: 0
has body: To Kill the local server, you may use Ctrl+C command and not any other command. This command is also mentioned when the server is up and running.
type: Answer
answers question: http://stackoverflow.com/q/50659044

scipy
tags question: http://stackoverflow.com/q/50610728
tags question: http://stackoverflow.com/q/50542864
tags question: http://stackoverflow.com/q/50661967
tags question: http://stackoverflow.com/q/50546065
tags question: http://stackoverflow.com/q/50693921
tags question: http://stackoverflow.com/q/50615463
tags question: http://stackoverflow.com/q/50647368
tags question: http://stackoverflow.com/q/50638315
tags question: http://stackoverflow.com/q/50646415
tags question: http://stackoverflow.com/q/50665681
tags question: http://stackoverflow.com/q/50612095
tags question: http://stackoverflow.com/q/50651997
type: Tag
tags question: http://stackoverflow.com/q/50665141
tags question: http://stackoverflow.com/q/50691375
tags question: http://stackoverflow.com/q/50559569
tag name: scipy
tags question: http://stackoverflow.com/q/50600831
tags question: http://stackoverflow.com/q/50576540
tags question: http://stackoverflow.com/q/50561013
tags question: http://stackoverflow.com/q/50560267
tags question: http://stackoverflow.com/q/50693669
tags question: http://stackoverflow.com/q/50578654
tags question: http://stackoverflow.com/q/50667003
tags question: http://stackoverflow.com/q/50542382
tags question: http://stackoverflow.com/q/50566226
tags question: http://stackoverflow.com/q/50582647
tags question: http://stackoverflow.com/q/50668212
tags question: http://stackoverflow.com/q/50626710
tags question: http://stackoverflow.com/q/50583777
tags question: http://stackoverflow.com/q/50653454
tags question: http://stackoverflow.com/q/50541885
tags question: http://stackoverflow.com/q/50685839
tags question: http://stackoverflow.com/q/50597925
tags question: http://stackoverflow.com/q/50591442
tags question: http://stackoverflow.com/q/50573104
tags question: http://stackoverflow.com/q/50644578
tags question: http://stackoverflow.com/q/50688365
tags question: http://stackoverflow.com/q/50560404
tags question: http://stackoverflow.com/q/50580459
tags question: http://stackoverflow.com/q/50574566
tags question: http://stackoverflow.com/q/50668651
tags question: http://stackoverflow.com/q/50557669
tags question: http://stackoverflow.com/q/50630101
tags question: http://stackoverflow.com/q/50646592
tags question: http://stackoverflow.com/q/50553645
tags question: http://stackoverflow.com/q/50667903
tags question: http://stackoverflow.com/q/50685015
tags question: http://stackoverflow.com/q/50545630
tags question: http://stackoverflow.com/q/50631713
tags question: http://stackoverflow.com/q/50558999
tags question: http://stackoverflow.com/q/50648860
tags question: http://stackoverflow.com/q/50587012
tags question: http://stackoverflow.com/q/50668453
tags question: http://stackoverflow.com/q/50673243
tags question: http://stackoverflow.com/q/50601648
tags question: http://stackoverflow.com/q/50552356

http://stackoverflow.com/q/50571231
type: Question
has answer: http://stackoverflow.com/a/50571355
answer count: 3
score: 5
has answer: http://stackoverflow.com/a/50571551
duplicate of: http://stackoverflow.com/q/48736670
favorite count: 0
tagged with: python-3.x
upvote count: 5
tagged with: python
has body: I would like to know how Python 3 (not 2, please :P) address the following situation: I have a class and two instances: class MyClass: def something(): pass a = MyClass() b = MyClass() Do a.something and b.something share the same memory address, or each one have a something declared? How the resolution of calling a.something works? When I try to see the methods id, they have the same: id(a.something), id(b.something) # (4487791304, 4487791304) But when I use is to compare if it's the same, the result is `False: id(a.something) is id(b.something) # And if I go furthermore, and print the available methods and data attributes of a or b, I can see that both of them have the something declared: ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'something'] Thank you.
has comment: http://stackoverflow.com/comment/88152301
possible better answer: http://stackoverflow.com/a/50571355
has title: Does different instances share the same methods declared in the class?
downvote count: 0
has comment: http://stackoverflow.com/comment/88152310
linked to: http://stackoverflow.com/q/48736670
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50571377
accepted answer: http://stackoverflow.com/a/50571377

http://stackoverflow.com/a/50648074
has body: After handling the default case, which submits a null query, I was able to fix my issue. Below is the corrected code. def search_bar(request): term = request.GET.get('term') if term: results = objCW.search(term) context = {'results': results} return render(request, 'uccx/search.html', context) else: context = {'': ''} return render(request, 'uccx/search.html', context)
answers question: http://stackoverflow.com/q/50630464
accepted answer of: http://stackoverflow.com/q/50630464
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/88332653
comment on: http://stackoverflow.com/q/50660685
score: 0
type: QuestionComment
type: Comment
has text: Please share your MainScreen.

http://stackoverflow.com/q/50656964
answer count: 1
favorite count: 0
tagged with: asyncpg
accepted answer: http://stackoverflow.com/a/50657088
downvote count: 2
tagged with: python
has title: Best way to open/close DB Connection with async/await
type: AnsweredQuestion
score: 2
tagged with: async-await
tagged with: tornado
type: Question
upvote count: 4
tagged with: event-loop
has answer: http://stackoverflow.com/a/50657088
has body: In tutorials I found, there is always opening and closing the connection for every request, for example : import asyncio import asyncpg async def run(): conn = await asyncpg.connect(user='user', password='password', database='database', host='127.0.0.1') values = await conn.fetch('''SELECT * FROM mytable''') await conn.close() loop = asyncio.get_event_loop() loop.run_until_complete(run()) While this works for one single function, How about web application ? IE: for example in Tornado, every URL is a class, which leads to lot of classes/methods. I have the habit to open the connection in a blocking way, then use the wrapper to make asynchronous DB calls, and close the connection only to shut down gracefuly the server, what is the best practice in that case with async/await ?
linked to: http://stackoverflow.com/q/42242093

http://stackoverflow.com/comment/88269377
type: Comment
has text: Should note that if the function is called more than one (and the file is not deleted beforehand) the results of each run will continue to be appended to the file.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50629701

http://stackoverflow.com/comment/88119914
type: AnswerComment
type: Comment
has text: I edited the question to show / briefly explain the code and show an additional KCacheGrind screen. Thx again for your help!
comment on: http://stackoverflow.com/a/50554426
score: 0

http://stackoverflow.com/q/50609465
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88264473
has comment: http://stackoverflow.com/comment/88228641
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
has body: I have used pandas excel read operation and merge operation to merge two spreadsheets in the same excel document together into one dataframe. The merged dataframe contains NaN values. I would like to replace/fill the NaN values with data from one of the original spreadsheets in the excel document. Is this possible? Data details: Historical Sheet Photo ID| Type| Date| Location 1 jpg 5/30/18 USA 2 jpg 5/30/18 USA 3 tiff 5/30/18 CAN 4 tiff 5/30/18 AUS 5 img 5/30/18 AUS Current Sheet: Photo ID| Type| Taken| Location 1 jpg 5/30/18 USA 2 jpg 5/30/18 USA 3 tiff 5/30/18 CAN 5 img 5/30/18 AUS Current Code: import pandas as pd from pandas import ExcelWriter from pandas import ExcelFile file_location = "H:\\Travel\\AC_Images.xlsx" test_xls = pd.ExcelFile(file_location) historical = test_xls.parse("Historical Photos",skiprows=1) current = test.xls.parse("Current Photos",skiprows=2) photo_data = historical.merge(current, left_on = "Photo ID", right_on = "photonum", how = "left") photo_data = photo_data[photo_data['Photo ID'].notnull()] Example Return: Photo ID| Type| Date| Location 1 jpg 5/30/18 USA 2 jpg 5/30/18 USA 3 tiff 5/30/18 CAN 4 NaN NaN NaN NaN 5 img 5/30/18 AUS Again, the merged output contains NaN values. I would like to populate the Date NaN cells with Date values from the Historical Photos sheet in the AC_Images excel document. I tried this: photo_data.replace('NaN', "Historical Photos"["location"]) It returned an error "string indicies must be integers." I am not sure how to pull the data from that column and import it in the NaN cells in the merged dataframe. Guidance?
tagged with: python
has title: Pandas .replace or .fillna to fill NAN values remedy
has comment: http://stackoverflow.com/comment/88230420
has answer: http://stackoverflow.com/a/50627256
upvote count: 1
answer count: 1
tagged with: excel
accepted answer: http://stackoverflow.com/a/50627256
has comment: http://stackoverflow.com/comment/88232431
has comment: http://stackoverflow.com/comment/88232757

http://stackoverflow.com/comment/88255749
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50622088
has text: How exactly do you measure that it is "faster"? What exactly do you compare it to? For what values? Also your code looks like Python so it probably makes sense to add that as a tag.

http://stackoverflow.com/q/50624745
downvote count: 1
linked to: http://stackoverflow.com/q/51140470
upvote count: 17
type: Question
tagged with: pyspark
has answer: http://stackoverflow.com/a/57386306
answer count: 3
possible better answer: http://stackoverflow.com/a/57386306
has answer: http://stackoverflow.com/a/50626100
favorite count: 0
tagged with: bigdata
tagged with: python
has answer: http://stackoverflow.com/a/50627510
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/110701736
accepted answer: http://stackoverflow.com/a/50626100
has body: I've got a dataframe like this and I want to duplicate the row n times if the column n is bigger than one: A B n 1 2 1 2 9 1 3 8 2 4 1 1 5 3 3 And transform like this: A B n 1 2 1 2 9 1 3 8 2 3 8 2 4 1 1 5 3 3 5 3 3 5 3 3 I think I should use explode, but I don't understand how it works... Thanks
score: 16
has title: Pyspark: how to duplicate a row n time in dataframe?

cassandra-driver
type: Tag
tag name: cassandra-driver
tags question: http://stackoverflow.com/q/50630585

http://stackoverflow.com/q/50642636
has comment: http://stackoverflow.com/comment/88295695
type: Question
has body: I want to encode the column values in pandas dataframe, such as the all the letters should be converted to a single letter(eg., 'vault' to 'NNNNN' , 'Nan123' to 'NNNDDD'). I'm thinking of something like this: df['TransDetails'] = df['TransDetails'].str.replace('A', 'N') My data: TransDetails 0 NEFT-PUNB0315500-JITENDER SING 1 NEFT-UTIB0CCH274-VIRENDER KUMA 2 NEFT-UTIB0CCH274-SUNITA DEVI 3 NEFT-PUNB0315500-AMLASH KUMAR 4 NEFT-PUNB0109800-FARIDUDDEN 5 NEFT-PUNB0109800-IDREESH 6 NEFT-PUNB0315500-BUDDHU 7 NEFT-UTIB0CCH274-SAKIL AHAMAD 8 NEFT-UTIB0CCH274-NAIM AHAMAD 9 NEFT-UTIB0CCH274-SALIM AHAMAD 10 NEFT-UTIB0CCH274-NADIM AHAMAD How can I convert all the column values in such codes? Thanks in advance
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88295484
score: 0
has answer: http://stackoverflow.com/a/50642800
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50642773
has answer: http://stackoverflow.com/a/50642773
has comment: http://stackoverflow.com/comment/88295827
tagged with: python
has title: I want to encode the column values in pandas dataframe
accepted answer: http://stackoverflow.com/a/50642800
type: AnsweredQuestion

http://stackoverflow.com/q/50629277
has comment: http://stackoverflow.com/comment/88269427
tagged with: python
has body: In the past few years I have worked with the libtiff library and I have developed some classes and scripts around it. I felt confident to now use my insights in a larger project. Instead of opening one TIFF file, I had to now open many of them. The runtime error "maximum recursion depth exceeded" has continued to disturb me since. Of course, I tried opening, reading and closing one file after the other - to no avail. I tried using the "del" keyword as well as gc.collect() - to no avail. What happens is that the local function extender_pyfunc with argument tiff_struct is invoking itself recursively. This function is part of the method __init__of class TIFFExtender in module libtiff_ctypes. The first time a TIFF file is opened there's no problem and as long as the TIFF files are read within a main() function no problems seem to occur, but as soon as I invoke my code from a method the runtime error comes back. Here's my module read_multiple_tifs.py: from libtiff.libtiff_ctypes import TIFFFieldInfo, TIFFDataType, FIELD_CUSTOM, add_tags, TIFF from libtiff import libtiff from lmgeo.formats import inmemoryraster from math import floor, ceil import os.path import numpy as np __ncols = 1 __nrows = 1 __tile_width = 1 __tile_length = 1 __nstrips = 1 __samples_per_pixel = 1 __bits_per_sample = 8 __sample_format = 16 __itemsize = 4 __tif = None def dummy(self, *args): pass; __ReadStrip = dummy(0, 0, 1) def ReadStripOfTiles(strip, buf, size): result = False try: num_tiles_per_strip = int(ceil(__ncols / __tile_width)) numpy_type = __tif.get_numpy_type(__bits_per_sample, __sample_format) if (strip == __nstrips-1): length = __nrows - (strip*__tile_length) else: length = __tile_length buf = buf.reshape(length, __ncols, __samples_per_pixel) for k in range(num_tiles_per_strip): if (k == num_tiles_per_strip-1): # We only need part of the tile because we are on the edge width = __ncols - (num_tiles_per_strip-1)*__tile_width else: width = __tile_width # Fill the buffer tile by tile tmp_bu…
tagged with: recursion
answer count: 0
score: 1
has title: How to prevent maximum recursion runtime error in python when using the libtiff library
upvote count: 1
type: Question
tagged with: ctypes
has comment: http://stackoverflow.com/comment/88291593
has comment: http://stackoverflow.com/comment/102076506
tagged with: libtiff
has comment: http://stackoverflow.com/comment/88296090
tagged with: runtime-error
has comment: http://stackoverflow.com/comment/88271004
downvote count: 0
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/88166553
score: 1
comment on: http://stackoverflow.com/q/50578714
type: Comment
has text: please create a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
type: QuestionComment

http://stackoverflow.com/a/50635852
downvote count: 0
has body: This seems to work: params = {'a': 'aaa', 'b': 'bbb', 'c': 'ccc', 'd': 'ddd-hoge'} print("1: {a} 2: {b} 3: {c} 4: {d}".format(**{ k: v.split('-')[0] for k, v in params.items()})) This does the processing on the dict, and then formats for print. Results: 1: aaa 2: bbb 3: ccc 4: ddd
answers question: http://stackoverflow.com/q/50635826
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/a/50616923
has comment: http://stackoverflow.com/comment/88250055
answers question: http://stackoverflow.com/q/50616770
upvote count: 2
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/50616770
has comment: http://stackoverflow.com/comment/108553493
has body: The Free Desktop Specification notes that ~/.local/bin is a general place for user binaries, so I don't think its safe to assume that deleting that wont affect anything else. The best method would be to use pip3 uninstall --user &lt;package&gt; to remove specific packages. you can list installed packages with pip3 list --user Edit: A one-liner to delete all pip3 installed packages, using pip3's uninstall method and jq: pip3 list --user --format=json | jq '.[].name' | xargs -I{} pip3 uninstall --user {} Be careful though, as it will delete everything user installed, whether you use it or not!
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/50580613
has comment: http://stackoverflow.com/comment/88170568
score: 6
accepted answer of: http://stackoverflow.com/q/50580479
answers question: http://stackoverflow.com/q/50580479
has body: Creating distinct variables does not scale well if you decide to add functionality. A class without behavior (i.e. no methods) is pretty pointless as well. My opinion is that you should use the dictionary or named tuples. &gt;&gt;&gt; from collections import namedtuple &gt;&gt;&gt; KeyBindings = namedtuple('KeyBindings', 'chars codecs hints') &gt;&gt;&gt; Chars = namedtuple('Chars', 'right left') &gt;&gt;&gt; &gt;&gt;&gt; key_bindings = KeyBindings(Chars('-&gt;', '&lt;-'), ['smooth', 'spiky'], ['Smooth protrutions', 'Spiky protrutions']) &gt;&gt;&gt; &gt;&gt;&gt; key_bindings.hints ['Smooth protrutions', 'Spiky protrutions'] &gt;&gt;&gt; key_bindings.chars.left '&lt;-'
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88170457
type: Answer
upvote count: 6

http://stackoverflow.com/comment/88231234
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/172100/discussion-between-harv-ipan-and-user40).
type: Comment
comment on: http://stackoverflow.com/a/50610110
score: 0
type: AnswerComment

http://stackoverflow.com/q/50653853
type: Question
score: 3
tagged with: enums
has answer: http://stackoverflow.com/a/50654481
tagged with: cythonize
downvote count: 0
answer count: 1
has title: Duplicate enum member names in Cython - redeclaration error?
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: Cython doesn't seem to allow me to reuse enum member names. I have the following enums that I'm trying to cythonize: from enum import Enum class Fruit(Enum): UNKNOWN = 0 APPLE = 1 ORANGE = 2 class Animal(Enum): UNKNOWN = 0 DOG = 1 CAT = 2 But the following results in a 'UNKNOWN' redeclared compilation error: cpdef enum Fruit: UNKNOWN = 0 APPLE = 1 ORANGE = 2 cpdef enum Animal: UNKNOWN = 0 DOG = 1 CAT = How should I fix the above? Also, I'd ideally like to use NULL as the enum member names instead of UNKNOWN. But it seems that NULL is a privileged keyword for Cython though it's not for CPython. Is there any workaround?
upvote count: 3
tagged with: cython

http://stackoverflow.com/q/50603891
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50605256
favorite count: 0
has title: How to install libraries to python in zeppelin-spark2 in HDP
accepted answer: http://stackoverflow.com/a/50605256
tagged with: python
upvote count: 2
has comment: http://stackoverflow.com/comment/119454658
has body: I am using HDP Version: 2.6.4 Can you provide a step by step instructions on how to install libraries to the following python directory under spark2 ? The sc.version (spark version) returns res0: String = 2.2.0.2.6.4.0-91 The spark2 interpreter name and value is as following zeppelin.pyspark.python: /usr/local/Python-3.4.8/bin/python3.4 The python version and current libraries are %spark2.pyspark import pip import sys sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()]) print("--") print (sys.version) print("--") print(installed_packages_list) -- 3.4.8 (default, May 30 2018, 11:05:04) [GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] -- ['pip==9.0.1', 'setuptools==28.8.0'] Update 1: using pip install [package name] actually leads to two problems 1) The HDP is pointing at python2.6 rather than python3.4.8 2) pip3 is not there for some reason Therefore, I am thinking of installing miniconda and pointing Zeppelin there and installing all the packages in conda to prevent conflict between python 2.6 and 3.4.8
tagged with: hortonworks-data-platform
tagged with: apache-zeppelin
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/60011726
tagged with: pyspark
has answer: http://stackoverflow.com/a/60011726

http://stackoverflow.com/q/50568409
type: Question
has title: Report Keras model evaluation metrics every 10 epochs?
downvote count: 0
tagged with: keras
has answer: http://stackoverflow.com/a/50569215
linked to: http://stackoverflow.com/q/50539213
tagged with: performance-testing
answer count: 1
tagged with: keras-2
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 7
upvote count: 7
has comment: http://stackoverflow.com/comment/88146955
has body: I'd like to know the specificity and sensitivity of my model. Currently, I'm evaluating the model after all epochs are finished: from sklearn.metrics import confusion_matrix predictions = model.predict(x_test) y_test = np.argmax(y_test, axis=-1) predictions = np.argmax(predictions, axis=-1) c = confusion_matrix(y_test, predictions) print('Confusion matrix:\n', c) print('sensitivity', c[0, 0] / (c[0, 1] + c[0, 0])) print('specificity', c[1, 1] / (c[1, 1] + c[1, 0])) The disadvantage of this approach, is I only get the output I care about when training has finished. Would prefer to get metrics every 10 epochs or so. BTW: Tried with the metrics=[] here. Possibly a callback is the way to go?
tagged with: tensorflow

http://stackoverflow.com/a/67637009
has body: from tkinter import * root = Tk() frame1 = Frame(root, highlightbackground="blue", highlightthickness=1,width=600, height=100, bd= 0) frame1.pack() root.mainloop() change the options accordingly highlightbackground is used to change the color of the widget in focus highlightthickness is used to specify the thickness of the border around the widget in focus.
score: 5
upvote count: 5
answers question: http://stackoverflow.com/q/50691267
downvote count: 0
type: Answer

http://stackoverflow.com/q/50651193
answer count: 0
score: 1
upvote count: 1
tagged with: sqlalchemy
type: Question
downvote count: 0
has title: pandas to_sql failing after updated pandas
has comment: http://stackoverflow.com/comment/88694556
tagged with: pandas
favorite count: 0
type: UnansweredQuestion
has body: I updated pandas from .20 to .23 recently, and now a script that would insert a pandas DataFrame to sql (MS SQL Server) fails. The frame is the same as it always has been (it's read from sql using pandas read_sql_table, and then just written back, solely as a test to make sure things are working). I haven't changed any drivers, e.g. odbc, and I tested across a few drivers that worked for me prior to the update. After the failure, I updated sqlalchemy, but this hasn't helped. I get this error: (pyodbc.ProgrammingError) ('The SQL contains 6039 parameter markers, but 137111 parameters were supplied', 'HY000') [SQL: 'INSERT INTO dbo.test_python_drop_write_append (various column names here) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?), (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?), (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?), (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, There are actual dataframe values farther down, but I didn't include them here. The question marks are odd-looking and I can't explain them. When I print the head of the dataframe, it looks just fine, and as I stated, it's the exact same dataframe that pandas has been reading and rewriting to sql in this test script successfully before. I don't even know what a parameter marker is, and I'm not trying to explicitly specify anything related to them. The writing code is this, and it's using the same sqlcon object that successfully reads data: dataf.to_sql(name=tablename, con=sqlcon, schema=schemaname, index=False, if_exists='replace') I'm hoping an edit might get me some more attention, and I have some more information. I tried looking through sql alchemy code to no avail. I w…
tagged with: python

http://stackoverflow.com/comment/88120636
comment on: http://stackoverflow.com/a/50554925
score: 0
has text: An instance making its own variable is the definition of dynamic
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50550375
has answer: http://stackoverflow.com/a/50550506
answer count: 1
downvote count: 0
favorite count: 0
has body: I am not able us bbox in python. code written bx=ttk.Treeview.bbox(db_rslt,"aman don",column='4') bx.configure(text='don') It is giving me error like File "C:\Users\Amandip\Anaconda3\lib\tkinter\ttk.py", line 1191, in bbox return self._getints(self.tk.call(self._w, "bbox", item, column)) or '' _tkinter.TclError: bad option "bbox": must be cget or configure
tagged with: python
accepted answer: http://stackoverflow.com/a/50550506
type: AnsweredQuestion
tagged with: tkinter
score: 1
upvote count: 1
type: Question
has title: Example for using bbox in treeview in python

http://stackoverflow.com/comment/88108760
comment on: http://stackoverflow.com/a/50547893
has text: Hi, I got one more question: The maximum length seems to be set to about 24h. I played around with the limit value, removed this limitation entirely, added "all_data=True", all without success.Do you have an idea how I would be able to get a timestamp.min() of 10 or 20 months back or even set a simple start date? This is the the portion I changed:
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89713495
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50572355
type: Comment
has text: @jpp "In place" ... with respect to the original DataFrame as opposed to using a function which returns a copy with the modified headers.... some disambiguation required.

http://stackoverflow.com/a/50633904
accepted answer of: http://stackoverflow.com/q/50633630
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50633630
score: 0
has comment: http://stackoverflow.com/comment/88307096
has comment: http://stackoverflow.com/comment/88307549
has body: I would read through the data once like you have already but store all rows with 'Card Task' in a separate list. Once you have a list of only card task items you can compare. card_task_row_object_list = [] count = 0 for row in sheet.rows: if 'Card Task' in row[4]: card_task_row_object_list.append(row) From here you would want to compare the time values. What are you needed to check, if two different card task times overlap? (row 12: start, row 13: end) def compare_times(card_task_row_object_list): for row in card_task_row_object_list: for comparison_row in card_task_row_object_list: if (comparison_row[12] &lt;= row[13] &amp;&amp; comparison_row[13] &gt;= row[12]) # No overlap else count+=1
type: Answer
has comment: http://stackoverflow.com/comment/88278225
has comment: http://stackoverflow.com/comment/88306961
has comment: http://stackoverflow.com/comment/88306988
has comment: http://stackoverflow.com/comment/88305707
has comment: http://stackoverflow.com/comment/88305950

http://stackoverflow.com/q/50655738
has answer: http://stackoverflow.com/a/51136986
has title: How do I resolve a TesseractNotFoundError?
has answer: http://stackoverflow.com/a/51662074
has answer: http://stackoverflow.com/a/66966105
has answer: http://stackoverflow.com/a/56605161
score: 101
has answer: http://stackoverflow.com/a/50855927
has answer: http://stackoverflow.com/a/55856244
has answer: http://stackoverflow.com/a/52237389
has answer: http://stackoverflow.com/a/52464062
has answer: http://stackoverflow.com/a/51829780
has answer: http://stackoverflow.com/a/50658000
upvote count: 102
has answer: http://stackoverflow.com/a/56559289
answer count: 26
has body: I am trying to use pytesseract in Python but I always end up with the following error: raise TesseractNotFoundError() pytesseract.pytesseract.TesseractNotFoundError: tesseract is not installed or it's not in your path However, pytesseract and Tesseract are installed on my system. Example code that produces this error: import cv2 import pytesseract img = cv2.imread('1d.png') print(pytesseract.image_to_string(img)) How do I resolve this TesseractNotFoundError?
has answer: http://stackoverflow.com/a/54199314
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/101806760
has answer: http://stackoverflow.com/a/65121519
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/54249658
tagged with: python
has answer: http://stackoverflow.com/a/51583635
tagged with: tesseract
tagged with: python-tesseract
has answer: http://stackoverflow.com/a/53387483
has answer: http://stackoverflow.com/a/50812164
has answer: http://stackoverflow.com/a/56885296
has answer: http://stackoverflow.com/a/59109764
has answer: http://stackoverflow.com/a/54979355
has answer: http://stackoverflow.com/a/64803742
has answer: http://stackoverflow.com/a/50794870
has answer: http://stackoverflow.com/a/50720602
downvote count: 1
has answer: http://stackoverflow.com/a/70183079
has answer: http://stackoverflow.com/a/75745055
type: Question
has answer: http://stackoverflow.com/a/56285610

http://stackoverflow.com/comment/88145078
type: AnswerComment
has text: each line in the file is a space separated file....like word=line.split(" ") and then the word[0] is the column header and word[1] is the column value
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50567515

http://stackoverflow.com/a/50612443
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/50610557
has body: Filter out false positives after the test items are collected: create a conftest.py in your tests directory with the custom post-collection hook: # conftest.py def pytest_collection_modifyitems(session, config, items): items[:] = [item for item in items if item.name != 'test_session'] pytest will still collect the test_session methods (you will notice that in the pytest report line collected n tests), but not execute them as tests and not consider them anywhere in the test run. Related: fix for unittest-style tests Check out this answer.
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50610557
has comment: http://stackoverflow.com/comment/88283167

http://stackoverflow.com/q/50557621
has comment: http://stackoverflow.com/comment/88126112
has comment: http://stackoverflow.com/comment/93501695
has title: Pointer to Python substring: memoryview vs itertools.islice vs …?
linked to: http://stackoverflow.com/q/18655648
tagged with: python
has comment: http://stackoverflow.com/comment/88126466
has comment: http://stackoverflow.com/comment/88126084
tagged with: binary-search-tree
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50557837
score: 1
type: Question
upvote count: 1
answer count: 1
downvote count: 0
tagged with: string
tagged with: data-structures
favorite count: 0
has body: Would I be better off using memoryview, itertools.islice or something else (e.g. var = (start, stop)) as a pointer in Python to a substring of a very large string? Context: I have some very long strings that I need to manipulate (cut and paste substrings, etc.) without creating a new string each time. I accomplish that by making a binary search tree in which each node represents a substring and then using split/merge operations (a Rope data structure). Each node needs a reference attached to it to the substring of the original very large string that the node represents. (That's necessary so that, when I walk the tree in-order to produce the final edited string, I get back the parts of the original string in the amended sequence.) I could attach a tuple representing start/stop values to each node and then use slicing string[start:stop], but in C you would use a pointer and a character count. Would it be better to do something similar in Python, either with memoryview or with islice or with something else?

http://stackoverflow.com/q/50635938
tagged with: paramiko
tagged with: centos
score: 0
tagged with: sftp
linked to: http://stackoverflow.com/q/15481934
has comment: http://stackoverflow.com/comment/88285212
favorite count: 0
has body: I have been trying to automate SFTP transfer from a Windows client via a python script to a CentOS machine running an Apache server. I have created a user account on the CentOS server that can only access SFTP, similar to the instructions listed here: https://www.digitalocean.com/community/tutorials/how-to-enable-sftp-without-shell-access-on-centos-7 I then used the following code in an attempt to transfer the file transport.connect(username = username, password = password) sftp = paramiko.SFTPClient.from_transport(transport) sftp.put(base_dir + '\\report', '/var/www/html/reports/' + host_name, confirm = False) However this results in the following error: Traceback (most recent call last): File "noschedule_make_report.py", line 74, in &lt;module&gt; main() File "noschedule_make_report.py", line 62, in main sftp.chdir('/var/www/html/reports') File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 626, in chdir if not stat.S_ISDIR(self.stat(path).st_mode): File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 460, in stat t, msg = self._request(CMD_STAT, path) File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 780, in _request return self._read_response(num) File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 832, in _read_response self._convert_status(msg) File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 861, in _convert_status raise IOError(errno.ENOENT, text) IOError: [Errno 2] No such file This code worked when I didn't set the restrictions on the upload user account as described in the Digital Ocean post, and instead had much more liberal permissions and shell login. Is there a way for me to have both the locked out login for the upload user and to use the Paramiko funcitonality? Please note that using a sftp.chdir('/var/www/html/reports') command before the put command produced the same error, occurring at the chdir line instead. Also I understand that similar questions have been asked (IO…
has title: Paramiko failing due due to file permissions
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50637073
has comment: http://stackoverflow.com/comment/88284760
downvote count: 1
has comment: http://stackoverflow.com/comment/88284021
type: Question
has comment: http://stackoverflow.com/comment/88283824
accepted answer: http://stackoverflow.com/a/50637073
answer count: 1

http://stackoverflow.com/comment/88417784
has text: "the delegate would be activated to edit the texts, and that is what is not wanted, so we establish a new delegate that no publisher returns as I show below:" I assume that the delegate is the code I create to overwrite the paren'ts method, but I don't understand the rest of this sentence. Thanks again eyllanesc.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50686271
type: AnswerComment

http://stackoverflow.com/q/50562626
tagged with: file-io
has comment: http://stackoverflow.com/comment/88135768
downvote count: 0
has comment: http://stackoverflow.com/comment/135512218
favorite count: 0
has answer: http://stackoverflow.com/a/50566228
has body: I am wanting to read pairs of lines in from a file, and perform operations on them. How do I go about doing this in Python? I can read the file once with the code below, but I don't know how to turn this into being able to read a whole file of lets say 20 lines, with the rest of my code having to operate on the 10 sets of data that the 20 line file has. There will always be an even amount of lines in the input file. import sys input = sys.stdin favouriteNumbersInput = [] with open("test.txt", 'r') as infile: lines_gen = islice(infile, 2) for line in lines_gen: favouriteNumbersInput.append(line.strip(' ').strip('\n')) firstName,lastName = map(str,line.split(" ")) favouriteNumbers = list(map(int, favouriteNumbersInput)) Input: 3, 1, 5, 2 John Doe 5, 1, 6, 7 Jane Doe Output: Sum of favourite numbers for John Doe: 11 Sum of favourite numbers for Jane Doe: 19
tagged with: python
has comment: http://stackoverflow.com/comment/88136983
has answer: http://stackoverflow.com/a/50565731
answer count: 4
has answer: http://stackoverflow.com/a/50562731
type: AnsweredQuestion
has title: Python - Reading pairs of lines in a file
upvote count: 3
possible better answer: http://stackoverflow.com/a/50565731
accepted answer: http://stackoverflow.com/a/50566228
type: Question
has comment: http://stackoverflow.com/comment/88135782
score: 3
has answer: http://stackoverflow.com/a/50562735

http://stackoverflow.com/q/50550227
has comment: http://stackoverflow.com/comment/88111445
tagged with: singly-linked-list
has comment: http://stackoverflow.com/comment/88111542
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88111367
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88111403
has comment: http://stackoverflow.com/comment/88111760
score: 0
has comment: http://stackoverflow.com/comment/88111454
has comment: http://stackoverflow.com/comment/88111677
has answer: http://stackoverflow.com/a/50550530
answer count: 1
has comment: http://stackoverflow.com/comment/88111607
has title: How do I use __str__() and __repr__() for a singly linked list in Python 3.6?
favorite count: 0
has comment: http://stackoverflow.com/comment/88111429
has comment: http://stackoverflow.com/comment/88111525
accepted answer: http://stackoverflow.com/a/50550530
has body: everyone. I've got a bit of a problem I need to sort out, and I was hoping for some assistance on what to do. So, I have this Python 3.6 assignment I've been working on, regarding Singly Linked Lists. Most of my test cases for appending/prepending, removing from front and back, and deleting nodes altogether are going well so far. However, I have some issues with a few of my test cases. The issues revolve around my use of the __str__(self) and __repr__(self) functions. Down below is the code I'm providing. (EDIT: I left only the test codes that has the faults that need fixing. All the other test cases are fine): class LinkedList(object): class Node(object): # pylint: disable=too-few-public-methods ''' no need for get or set, we only access the values inside the LinkedList class. and really: never have setters. ''' def __init__(self, value, next = None): self.value = value self.next = next def __repr__(self): return repr(self.value) def __str__(self): return str(self.value) + "; " def __init__(self, initial=None): self.front = self.back = self.current = None def empty(self): return self.front == self.back == None def __iter__(self): self.current = self.front return self def __str__(self): string = 'List[ ' curr_node = self.front while curr_node != None: string += str(curr_node) curr_node = curr_node.next() string += ']' return string def __repr__(self): nodes = [] curr = self.front while curr: nodes.append(repr(curr)) curr = curr.next return '[' +', '.join(nodes) + ']' def __next__(self): if self.current: tmp = self.current.value self.current = self.current.next return tmp else: raise StopIteration() def push_front(self, value): x = self.Node(value, self.front) if self.empty(): self.front = self.back = x else: self.front = x #you need to(at least) implement the following three methods def pop_front(self): if self.empty(): raise RuntimeError("Empty List") x = self.front.value self.front = self.front.next if not self.front: self.back = None return x def push_back(self, …
tagged with: python

http://stackoverflow.com/comment/120564573
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50626100
type: AnswerComment
has text: @DVL Unfortunately some of us are still stuck with previous spark versions...

http://stackoverflow.com/comment/88129488
has text: @Alex - Yes, also removeing duplicated level, but if performance is important `transform` is my choice.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50559342

http://stackoverflow.com/comment/88411107
type: Comment
has text: BTW, `conda-manager` installs for me, but Spyder doesn't seem to find it :( Not sure why yet.
type: AnswerComment
comment on: http://stackoverflow.com/a/50700776
score: 0

http://stackoverflow.com/comment/88352718
has text: I got it, the problem now is that ' ' > ' is not supported between instances of 'complex' and 'int' ', so it means that I would have to change all code, isn't it? Anyway, I don't need the complex root, I only need [ ] as return when b**2 - 4*a*c < 0, but advice appears always.
comment on: http://stackoverflow.com/a/50671265
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88205214
score: 0
has text: This does not provide any direct solution to your problem but just to let you know there is an `ImageField` in Django that you can use! Check [here](https://docs.djangoproject.com/en/2.0/ref/models/fields/#imagefield)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50597807

http://stackoverflow.com/comment/88388288
comment on: http://stackoverflow.com/a/50689233
type: AnswerComment
score: 0
has text: Not my downvote, but probably because `data['amount']` does not work because the JSON defines a nested dictionary.
type: Comment

http://stackoverflow.com/comment/88128235
has text: `return ['Emma', 'Madison', 'Hannah', 'Grace', 'Emily`]` should do it
score: 0
comment on: http://stackoverflow.com/q/50558768
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88178393
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50567528
type: Comment
has text: True - for things which are guaranteed constants I'd probably use `self.BAR` too to be honest ;)

http://stackoverflow.com/comment/88313375
has text: Anyway: Convert them into `datetime.timedelta` objects, or integer microseconds or milliseconds, or float seconds, or any other type that can do basic arithmetic, and then you can average them the same way you'd average anything else: either with `statistics.mean`, or just `sum(times) / len(times)`.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50651216

http://stackoverflow.com/q/50649754
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/88310848
has comment: http://stackoverflow.com/comment/88310622
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88310429
has comment: http://stackoverflow.com/comment/88310614
has title: Spaces in middle of each row in file csv
score: 1
tagged with: file
upvote count: 1
has comment: http://stackoverflow.com/comment/88313248
type: Question
has comment: http://stackoverflow.com/comment/88313050
has answer: http://stackoverflow.com/a/50650052
has comment: http://stackoverflow.com/comment/88310367
has comment: http://stackoverflow.com/comment/88310623
has body: I have a problem with me file csv. It's saving with spaces in middle of each row. I don't know why. How do I solve this problem? I'm asking because I don't find any answer and solutions to this. Here is the code: import csv import random def dict_ID_aeropuertos(): with open('AeropuertosArg.csv') as archivo_csv: leer = csv.reader(archivo_csv) dic_ID = {} for linea in leer: dic_ID.setdefault(linea[0],linea[1]) archivo_csv.close() return dic_ID def ruteoAleatorio(): dic_ID = dict_ID_aeropuertos() lista_ID = list(dic_ID.keys()) cont = 0 lista_rutas = [] while (cont &lt; 50): r1 = random.choice(lista_ID) r2 = random.choice(lista_ID) if (r1 != r2): t = (r1,r2) if (t not in lista_rutas): lista_rutas.append(t) cont += 1 with open('rutasAeropuertos.csv', 'w') as archivo_rutas: escribir = csv.writer(archivo_rutas) escribir.writerows(lista_rutas) archivo_rutas.close() ruteoAleatorio() Here is the file csv AeropuertosArg.cvs: 1,Aeroparque Jorge Newbery,Ciudad Autonoma de Buenos Aires,Ciudad Autonoma de Buenos Aires,-34.55803,-58.417009 2,Aeropuerto Internacional Ministro Pistarini,Ezeiza,Buenos Aires,-34.815004,-58.5348284 3,Aeropuerto Internacional Ingeniero Ambrosio Taravella,Cordoba,Cordoba,-31.315437,-64.21232 4,Aeropuerto Internacional Gobernador Francisco Gabrielli,Ciudad de Mendoza,Mendoza,-32.827864,-68.79849 5,Aeropuerto Internacional Teniente Luis Candelaria,San Carlos de Bariloche,Rio Negro,-41.146714,-71.16203 6,Aeropuerto Internacional de Salta Martin Miguel de Guemes,Ciudad de Salta,Salta,-24.84423,-65.478412 7,Aeropuerto Internacional de Puerto Iguazu,Puerto Iguazu,Misiones,-25.731778,-54.476181 8,Aeropuerto Internacional Presidente Peron,Ciudad de Neuquen,Neuquen,-38.952137,-68.140484 9,Aeropuerto Internacional Malvinas Argentinas,Ushuaia,Tierra del Fuego,-54.842237,-68.309701 10,Aeropuerto Internacional Rosario Islas Malvinas,Rosario,Santa Fe,-32.916887,-60.780391 11,Aeropuerto Internacional Comandante Armando Tola,El Calafate,Santa Cruz,-50.283977,-72.053641 1…
accepted answer: http://stackoverflow.com/a/50650052
has comment: http://stackoverflow.com/comment/88310644
has comment: http://stackoverflow.com/comment/88312132
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88310789
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88310544

http://stackoverflow.com/q/50651509
downvote count: 0
tagged with: django-rest-framework
has title: I want to get the url of a ForeignKey in Django Rest Framework
answer count: 1
has body: I have a HyperlinkedModelSerializer of a model with a ForeignKey, and I want to return the hyperlink to the instance referenced in that field, but I get the whole object nested in the json. These are my models: class Hotel(models.Model): ONE_STAR = '*' TWO_STARS = '**' THREE_STARS = '***' FOUR_STARS = '****' FIVE_STARS = '****' GRAND_TOURISM = 'GRAND_TOURISM' NA = 'NA' SPECIAL = 'SPECIAL' ECO = 'ECO' BOUTIQUE = 'BOUTIQUE' HOTEL_CATEGORY_CHOICES = ( (ONE_STAR, _('*')), (TWO_STARS, _('**')), (THREE_STARS, _('***')), (FOUR_STARS, _('****')), (FIVE_STARS, _('*****')), (GRAND_TOURISM, _('Grand Tourism')), (NA, _('NA')), (SPECIAL, _('Special')), (ECO, _('Eco-Hotel')), (BOUTIQUE, _('Boutique-Hotel')) ) company = models.OneToOneField(Company, on_delete=models.CASCADE, primary_key=True, verbose_name=_('Company')) code = models.CharField(max_length=10, verbose_name=_('Code')) city = models.ForeignKey(City, on_delete=models.PROTECT, related_name='hotels', verbose_name=_('City')) category = models.CharField(max_length=20, choices=HOTEL_CATEGORY_CHOICES, verbose_name=_('Category')) capacity = models.IntegerField(verbose_name=_('Capacity')) position = models.DecimalField(max_digits=11, decimal_places=2, default=0.00, verbose_name=_('Position')) in_pickup = models.BooleanField(default=False, verbose_name=_('In pickup?')) is_active = models.BooleanField(default=True, verbose_name=_('Is active?')) class Meta: verbose_name = _('Hotel') verbose_name_plural = _('Hotels') def __str__(self): return self.company.name class Company(models.Model): name = models.CharField(max_length=40, verbose_name=_('Name')) legal_name = models.CharField(max_length=100, null=True, blank=True, verbose_name=_('Legal name')) tax_id = models.CharField(max_length=12, null=True, blank=True, verbose_name=_('Tax ID')) url = models.URLField(null=True, blank=True, verbose_name=_('URL')) address = models.TextField(max_length=400, null=True, blank=True, verbose_name=_('Address')) class Meta: verbose_name = _('Company'…
favorite count: 0
has answer: http://stackoverflow.com/a/50651843
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/50651843
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/q/50590385
answer count: 1
has answer: http://stackoverflow.com/a/50590491
score: 0
tagged with: tkinter
has title: How to change a specific tag in python with tkinter
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88190567
type: Question
has body: i really can't get my head around something. The thing is that i'm working on a canvas with multiple shapes on it, like circles or rectangles. I want to modify a specific tag and i couldn't find anything useful on this subject. self.entry=workspace.create_rectangle(10,10,40,40, fill = "red",tag = "false" this is how i create my rectangle inside a class and what i want to do is modify that specific tag from "false" to "true"

http://stackoverflow.com/q/50690173
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50690264
upvote count: 1
tagged with: python
tagged with: regex
answer count: 1
has comment: http://stackoverflow.com/comment/88390164
has comment: http://stackoverflow.com/comment/88390124
has answer: http://stackoverflow.com/a/50690264
has body: I would like to search for strings that match a pattern in a text file and export only the matched strings k='' regex = re.compile(r'[a-zA-Z]{2}\d{8}') with open(file, 'r') as f: for line in f: line = line.replace(',', '') line = line.replace('.', '') k = regex.findall(line) #k.append(line) if not k=='': position=True else: position=False if position==True: print(k) Somehow my code doesn't work, it always returns the following output: [] [] [] [] [] [] [] ['AI13933231'] [] [] [] [] [] I want the output to contain only the matched strings. Thank you!
has title: Python search for patterns in all lines, export only lines with results
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/comment/88207552
comment on: http://stackoverflow.com/q/50598995
score: 0
type: Comment
type: QuestionComment
has text: Please note that using wildcard imports in Python is discouraged by [PEP 8](https://www.python.org/dev/peps/pep-0008/#imports) for added a lot of confusion when debugging and because they might have side-effects.

http://stackoverflow.com/q/50665515
tagged with: python
tagged with: selenium-chromedriver
has body: how to measure the time taken by the reports to display data embedded in an iframe of webpage? I have used time.sleep() function earlier. but i have to record the report loading time. browser.get('https://public.tableau.com/profile/ifpri.td7290#!/vizhome/2014GHI/2014GHI') browser.get('https://public.tableau.com/en-us/s/gallery/books-made-movies?gallery=votd')
linked to: http://stackoverflow.com/q/26566799
tagged with: selenium
type: Question
upvote count: 0
score: -2
has answer: http://stackoverflow.com/a/50665639
answer count: 2
duplicate of: http://stackoverflow.com/q/26566799
has answer: http://stackoverflow.com/a/50665542
favorite count: 0
has comment: http://stackoverflow.com/comment/88341196
has title: measure the time taken by the reports embedded in a webpage using python selenium
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/comment/88325354
comment on: http://stackoverflow.com/q/50657642
has text: As an adition to @chris response, when comparing to the size of the array, you can use `while item < len(array_name)`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50699366
has body: You can easily using the numpy ndarray with tf tensor simultaneously, you can define operations such as combine or add the two type of data. But the error you got, is just because you need to understand that, when you try to do the MatMul operation in tf, the two input data a and b must has the same type, as you can see, synaptic_weights = 2 * random.random((3, 1)) - 1 you can get a weights variable with type np.float64, because np.random.random((,)) return a float type (you can run synaptic_weights.dtype to see the true type). But, you also write that, output = 1 / (1 + exp(-(tf.tensordot(training_set_inputs, synaptic_weights,1)))) when you try to run the tf.tensordot operation, the input a is training_set_inputs with a type of int32_ref or int32, but input b is synaptic_weights with a type of float64 as default, that's why you get the error. To solve this error, you can define the tf variable with the float type at the beginning.
accepted answer of: http://stackoverflow.com/q/50697171
answers question: http://stackoverflow.com/q/50697171
has comment: http://stackoverflow.com/comment/88410185
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88411314
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/88411608

http://stackoverflow.com/a/50579631
has body: x = eval('lambda: print(y)',{},{'y':2}) is not equal to this line x = eval('lambda: print(y)', {'y': 2},{}) in first part change params order and it should work
score: -1
answers question: http://stackoverflow.com/q/50579541
type: Answer
downvote count: 1
upvote count: 0

append
tags question: http://stackoverflow.com/q/50554405
tag name: append
tags question: http://stackoverflow.com/q/50650850
tags question: http://stackoverflow.com/q/50555529
tags question: http://stackoverflow.com/q/50688943
tags question: http://stackoverflow.com/q/50662613
type: Tag

http://stackoverflow.com/q/50587458
type: AnsweredQuestion
has body: I've made a simple registration form using tkinter and mongoengine.But due to some reason, the value grabbed from tkinter entry boxes are stored as null or empty in mongodb.I guess the problem is that the variable is not able to grab the value entered in the tkinter entry box, but I am not able to find a solution to this problem as the code looks syntactically correct. from tkinter import * import tkinter.messagebox from mongoengine import * connect('demo') class Registration(Document): username = StringField(required=True,unique=True) password = StringField(required=True) def register(): if len(Registration.objects(username=name)) == 1: tkinter.messagebox.showinfo("Oops!", "Username already taken") else: entry = Registration( username=name, password=pwd ) entry.save() tkinter.messagebox.showinfo("Notice", "Registered Successfully !") # GUI root = Tk() root.title("Registration Demo") frame = Frame(root,width=500,height=500) frame.pack() label1 = Label(frame,text="username") label2 = Label(frame,text="password") entry1 = Entry(frame) entry2 = Entry(frame) name = entry1.get() pwd = entry2.get() button = Button(frame,text="Register",command=register) label1.grid(row=0,column=0,sticky=E) label2.grid(row=1,column=0,sticky=E) entry1.grid(row=0,column=1) entry2.grid(row=1,column=1) button.grid(columnspan=2) root.mainloop() And here's the mongodb table view : Mongodb Output As you can see in the output, the id is created but the username and password fields are blank, although the user had typed an input.
has comment: http://stackoverflow.com/comment/88184339
tagged with: mongoengine
type: Question
tagged with: mongodb
answer count: 1
accepted answer: http://stackoverflow.com/a/50587682
score: 0
has answer: http://stackoverflow.com/a/50587682
tagged with: tkinter
has title: Tkinter entry box values stored as null in mongodb
tagged with: python
has comment: http://stackoverflow.com/comment/88184482
has comment: http://stackoverflow.com/comment/88184975

http://stackoverflow.com/comment/88336817
type: AnswerComment
type: Comment
has text: I think I installed it through `apt-get install` command. I am using ubuntu.
comment on: http://stackoverflow.com/a/50663367
score: 0

http://stackoverflow.com/q/50601979
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88227813
has comment: http://stackoverflow.com/comment/88213789
score: 2
has comment: http://stackoverflow.com/comment/88228203
has comment: http://stackoverflow.com/comment/88248231
has body: I am trying to read outlook *.msg using python and Pandas. I got the body of the emails using a module called 'ExtractMsg'. The emails contain a table which is very complex since there are hard new lines ('\r\n') even within some cells. This makes the converting to Pandas very unpredictable. I am wondering how I could reproduce the same tables in Pandas. Thanks very much! How an email look like is attached: email screenshot my code is here: import ExtractMsg email = ExtractMsg.Message(file) email_body = email.body The the email body looks like: ' \r\nA\r\nB\r\nC\r\n1\r\n1a\r\n1b\r\nss\r\n1c\r\n2\r\n2a\r\n2b\r\n2c\r\n3\r\n3a\r\n3b\r\n3c\r\nxxx\r\n4\r\n4a\r\n4b\r\n4c\r\n5\r\n5a\r\nttt\r\n5b\r\n5c\r\n \r\n'
type: Question
tagged with: html-table
tagged with: outlook
has comment: http://stackoverflow.com/comment/88221232
downvote count: 0
has title: parsing tables in outlook *.msg emails by python
favorite count: 0
has comment: http://stackoverflow.com/comment/88234853
has comment: http://stackoverflow.com/comment/88222886
has comment: http://stackoverflow.com/comment/88215406
tagged with: pandas
tagged with: html-email
tagged with: python
has comment: http://stackoverflow.com/comment/88220113
answer count: 0

http://stackoverflow.com/q/50569663
tagged with: google-maps
type: UnansweredQuestion
score: 2
tagged with: shapely
answer count: 0
downvote count: 0
favorite count: 0
has title: Assertion failed on google maps polyline extraction and buffer
has body: I am working on a django project where the user inputs their start and end location in the form a string. My application must connect to the google direction service API, take the string and convert it to coords. Then from the coordinates create a polyline, and add a 1km buffer. Which will be saved in a postgis database as a polygon. from django.db import models from django.contrib.gis.db import models from django.forms import ModelForm from django_google_maps import fields as map_fields import shapely.geometry import googlemaps from googlemaps import Client # Create your models here. class Route(models.Model): startPoint_address = PointField() startPoint_geolocation = Pointfield() endPoint_address = PointField() endPoint_geolocation = Pointfield() # endPoint = models.PointField() # deviationDistance = models.IntegerField(default=20) # routeName = models.CharField(max_length=50) # https://github.com/geodav-tech/decode-google-maps-polyline def decode_polyline(polyline_str): '''Pass a Google Maps encoded polyline string; returns list of lat/lon pairs''' index, lat, lng = 0, 0, 0 coordinates = [] changes = {'latitude': 0, 'longitude': 0} # Coordinates have variable length when encoded, so just keep # track of whether we've hit the end of the string. In each # while loop iteration, a single coordinate is decoded. while index &lt; len(polyline_str): # Gather lat/lon changes, store them in a dictionary to apply them later for unit in ['latitude', 'longitude']: shift, result = 0, 0 while True: byte = ord(polyline_str[index]) - 63 index+=1 result |= (byte &amp; 0x1f) &lt;&lt; shift shift += 5 if not byte &gt;= 0x20: break if (result &amp; 1): changes[unit] = ~(result &gt;&gt; 1) else: changes[unit] = (result &gt;&gt; 1) lat += changes['latitude'] lng += changes['longitude'] coordinates.append((lat / 100000.0, lng / 100000.0)) return coordinates gmaps = googlemaps.Client(key='AIzaSyCetShZ10WQVBVPaIu9pdPEktRVQq78TF4') google_directions = gmaps.directions("Stellenbosch", "Cape…
type: Question
tagged with: django
tagged with: python
upvote count: 2
has comment: http://stackoverflow.com/comment/88856609

http://stackoverflow.com/comment/88393352
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50691903
score: 0
has text: try `polls/` without `index.html`

http://stackoverflow.com/a/50549966
has body: Here is a random example: import numpy as np np.random.seed(123456) array = np.array(np.random.randn(12)) print((array &lt; 1) &amp; (array &gt; 0)) And numpy you have to put the conditions in parenthesis, and then use the &amp; operator for an and condition. For an or condition you use the | operator and then follow the same format. This will get you an array of Boolean values.
accepted answer of: http://stackoverflow.com/q/50549910
answers question: http://stackoverflow.com/q/50549910
score: 4
has comment: http://stackoverflow.com/comment/88110945
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88110909
type: Answer

http://stackoverflow.com/q/50626630
score: 1
has comment: http://stackoverflow.com/comment/88263389
tagged with: recurrent-neural-network
type: Question
has title: Stacking convolutional network and recurrent layer
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50641173
tagged with: keras
tagged with: lstm
favorite count: 0
has comment: http://stackoverflow.com/comment/88263465
accepted answer: http://stackoverflow.com/a/50641173
upvote count: 1
tagged with: python
type: AnsweredQuestion
has body: I'm working on a classifier for video sequences. It should take several video frames on input and output a label, either 0 or 1. So, it is a many-to-one network. I already have a classifier for single frames. This classifier makes several convolutions with Conv2D, then applies GlobalAveragePooling2D. This results in 1D vector of length 64. Then original per-frame classifier has a Dence layer with softmax activation. Now I would like to extend this classifier to work with sequences. Ideally, sequences should be of varying length, but for now I fix the length to 4. To extend my classifier, I'm going to replace Dense with an LSTM layer with 1 unit. So, my goal is to have the LSTM layer to take several 1D vectors of length 64, one by one, and output a label. Schematically, what I have now: input(99, 99, 3) - [convolutions] - features(1, 64) - [Dense] - [softmax] - label(1, 2) Desired architecture: 4x { input(99, 99, 3) - [convolutions] - features(1, 64) } - [LSTM] - label(1, 2) I cannot figure out, how to do it with Keras. Here is my code for convolutions from keras.layers import Conv2D, BatchNormalization, GlobalAveragePooling2D, \ LSTM, TimeDistributed IMAGE_WIDTH=99 IMAGE_HEIGHT=99 IMAGE_CHANNELS=3 convolutional_layers = Sequential([ Conv2D(input_shape=(IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_CHANNELS), filters=6, kernel_size=(3, 3), strides=(2, 2), activation='relu', name='conv1'), BatchNormalization(), Conv2D(filters=64, kernel_size=(1, 1), strides=(1, 1), activation='relu', name='conv5_pixel'), BatchNormalization(), GlobalAveragePooling2D(name='avg_pool6'), ]) Here is the summary: In [24]: convolutional_layers.summary() _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv1 (Conv2D) (None, 49, 49, 6) 168 _________________________________________________________________ batch_normalization_3 (Batch (None, 49, 49, 6) 24 ______________________________________…
has comment: http://stackoverflow.com/comment/88263596

http://stackoverflow.com/comment/88642394
score: 0
type: Comment
type: QuestionComment
has text: I must be surely missing something. but set(a) ?
comment on: http://stackoverflow.com/q/50592576

http://stackoverflow.com/comment/88390064
type: Comment
comment on: http://stackoverflow.com/q/50679177
type: QuestionComment
score: 1
has text: @Kiran Please take a look at my answer because i include what you want in the image the average

http://stackoverflow.com/comment/88331223
comment on: http://stackoverflow.com/q/50660042
score: 0
has text: Thanks. The price does not correspond to the dates. It is calculated as ( percentage * ema + ema ) I am a trader and need to know the price that corresponds to the percentage; that is why I have plotted the line chart below.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50615550
has answer: http://stackoverflow.com/a/50615580
tagged with: python
type: AnsweredQuestion
has title: The abstract concept name of symbol `%`
type: Question
upvote count: 4
answer count: 2
accepted answer: http://stackoverflow.com/a/50615580
downvote count: 0
has body: This might be frivolous, but what's the symbol % as an abstract concept name? For example, \ is called "escape symbol" in addition to "backslash", while % is just called "percent symbol", In [45]: content = "percent and format me" In [46]: print("test %s" % content) test percent and format me Is it named "formatted symbol"?
favorite count: 0
possible better answer: http://stackoverflow.com/a/50615571
has answer: http://stackoverflow.com/a/50615571
score: 4

http://stackoverflow.com/comment/88327586
score: 0
type: Comment
has text: Are you using heroku?
comment on: http://stackoverflow.com/a/50658318
type: AnswerComment

http://stackoverflow.com/comment/88210212
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50599850
has text: @Chris_Rands The docs say "The following Python code helps explain what tee does (although the actual implementation is more complex and uses only a single underlying FIFO queue)." If you look at `teedataobject_getitem` in the CPython code, you see that it only grabs new data `PyIter_Next` if the lead iterator has reached that point. It then stores that until all `tee`s have used the value.
score: 0

http://stackoverflow.com/a/50608554
answers question: http://stackoverflow.com/q/50595288
score: 0
type: Answer
has body: You are trying to add a day to the departure date if the departure is before the arrival. To do this you would need to use Python's datetime library. Start by combining the date and time components into a single string and then converting the string into a datetime object. You can then do a simple comparison to determine if one date is before another. If this is the case, use timedelta to a day to the departure date. Next convert this back into date string and update the third column (i.e. row[2]). The updated data can then be written back to a seperate CSV file: from datetime import datetime, timedelta import csv one_day = timedelta(days=1) with open('times.csv', newline='') as f_input, open('times_updated.csv', 'w', newline='') as f_output: csv_input = csv.reader(f_input) csv_output = csv.writer(f_output) header = next(csv_input) csv_output.writerow(header) for row in csv_input: arrival_time = datetime.strptime('{} {}'.format(row[0], row[1]), '%Y/%m/%d %H:%M') departure_time = datetime.strptime('{} {}'.format(row[2], row[3]), '%Y/%m/%d %H:%M') if departure_time &lt; arrival_time: departure_time += one_day row[2] = departure_time.strftime('%Y/%m/%d') csv_output.writerow(row) This would give you an output CSV file containing: #Arrival_Date#,#Arrival_Time#,#Departure_Date#,#Departure_Time# 2017/01/01,23:30,2017/01/02,00:30 2017/02/01,23:30,2017/02/01,23:40 2017/03/01,15:45,2017/03/01,17:30 2017/04/10,23:50,2017/04/11,00:30 Note, this assumes you are using Python 3.x and that your CSV files are formatted as normal CSV files, i.e. aaa,bbb,ccc,ddd

http://stackoverflow.com/q/50548012
type: UnansweredQuestion
has title: Delete row in tkinter treeview with identified "cell"
has comment: http://stackoverflow.com/comment/88120205
has comment: http://stackoverflow.com/comment/88118092
has comment: http://stackoverflow.com/comment/88118206
has comment: http://stackoverflow.com/comment/88114198
has comment: http://stackoverflow.com/comment/88119787
has comment: http://stackoverflow.com/comment/88121041
type: Question
score: 0
has comment: http://stackoverflow.com/comment/88118397
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88118512
has comment: http://stackoverflow.com/comment/88120950
has answer: http://stackoverflow.com/a/50556344
has body: I made a treeview with tkitner and I made it si that you can identify a "cell" inside the treeview with a button click, I used tree.identify_region(event.x, event.y) == ' cell'. The "cell" is identified with one button click (i have used bind function &lt;Button-1&gt;). I want to make a function that will delete the row (selected row), but the function does not work. It does not show any error. I think that the problem is because even if the row is selected, its also a "cell" thats selected. I posted a full code (even if its long) because I think that you need to see what I have done to make this This is the code: from tkinter import * from tkinter import ttk import math from tkinter import messagebox def edit(event): def double(event): # funkcija koja kreira celiju kada se klikne dupli klik try: if tree.identify_region(event.x, event.y) == 'cell': # the user clicked on a cell def ok(event): """Change item value.""" tree.set(item, column, entry.get()) entry.destroy() column = tree.identify_column(event.x) # identify column item = tree.identify_row(event.y) # identify item x, y, width, height = tree.bbox(item, column) value = tree.set(item, column) elif tree.identify_region(event.x, event.y) == 'heading': # the user clicked on a heading def ok(event): """Change heading text.""" tree.heading(column, text=entry.get()) entry.destroy() column = tree.identify_column(event.x) # identify column # tree.bbox work only with items so we have to get the bbox of the heading differently x, y, width, _ = tree.bbox(tree.get_children('')[0], column) # get x and width (same as the one of any cell in the column) # get vertical coordinates (y1, y2) y2 = y # get bottom coordinate while tree.identify_region(event.x, y2) != 'heading': y2 -= 1 # get top coordinate y1 = y2 while tree.identify_region(event.x, y1) == 'heading': y1 -= 1 height = y2 - y1 y = y1 value = tree.heading(column, 'text') elif tree.identify_region(event.x, event.y) == 'nothing': column = tree.identify_column(event.x) # …
tagged with: tkinter

binary-tree
tag name: binary-tree
type: Tag
tags question: http://stackoverflow.com/q/50657451
tags question: http://stackoverflow.com/q/50691220

http://stackoverflow.com/q/50656471
downvote count: 0
tagged with: scikit-learn
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88323323
has answer: http://stackoverflow.com/a/50656815
type: Question
upvote count: 5
has title: estimator should be an estimator implementing 'fit' method
has body: when I try to run the code in python I encounter this problem , how can I solve it? ---> 95 validation(sm_classifier, x_test_normal_s, y_n2_test, y_test, classes_names, ' NSLKDD SAE-SAE(test)') 96 #if __name__ == "__main__":main() ## with if 97 <ipython-input-23-95022ce9a680> in validation(classifier, data, y_data, y_target, class_names, title) 52 print ("No accuracy to be computed") 53 else: ---> 54 accuracy = model_selection.cross_val_score(classifier,x, y_target, scoring='accuracy') 55 print("Accuracy: "+ str(accuracy)) 56 precision = model_selection.cross_val_score(self.classifier, x, target, scoring='precision') C:\ProgramData\Anaconda3\lib\site-packages\sklearn\model_selection\_validation.py in cross_val_score(estimator, X, y, groups, scoring, cv, n_jobs, verbose, fit_params, pre_dispatch) 130 cv = check_cv(cv, y, classifier=is_classifier(estimator)) 131 cv_iter = list(cv.split(X, y, groups)) --> 132 scorer = check_scoring(estimator, scoring=scoring) 133 # We clone the estimator to make sure that all the folds are 134 # independent, and that it is pickle-able. C:\ProgramData\Anaconda3\lib\site-packages\sklearn\metrics\scorer.py in check_scoring(estimator, scoring, allow_none) 248 if not hasattr(estimator, 'fit'): 249 raise TypeError("estimator should be an estimator implementing " --> 250 "'fit' method, %r was passed" % estimator) 251 if isinstance(scoring, six.string_types): 252 return get_scorer(scoring) TypeError: estimator should be an estimator implementing 'fit' method, <__main__.Softmax object at 0x00000000048D1F98> was passed .............................. import numpy as np import math import random from operator import itemgetter class Softmax: #from IPython.core.debugger import Tracer; Tracer()() def __init__(self, batch_size=50, epochs=1000, learning_rate=1e-2, reg_strength=1e-5, weight_update='adam'): self.W = None self.batch_size = batch_size self.epochs = epochs self.learning_rate = learning_rate self.reg_strength = reg_strength self.weight_upda…
has comment: http://stackoverflow.com/comment/88322990
answer count: 2
score: 5
has answer: http://stackoverflow.com/a/75909942

http://stackoverflow.com/comment/88234573
type: QuestionComment
has text: Looks like the [0] was the issue. I wanted all the values, an accidentally took a single value. Thanks for the solution. @chrisz your answer worked, If you post it as a solution, I'll accept it.
score: 0
comment on: http://stackoverflow.com/q/50610258
type: Comment

http://stackoverflow.com/comment/88831068
comment on: http://stackoverflow.com/q/50674923
score: 0
type: Comment
type: QuestionComment
has text: I added more info to the code in the question. that is where I get None value as return every now and then. but since I have `try/except` statement the code keep running.

http://stackoverflow.com/comment/123391325
has text: I have added a new question here, can you help on that? https://stackoverflow.com/questions/69754542/how-to-run-python-script-from-c-sharp-code-by-using-command?noredirect=1#comment123367833_69754542
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/69776097

http://stackoverflow.com/comment/88203301
type: Comment
comment on: http://stackoverflow.com/q/50596286
score: 0
has text: @KlausD. See my edits
type: QuestionComment

http://stackoverflow.com/comment/88099414
score: 0
has text: Can you post the relevant migration file.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50544151

http://stackoverflow.com/comment/88372799
has text: I thought, using something like `input_data = Input(shape=(num_neurons1,)); encoded = Dense(encoding_dim1, activation='relu', name='encoder1')(input_data); encoded1 = Dense(encoding_dim2, activation='relu', name='encoder2')(encoded); encoder = Model(inputs=input_data, outputs=encoded1); encoder.predict(numpyInputs)` would give reduced features. Please let me know where I am going wrong. But what would I use as x_test while testing the model - mymlp.predict(???,y_test) [semicolon for newline]
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50658818
type: Comment

http://stackoverflow.com/q/50657503
tagged with: pandas
has answer: http://stackoverflow.com/a/50657564
favorite count: 0
has title: merge 2 pandas dataframe in 1 with data priority
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50657564
score: 1
upvote count: 1
type: Question
tagged with: combinations
possible better answer: http://stackoverflow.com/a/50657580
answer count: 2
has body: I have 2 Dataframes: A = [ A B C name1 1 2 3 name2 1 2 3 name3 1 2 3 ] B = [ A B C D name1 11 12 13 12 name2 12 22 23 23 name3 31 32 33 14 name4 41 42 43 44 ] I would like to add in A columns and rows that I don't have in A but have in B, without changing existing data in A As a result, A must be: A = [ A B C D name1 1 2 3 12 name2 1 2 3 23 name3 1 2 3 14 name4 41 42 43 44 ] How I should do it?
has answer: http://stackoverflow.com/a/50657580
downvote count: 0
tagged with: dataframe

http://stackoverflow.com/q/50574359
upvote count: 0
has comment: http://stackoverflow.com/comment/88158458
has comment: http://stackoverflow.com/comment/88158371
score: -2
tagged with: discord
has answer: http://stackoverflow.com/a/50574545
has body: What I want is for the bot to say Snacktoshis: 5, but it won't print the variable in the chat. Here is my code: from discord import * from discord.ext import * from discord.ext.commands import Bot from discord.ext.commands import * import random import asyncio from discord import Game from discord.ext.commands import Bot import aiohttp import discord import requests import time BOT_PREFIX = ("?", "!") client = Bot(command_prefix=BOT_PREFIX) TOKEN ="3812236138921603126360103210983inserttoken21831382ufsfuadha" @client.command() async def bal(): snack = 0 await client.say("Snacktoshis:",snack) client.run(TOKEN) My error message is: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/discord/ext/commands/bot.py", line 846, in process_commands yield from command.invoke(ctx) File "/usr/local/lib/python3.6/site-packages/discord/ext/commands/core.py", line 374, in invoke yield from injected(*ctx.args, **ctx.kwargs) File "/usr/local/lib/python3.6/site-packages/discord/ext/commands/core.py", line 54, in wrapped raise CommandInvokeError(e) from e discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: send_message() takes from 2 to 3 positional arguments but 4 were given I know I have alot of unused modules.
favorite count: 0
downvote count: 2
tagged with: python
has title: Discord.py bot wont print a SIMPLE variable in the chat
type: AnsweredQuestion
tagged with: bots
has answer: http://stackoverflow.com/a/50574590
accepted answer: http://stackoverflow.com/a/50574545
has comment: http://stackoverflow.com/comment/88158432
type: Question
possible better answer: http://stackoverflow.com/a/50574590
answer count: 2
tagged with: discord.py
has comment: http://stackoverflow.com/comment/88158308

http://stackoverflow.com/comment/88182188
type: QuestionComment
type: Comment
score: 1
has text: @Sayse it's boolean algebra, I don't want to feed the result back into a program https://en.wikipedia.org/wiki/Boolean_algebra
comment on: http://stackoverflow.com/q/50586329

http://stackoverflow.com/q/50595897
type: Question
tagged with: oop
tagged with: class
has comment: http://stackoverflow.com/comment/88200954
has comment: http://stackoverflow.com/comment/88201254
score: 0
has title: explanation of dot notation on class.property
has body: I'm trying to understand deeply why use a same name of variable in a class property? The code below: class Cat: def __init__ (self, color, legs) self.color = color self.legs = legs felix = Cat("black, 4) I can write it as this: class Cat: def __init__ (self, color, legs) self.classColor = color self.classLegs = legs felix = Cat("black", 4) or this: class Cat: def __init__ (self, catColor, catLegs) self.color = catColor self.legs = catLegs felix = Cat("black", 4) I see the first one as the conventional way of declaring properties of class and variables. Found some information on internet they write it that way as to avoid confusion but I'm confused why is not having an error?
type: UnansweredQuestion
tagged with: python
tagged with: properties
answer count: 0
has comment: http://stackoverflow.com/comment/88200940

http://stackoverflow.com/q/50601338
has comment: http://stackoverflow.com/comment/88211855
duplicate of: http://stackoverflow.com/q/42588077
score: 0
tagged with: apache-spark
tagged with: python
has body: I'm really new to spark and have little trouble Suppose I have this : 'a' | 'b' 0 | 5416 1 | 5278 2 | 2 3 | 568 0 | 416 1 | 216 2 | 56 3 | 56 and I want a third column with a kind of index that group by de series of 'a' like this : 'a' | 'b' | 'Index' 0 | 5416 | 1 1 | 5278 | 1 2 | 2 | 1 3 | 568 | 1 0 | 416 | 2 1 | 216 | 2 2 | 56 | 2 3 | 56 | 2 How can I do thi ? with Window() ? Thanks !
answer count: 0
type: UnansweredQuestion
has title: PySpark : Add column with goup index
tagged with: pyspark
has comment: http://stackoverflow.com/comment/88211811
type: Question
linked to: http://stackoverflow.com/q/42588077

http://stackoverflow.com/comment/88170321
score: 0
has text: @Shift 'N Tab i added more information.. i don't have idea
type: Comment
comment on: http://stackoverflow.com/q/50577697
type: QuestionComment

http://stackoverflow.com/q/50626959
tagged with: django
has title: Django Rest Framework - How to save using id and retrieve other columns as well?
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50627092
type: AnsweredQuestion
has body: This question is a continuation of other question from this link here(Django Rest Framework how to save a model with Related Field based on ID) My situation got solved when I used PrimaryKeyRelatedField() to store data using id on a POST request. This, in turn, created another issue. I was using the same API's GET option to list all the columns from the related (Foreign Key referred)model, after using PrimaryKeyRelatedField() the other columns got disappeared and ID is only showing up. Need help on this. To be more clear need ID column of the referred table during POST call and need other columns of the model/table during GET call. PS: I have used serializers.ModelSerializer method
score: 1
tagged with: django-models
linked to: http://stackoverflow.com/q/27028832
type: Question
downvote count: 0
tagged with: django-rest-framework
favorite count: 0
has answer: http://stackoverflow.com/a/50627092
answer count: 1

http://stackoverflow.com/comment/88200870
has text: You could place everything into a `"""...triple-double-quoted multiline string ..."""`, and then don't use the string. If you are using triple-double-quoted strings already, then use a `'''...triple-single-quoted multiline string...'''`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50595827

http://stackoverflow.com/q/50628805
has comment: http://stackoverflow.com/comment/88268217
has comment: http://stackoverflow.com/comment/88268085
has comment: http://stackoverflow.com/comment/88269049
tagged with: python-requests
type: Question
has comment: http://stackoverflow.com/comment/88268184
accepted answer: http://stackoverflow.com/a/50630416
has body: I want to webscrape the IAA Consensus price on https://www.settrade.com/AnalystConsensus/C04_10_stock_saa_p1.jsp?txtSymbol=PTT&ssoPageId=9&selectPage=10 In Google chrome inspect elements, I can use through beautifulsoup to get the data. But from the print page.content I get ... ... Where it should be 62.00 Here's my code import requests from bs4 import BeautifulSoup def findPrice(Quote): link = "http://www.settrade.com/AnalystConsensus/C04_10_stock_saa_p1.jsp?txtSymbol="+Quote+"&ssoPageId=9&selectPage=10" page = requests.get(link) soup = BeautifulSoup(page.content,'html.parser') print page.content target = soup.findAll('h3') return target.string findPrice('PTT')
has comment: http://stackoverflow.com/comment/88267799
has comment: http://stackoverflow.com/comment/88268244
has comment: http://stackoverflow.com/comment/88268452
has comment: http://stackoverflow.com/comment/88268143
score: 0
has comment: http://stackoverflow.com/comment/88268160
answer count: 1
has comment: http://stackoverflow.com/comment/88269239
tagged with: beautifulsoup
linked to: http://stackoverflow.com/q/48874874
has answer: http://stackoverflow.com/a/50630416
has comment: http://stackoverflow.com/comment/88267919
tagged with: python
type: AnsweredQuestion
has title: Data missing on requests.get() Python 2
has comment: http://stackoverflow.com/comment/88268663

http://stackoverflow.com/comment/88138816
comment on: http://stackoverflow.com/a/50564297
type: AnswerComment
has text: Thank you so much, i realise now how stupid was my question.
score: 0
type: Comment

http://stackoverflow.com/comment/88218947
has text: It seems odd that you're passing the `BuildingAddress` class itself when creating a new `LayerMapping`. Shouldn't you be passing an instance of `BuildingAddress`? Can you post the `LayerMapping` code please?
score: 0
comment on: http://stackoverflow.com/q/50597101
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50575933
has comment: http://stackoverflow.com/comment/88161212
favorite count: 0
score: 0
tagged with: pandas
tagged with: datetime
has comment: http://stackoverflow.com/comment/88161296
has title: Pandas - Speeding up df.apply() - Calculating time difference
tagged with: time
accepted answer: http://stackoverflow.com/a/50625798
upvote count: 1
tagged with: python
downvote count: 1
tagged with: pytz
has body: I have working code for calculating the business hours between two dates using df.apply(). However given my df is ~40k rows it's extremely slow, is there a way I could speed this up by vectorising? Original code: import datetime import pytz import businesstimedelta import holidays as pyholidays workday = businesstimedelta.WorkDayRule( start_time=datetime.time(9), end_time=datetime.time(17), working_days=[0, 1, 2, 3, 4]) vic_holidays = pyholidays.AU(prov='VIC') holidays = businesstimedelta.HolidayRule(vic_holidays) businesshrs = businesstimedelta.Rules([workday, holidays]) def BusHrs(start, end): return businesshrs.difference(start,end).hours+float(businesshrs.difference(start,end).seconds)/float(3600) df['Diff Hrs'] = df.apply(lambda row: BusHrs(row['Updated Date'], row['Current Date']), axis=1) Gives: Index Created Date Updated Date Diff Hrs Current Date 10086 2016-11-04 16:00:00 2016-11-11 11:38:00 35.633333 2018-05-29 10:09:11.291391 10087 2016-11-04 16:03:00 2016-11-29 12:54:00 132.850000 2018-05-29 10:09:11.291391 10088 2016-11-04 16:05:00 2016-11-16 08:05:00 56.916667 2018-05-29 10:09:11.291391 10089 2016-11-04 16:17:00 2016-11-08 11:37:00 11.333333 2018-05-29 10:09:11.291391 10090 2016-11-04 16:20:00 2016-11-16 09:58:00 57.633333 2018-05-29 10:09:11.291391 10091 2016-11-04 16:32:00 2016-11-08 11:10:00 10.633333 2018-05-29 10:09:11.291391 I can see it crunching and looks like it could take 5+ hours to complete. Curiously, I have a hunch that it is calculating faster the closer the two dates are together. Ex. df['Time Since Last Update'] = df.apply(lambda row: BusHrs(row['Updated Date'], row['Current Date']), axis=1) is much faster than df['Time Since Last Update'] = df.apply(lambda row: BusHrs(row['Created Date'], row['Updated Date']), axis=1) Optimizing like this is a step above what I'm used to so any help is appreciated.
type: AnsweredQuestion
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/50625798

http://stackoverflow.com/q/50584059
answer count: 2
tagged with: pandas
has body: I have the following dataframe: df = pd.DataFrame({'date': ['31/12/2015','31/12/2016','31/12/2017','31/12/2018', '31/12/2019','31/12/2020','31/12/2015','31/12/2016', '31/12/2017','31/12/2018','31/12/2019','31/12/2020'], 'season': ['S1','S1','S1','S1','S1','S1','S2','S2','S2','S2','S2','S2'], 'total' : [1,0,0,0,0.022313421,0.053791041,0,0,0.307783314,0,0,0] }) df.date= pd.to_datetime(df.date) print(df) date season total 0 2015-12-31 S1 1.000000 1 2016-12-31 S1 0.000000 2 2017-12-31 S1 0.000000 3 2018-12-31 S1 0.000000 4 2019-12-31 S1 0.022313 5 2020-12-31 S1 0.053791 6 2015-12-31 S2 0.000000 7 2016-12-31 S2 0.000000 8 2017-12-31 S2 0.307783 9 2018-12-31 S2 0.000000 10 2019-12-31 S2 0.000000 11 2020-12-31 S2 0.000000 I would like to do several calculations for each row based on the value contained in the column 'total' to obtain a dataframe in the following format (example for the first row): date season total calculation id result 0 2015-12-31 S1 1.000000 1 x1 0 2015-12-31 S1 1.000000 2 x2 0 2015-12-31 S1 1.000000 3 x3 0 2015-12-31 S1 1.000000 4 x4 0 2015-12-31 S1 1.000000 5 x5 basically something like: for index, row in df.iterrows(): for i, a in enumerate(np.linspace(0,getattr(row,'total'),6)): assing the result of the calculation to the column result Any idea on how i could do that? For the sake of the example, the result column could be evaluated to a*5 in the loop. Thanks for your help, Pierre
tagged with: iteration
possible better answer: http://stackoverflow.com/a/50587020
has answer: http://stackoverflow.com/a/50587020
tagged with: python
has comment: http://stackoverflow.com/comment/88178511
type: AnsweredQuestion
has title: Pandas, multiple calculation per row of the dataframe
type: Question
has answer: http://stackoverflow.com/a/50586595
accepted answer: http://stackoverflow.com/a/50586595
has comment: http://stackoverflow.com/comment/88177909
tagged with: rows
score: 0

http://stackoverflow.com/q/50623430
tagged with: python-3.x
type: Question
accepted answer: http://stackoverflow.com/a/50623449
tagged with: python
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/50623499
tagged with: if-statement
possible better answer: http://stackoverflow.com/a/50623499
has answer: http://stackoverflow.com/a/50623449
has title: IndexError: single positional indexer is out-of-bounds and if condition
has body: I have a dataframe that looks like this: Repo Out[624]: 1 Instrument Term Code WTD Rate 2 GC_AUSTRIA_SUB_10YR T-N -0.49 3 GC_AUSTRIA_SUB_10YR O -0.467643 4 R_RAGB_1.15_10/18 S-N -0.520299 5 R_RAGB_4.35_03/19 S-N -0.497759 6 R_RAGB_4.35_03/19 T-N -0.5 7 R_RAGB_1.95_06/19 S-N -0.501478 8 R_RAGB_0.25_10/19 S-N -0.497765 I have an if condition which is dependent on the column "Instrument" if condition: return Repo.loc[(Repo['Instrument']=='GC_LCH_BELGIUM') &amp; (Repo['Term Code']=='T-N'),'WTD Rate'].iloc[0] The issue is that the Instrument name sometimes does not exist and get an error IndexError: single positional indexer is out-of-bounds How can I say in the "if condition" that if the instrument does exist (or if there is an error) reverts back to default value of say 10. I should point out that when Instrument does not exist there is no row in the dataframe. therefore code that looks something like "is empty" would not work
tagged with: pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50623630
downvote count: 0
score: 1
favorite count: 0
tagged with: series

http://stackoverflow.com/q/50669205
has answer: http://stackoverflow.com/a/50671798
accepted answer: http://stackoverflow.com/a/50671798
answer count: 1
has title: Python Ctypes function call Segmentation Fault when used on Unix systems
has comment: http://stackoverflow.com/comment/88348592
favorite count: 0
tagged with: x86
tagged with: assembly
tagged with: python
has comment: http://stackoverflow.com/comment/88348781
has comment: http://stackoverflow.com/comment/88348170
has comment: http://stackoverflow.com/comment/88352582
has comment: http://stackoverflow.com/comment/88352154
has comment: http://stackoverflow.com/comment/88352681
has comment: http://stackoverflow.com/comment/88348889
has comment: http://stackoverflow.com/comment/88352042
has comment: http://stackoverflow.com/comment/88353003
downvote count: 0
has comment: http://stackoverflow.com/comment/88348552
has comment: http://stackoverflow.com/comment/88352951
has body: Background: Writing a proof of concept that includes executing machine code it within the running python process. Wanting to make the functionality cross platforms, but problem arises when tested against unix systems. Almost exactly like this question: Python ctypes and function calls but the solution does not work this time. Problem: When executing the python script in VM 32bit Ubuntu server 12.04.5 LTS, the output says Segmentation fault (core dumped) Which means I am getting denied for accessing memory that I don't have permission for. This is strange b/c in the source code I also set cytpes.mprotect(allocated_space, space_size, 7) &lt;== 4 + 2 + 1 is for wrx permissions NOTE: Please do not try to execute the following machine code on a machine without having full consent from owner for testing purposes. Python Script: #!/usr/bin/env python import ctypes import os import sys # linux machine code buf += "\xbd\xfc\xa1\x5d\x63\xd9\xee\xd9\x74\x24\xf4\x5e\x31" buf += "\xc9\xb1\x1c\x31\x6e\x14\x03\x6e\x14\x83\xee\xfc\x1e" buf += "\x54\x37\x1e\x86\x0e\x7a\xe7\x8f\x31\x6b\xe8\xef\xb8" buf += "\x68\x8e\x6e\x59\x6e\xbf\xbd\x1e\x5e\xe4\xca\xfc\xf2" buf += "\x59\x67\x69\xf7\xd4\x66\xdd\x91\x2b\xe8\x4f\x34\xb0" buf += "\xbc\x05\xca\xd2\x3d\x8a\x5d\xab\xdc\x40\x6c\xf7\x74" buf += "\xf3\x28\xca\x08\x6c\x4b\x10\x1c\xca\x17\xc7\x4e\x84" buf += "\xa5\xf7\x7f\x08\xc0\xe7\x2e\xe0\x9d\xe9\xba\x66\xc6" buf += "\x24\xba\xb6\x15\x06\xdc\xf5\x5a\x37\x63\xb6\x3d\x31" buf += "\x32\xb2\x0c\xc1\x27\x0c\x82\x72\x44\xbc\x1b\xf5\x95" buf += "\x65\xac\xfc\xe4\x1a\x33\xe1" def main(buf): if os.name == 'posix': try: libc = ctypes.CDLL('libc.so.6') buf_ptr = ctypes.c_char_p(buf) size = len(buf) addr_freespace = ctypes.c_void_p(libc.valloc(size)) ctypes.memmove(addr_freespace, buf_ptr, size) libc.mprotect(addr_free_space, size, 1 | 2 | 4) # changed to 7 for all three access run = ctypes.cast(free_space, ctypes.CFUNCTYPE(ctypes.c_void_p)) run() sys.exit() except Exception as e: print "Error: " e els…
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88348519
has comment: http://stackoverflow.com/comment/88350130
has comment: http://stackoverflow.com/comment/88352435
tagged with: http://stackoverflow.com/tag/c
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/88350851
linked to: http://stackoverflow.com/q/275207
tagged with: ctypes
has comment: http://stackoverflow.com/comment/88350078
has comment: http://stackoverflow.com/comment/88348648

http://stackoverflow.com/comment/88166747
type: QuestionComment
comment on: http://stackoverflow.com/q/50578714
has text: @U8-Forward I have updated with more explanation.
score: 0
type: Comment

http://stackoverflow.com/q/50659966
answer count: 0
tagged with: stack
has comment: http://stackoverflow.com/comment/88330351
has comment: http://stackoverflow.com/comment/88330730
type: Question
has body: I ran into this problem in trying to solve a string candy crush problem. Here's MY version of the explanation of the problem: Given a string "DAABBBBABCC", return a string where 3 or more consecutive letters or characters are removed. Note that the once you remove a section of the string, any new combinations that make 3 or more consecutive letters should also subsequently be removed. Hence "DAABBBBABCC" when reduced becomes "DAAABCC" which is further reduced to "DBCC" [the returned string]. I approached this problem by maintaining a stack of letter dictionaries. If I saw letter 'a', I would add it to the stack as {'a': 1} and if the next letter was also 'a', I would increment this value otherwise I would push to the stack a dictionary of the new letter say {'b': 1}. Now in order to increment the count of the repeating character, I would need to check the count of the last letter dictionary added to the stack. What is the most efficient way of accessing the count in Python without knowing what the key is in this last dictionary that was pushed? For the purposes of explaining the question, here's an example. The stack was built after iterating over a string "hhaaa" &gt;&gt;&gt; stack [{'h': 2}, {'a': 3}] I have thought of 2 ways but they seem somewhat laborious. Which one is more efficient than the other and is there a shorter way of getting the count? NOTE: you don't know what the key of the last dictionary is and the dictionary is will always have one key-value pair. The 1st approach is: &gt;&gt;&gt; value = list(stack[-1].values())[0] &gt;&gt;&gt; value 3 The 2nd approach is: &gt;&gt;&gt; value = next(iter(stack[-1].values())) &gt;&gt;&gt; value 3 Which of the two approaches is more time and space efficient and is there another approach that beats the two given the approach of using a stack of dictionaries to solve the problem?
has comment: http://stackoverflow.com/comment/88330333
has comment: http://stackoverflow.com/comment/88330626
score: 0
has title: More time and space efficient way to access value of dictionary in stack without knowing its key?
has comment: http://stackoverflow.com/comment/88330226
has comment: http://stackoverflow.com/comment/88329986
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/88330818
has comment: http://stackoverflow.com/comment/88330492

http://stackoverflow.com/comment/88322755
score: 0
has text: Thank you so much! @Priya, I solved the problem with your advice.
type: Comment
comment on: http://stackoverflow.com/a/50596846
type: AnswerComment

http://stackoverflow.com/q/50672358
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50672369
tagged with: python
score: 2
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/50672400
has body: I'm getting a NameError: global name 'spacing' is not defined for and im not sure why def main(): print("Project One\n") print("To encrypt message enter: 1") print("To decrypt messsge enter: 2\n") pick = int(input()) if pick == 1: print("Encrypting!") spacing() elif pick == 2: print("Decrypting!") else: print("Try again") if __name__ == '__main__': main() def spacing(): text = raw_input("Please Enter the message to encrypt: ").upper() print(text) key = raw_input("Please enter a key to encrypt").upper() print(key) space_ignore = "" j = 0 for i in range(len(text)): if ord(text[i]) == 32: space_ignore += " " else: if j &lt; len(key): space_ignore += key[j] j += 1 else: j = 0 space_ignore += key[j] j += 1 print(space_ignore) return text, space_ignore
tagged with: nameerror
upvote count: 2
answer count: 3
has answer: http://stackoverflow.com/a/50672371
favorite count: 0
has title: why am i getting NameError: global name 'spacing' is not defined
has comment: http://stackoverflow.com/comment/88354475

upsert
tags question: http://stackoverflow.com/q/50606970
type: Tag
tag name: upsert

http://stackoverflow.com/q/50687892
score: -1
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/50688178
has answer: http://stackoverflow.com/a/50690407
has comment: http://stackoverflow.com/comment/88385720
favorite count: 0
has comment: http://stackoverflow.com/comment/88385454
type: UnansweredQuestion
has body: I need to remake sentences (which are opened from a txt file) in a way that a letter in a word is repeated as many times as it is encountered in the word itself. Example: "I need a drink" must become: "I neeeed a drink" Here is the code. It's pretty screwed up, I know: import collections c = collections.Counter() words_title = [] new_word = '' new_word2 = '' with open("file.txt", "r", encoding = "utf-8-sig") as file: reading = file.read() splitted = reading.split() words_title = [word.title() for word in reading] for word in words_title: for wor in word: for wo in word: c[wo] += 1 new_word += word for word2 in new_word: word2 = word2 * c[word2] new_word2 += word2 print(c) print(new_word) print(new_word2)
tagged with: python
has comment: http://stackoverflow.com/comment/88385612
tagged with: collections
has answer: http://stackoverflow.com/a/50688213
has comment: http://stackoverflow.com/comment/88385775
has comment: http://stackoverflow.com/comment/88385551
has title: I have an issue with "collections" module in Python
type: Question
downvote count: 2

http://stackoverflow.com/q/50551385
type: UnansweredQuestion
tagged with: python
has body: I have the basic screensaver program. I want to bind Mouse button 1 to delete everything on screen, but when I press the Button-1 I get this error: Exception in Tkinter callback Traceback (most recent call last): File "C:\Python34\lib\idlelib\run.py", line 121, in main seq, request = rpc.request_queue.get(block=True, timeout=0.05) File "C:\Python34\lib\queue.py", line 175, in get raise Empty queue.Empty During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__ return self.func(*args) TypeError: delete() takes 0 positional arguments but 1 was given . . . . This is my program: import tkinter canvas=tkinter.Canvas(width=1000,height=800) canvas.pack() from random import * entry1=tkinter.Entry() entry1.pack() def setric(): x=randrange(900) y=randrange(700) global a canvas.delete('all') farba=choice(("red","purple","blue","lightblue","green","lightgreen")) if a&gt;-90: a=a-10 else: a=-10 if entry1.get()=="": canvas.update() canvas.after(3000,setric) a=0 else: canvas.create_text(x,y,text=entry1.get(),font="Arial 40",fill=farba,angle=a) canvas.after(2000, setric) def delete(): canvas.delete("all") a=0 setric() canvas.bind('&lt;Button-1&gt;',delete) Even when I change what is in the def delete I still get the error. Thanks for your time! I am new to this so I have no idea where is the problem ....................................................................................................................................................................................................................................................
tagged with: bind
tagged with: tkinter
score: 1
upvote count: 1
type: Question
has title: python bind not working
has answer: http://stackoverflow.com/a/50557119
tagged with: tkinter-canvas
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/88398012
type: Comment
comment on: http://stackoverflow.com/a/50681799
type: AnswerComment
has text: Thank you so much for you reply. It is very useful and same as I wanted.
score: 0

http://stackoverflow.com/comment/88403932
has text: still not getting the expected output
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50696442
type: AnswerComment

http://stackoverflow.com/comment/88201595
has text: it is class_ bcos class is reserved keyword
comment on: http://stackoverflow.com/q/50596236
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50642171
downvote count: 0
has body: You can create first MultiIndex in columns by parameter header and then loop by first level with concat: df = pd.read_csv(file, header=[0,1]) L = [] cols = df.columns.get_level_values(0) for x in cols: c = df[x].columns.str.split(',')[0] a = pd.concat([df[x].squeeze()] * len(c), axis=1, keys=c) L.append(a) df = pd.concat(L, axis=1, keys=cols) With sample data: df = pd.DataFrame(data=np.random.random(size=(5,6)), columns={'a', 'b', 'c, d', 'c', 'f, g', 'h'}) #print (df) L = [] for x in df.columns: c = x.split(', ') a = pd.concat([df[x].squeeze()] * len(c), axis=1, keys=c) L.append(a) df = pd.concat(L, axis=1) s = df.columns.to_series() df.columns = s + s.groupby(s).cumcount().astype(str).radd('.').str.replace('.0', '') print (df) c h a c.1 d b f \ 0 0.846482 0.285415 0.695800 0.497593 0.497593 0.159911 0.286545 1 0.195390 0.369074 0.371147 0.102207 0.102207 0.924279 0.349958 2 0.967811 0.059451 0.942390 0.826203 0.826203 0.722080 0.196833 3 0.546076 0.789354 0.876819 0.243305 0.243305 0.391054 0.213517 4 0.311528 0.544023 0.380844 0.308427 0.308427 0.511651 0.795380 g 0 0.286545 1 0.349958 2 0.196833 3 0.213517
has comment: http://stackoverflow.com/comment/88299285
score: 3
has comment: http://stackoverflow.com/comment/88299205
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50641835
upvote count: 3
answers question: http://stackoverflow.com/q/50641835
type: Answer

http://stackoverflow.com/a/50686586
answers question: http://stackoverflow.com/q/50612686
score: 0
has body: Solved by comment from @Y. Luo. In trying to simplify my file string, I only partially cloned the Gorner GitHub file into my host file and missed the utils_datagen file. Now python can find it. Close this thread.
type: Answer

http://stackoverflow.com/comment/88314731
type: QuestionComment
score: 0
type: Comment
has text: Thank you! i have replace '/' by '\\' but still error continues. i think that error is comming due to imshow function.
comment on: http://stackoverflow.com/q/50644073

http://stackoverflow.com/comment/88267897
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50627320
has text: You can try iterating over the rows and manually appending to the csv. https://stackoverflow.com/questions/33030726/how-to-iterate-records-spark-scala?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

http://stackoverflow.com/comment/88232884
type: Comment
score: 0
has text: That part works. When I enter that code every data set that was from the year 1989 in the file "Customers" is selected. Now it is just a matter of exporting the selected data into a new files called "Customers_1989"
comment on: http://stackoverflow.com/q/50611275
type: QuestionComment

http://stackoverflow.com/comment/88328690
has text: Ok cheers, so the sigma is derived from the value you set as gamma?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50658725

http://stackoverflow.com/comment/88388638
comment on: http://stackoverflow.com/a/50689272
type: AnswerComment
has text: @Sethen: can you post the full model? Did you make migrations and applied these?
score: 0
type: Comment

http://stackoverflow.com/a/50677071
type: Answer
score: 0
has body: I had the same problem, i used to run the app flask with : app.run(debug=True, host="0.0.0.0", threaded=True) Then I tested with threaded=False (because joblib wants to be in the main thread), but it didn't worked too. I don't know why, but it works with debug=False... Here is how i fixed the problem : app.run(debug=False, host="0.0.0.0", threaded=False) If someone knows why the debug=True causes joblib warning, i'd like to know :)
has comment: http://stackoverflow.com/comment/88382664
answers question: http://stackoverflow.com/q/50665837

http://stackoverflow.com/q/50548373
has body: I am having issues building a web scraper for this website which heavily uses javascript. The code I have is below: from pyvirtualdisplay import Display from selenium import webdriver from bs4 import BeautifulSoup display = Display(visible=0, size=(800, 600)) display.start() browser = webdriver.Chrome() #Page 1 url1 = 'https://www.zalora.co.id/women/pakaian/atasan/?gender=women&amp;dir=desc&amp;sort=popularity&amp;category_id=704&amp;page=1' browser.get(url1) soup_1 = BeautifulSoup(browser.page_source, 'html5lib') page_script_1 = soup_1.findAll('script')[40].text #Page 2 url2 = 'https://www.zalora.co.id/women/pakaian/atasan/?gender=women&amp;dir=desc&amp;sort=popularity&amp;category_id=704&amp;page=2' browser.get(url2) page_script_2 = soup.findAll('script')[40].text soup_2 = BeautifulSoup(browser.page_source, 'html5lib') page_script_2 = soup_2.findAll('script')[40].text The desired output is the html of the 2 distinct pages (i.e. the value in page_script_1 should be different from page_script_2) HOWEVER, the output in both cases appears to be the same. Anyone know why? (Note, I basically want to scrape the products on all the pages)
type: UnansweredQuestion
tagged with: python
tagged with: selenium-chromedriver
answer count: 0
score: 1
tagged with: selenium
tagged with: web-scraping
upvote count: 1
type: Question
has title: Issue web scraping javascript website using selenium
has comment: http://stackoverflow.com/comment/88107977
downvote count: 0
favorite count: 0
tagged with: beautifulsoup

reindex
tag name: reindex
tags question: http://stackoverflow.com/q/50562309
type: Tag

http://stackoverflow.com/q/50642738
has comment: http://stackoverflow.com/comment/88301765
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88312138
type: UnansweredQuestion
has title: Map wordNet sense key to VerbNet
has answer: http://stackoverflow.com/a/75682216
type: Question
tagged with: nltk
answer count: 1
has body: How to get the verb class id given the wordNet sense key using NLTK. For example: extracting the verb class id from this wordnet sense key: take.v.01
score: 0
linked to: http://stackoverflow.com/q/29323849
has comment: http://stackoverflow.com/comment/88312038
tagged with: python
has comment: http://stackoverflow.com/comment/88303530

http://stackoverflow.com/comment/88321799
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50655906
has text: What should your output look like? An array the size of `a1` with the count at each index?
score: 0

http://stackoverflow.com/comment/88292822
comment on: http://stackoverflow.com/q/50641240
score: 0
type: QuestionComment
type: Comment
has text: Thanks @Moia, I am completely aware of your concern. For the time being, it will be sufficient for the objective of this small program.

http://stackoverflow.com/a/50655660
has body: Converting comment into answer: The problem is passing list of lists as inputs to the final model. You need concatenate the individual input lists of sub models: model = Model(inputs=cnnModel.inputs+cnnModel2.inputs, outputs=outputs)
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50653128
answers question: http://stackoverflow.com/q/50653128
downvote count: 0
score: 1

http://stackoverflow.com/a/50589008
upvote count: 3
has comment: http://stackoverflow.com/comment/88212408
has comment: http://stackoverflow.com/comment/88200771
accepted answer of: http://stackoverflow.com/q/50588857
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50588857
has body: You are trying to create an instance of the class before the class statement has completed. The class object has been created, but has not yet been assigned to a global name. The order of events is: the class Dep_A statement is found, and the class body is executed to form the attributes (creating the __init__ function). the metaclass __new__ method is called with the classname, bases, and the class body namespace ('Dep_A', (Department,) and {'__init__': &lt;function ...&gt;, ...} respectively). the metaclass creates the new class object The metaclass calls registry(), passing in the new class object registry() calls the class object The class __init__ method is called Normally, Dep_A is assigned when the metaclass __new__ method returns the newly created object. Until that point there is no global name Dep_A assigned, so the super(Dep_A, self).__init__() call fails. You could set the name from there first: class MetaClass(type): def __new__(mcs, clsname, bases, attrs): # newclass = super(MetaClass, mcs).__new__(mcs, clsname, bases, attrs) newclass = type.__new__(mcs,clsname, bases, attrs) globals()[clsname] = newclass register(newclass) return newclass Alternatively, don't try to create an instance in the registry, store a class instead. You can always create a single instance later on. The following implements a registry that transparently creates an instance later when you need one, and stores just that one instance created: from collections import Mapping class Registry(Mapping): def __init__(self): self._classes = {} self._instances = {} def __getitem__(self, name): if name not in self._instances: self._instances[name] = self._classes.pop(name)() return self._instances[name] def __iter__(self): return iter(self._classes.viewkeys() | self._instances.viewkeys()) def __len__(self): return len(self._classes) + len(self._instances) def register(self, cls): self._classes[cls.__name__] = cls registry = Registry() class MetaClass(type): def __new__(mcs, clsname, bases,…
type: Answer
score: 3

http://stackoverflow.com/q/50652204
has comment: http://stackoverflow.com/comment/88315304
has answer: http://stackoverflow.com/a/50652508
tagged with: pandas
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50652508
has body: So I am trying to create a function that could allow me to quickly create a pivot table based on a number of factors. However, every time I run it, the function doesn't drop the index, which in turn does not aggregate data. for example Here is one of the dframes I've been working with User_ID Trans_Type Date Revenue Cohort Month 0 958507335 Purchase 2013-02-01 22.0 2013-02 2013-02 1 77396089 Purchase 2013-02-01 50.0 2013-02 2013-04 2 168623910 Sale 2013-02-01 20.0 2013-02 2013-02 3 124390583 Sale 2013-02-01 53.0 2013-02 2013-03 4 312221573 Sale 2013-02-01 160.0 2013-02 2013-04 5 767171090 Sale 2013-02-01 56.0 2013-02 2013-04 6 328835282 Sale 2013-02-01 76.0 2013-02 2013-02 7 289850608 Sale 2013-02-01 27.0 2013-02 2013-06 8 926145734 Sale 2013-02-01 16.0 2013-02 2013-02 9 950422305 Sale 2013-02-01 49.0 2013-02 2013-04 Basically, there are two transaction types. Sale and Purchase. Here is the function I have been using to create a pivot table from it. x = 'Sale' df = df.set_index('User_ID', inplace=True) def LTV_calc_(df): df1 = df[df['Transaction_Type'] == x] #Convert to a pivot table df2 = df1.groupby(['Cohort','Month']) df3 = df2.agg({'User_ID': ['count'], 'Revenue': ['sum']}) return df3 Sales = df.groupby(level=0).apply(LTV_calc_) Now when I run the Sales DF, it comes out something like this: User_ID Revenue count sum Cohort Month 16940 2013-02 2013-02 1 59.0 16941 2013-02 2013-02 1 62.0 16942 2013-04 2013-04 1 288.0 16943 2013-02 2013-02 1 33.0 16944 2013-05 2013-05 1 14.0 16945 2013-03 2013-03 1 0.0 Whenever I run the code without a function, it correctly produces this: User_ID Rev/Payout count sum Cohort Month 2013-02 2013-02 293 8449.0 2013-03 41 1208.0 2013-04 52 1708.0 2013-05 55 2469.0 2013-06 62 2911.0 I've had this problem a couple other times. Anyone know what I a doing wrong?
favorite count: 0
has comment: http://stackoverflow.com/comment/88315511
tagged with: python
has title: Group by within a function does not properly group by
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/comment/88258861
has text: ok that is good, now I'm getting Invalid Token error, so I need a bit more handling to have here, is this even possible to achieve?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50624497
type: AnswerComment

http://stackoverflow.com/comment/88336920
has text: Sorry, I added a countdown label that also uses the`after` method
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50663103

http://stackoverflow.com/comment/88174450
type: QuestionComment
comment on: http://stackoverflow.com/q/50582647
has text: It is hard to tell what you really want to do. But using a grid summation approach like mine could work for you:https://stackoverflow.com/questions/49451834/gaussian-summation-for-2d-scatter-plots-using-python
score: 0
type: Comment

http://stackoverflow.com/a/50554610
has body: Change your code to pizza_vege=['tomato sauce','mushrooms','pepper','cheese','garlic powder'] print(pizza_vege) pizza_vege.append('peperoni') print(pizza_vege) Which yields ['tomato sauce', 'mushrooms', 'pepper', 'cheese', 'garlic powder'] ['tomato sauce', 'mushrooms', 'pepper', 'cheese', 'garlic powder', 'peperoni']
score: 0
answers question: http://stackoverflow.com/q/50554589
type: Answer

http://stackoverflow.com/q/50685937
has comment: http://stackoverflow.com/comment/88419787
score: 2
answer count: 0
favorite count: 0
type: Question
tagged with: windows
tagged with: python
linked to: http://stackoverflow.com/q/1023038
has title: How to "own" a processor?
upvote count: 3
linked to: http://stackoverflow.com/q/2319495
tagged with: multithreading
tagged with: cpu
downvote count: 1
has comment: http://stackoverflow.com/comment/88381783
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88381896
has body: I have a somewhat different problem to solve with threads in Python. I have a Python application that talks to very high-speed hardware through a polling interface. I would like the Python process to "own" one of the CPUs, that is, I don't want the Python application to share its CPU with any other process. What I am currently seeing is that my application gets put "on hold" for tens of milliseconds at a time while it is servicing hardware that executes commands in tens of microseconds, thus the hardware goes idle while my Python application is put on hold. I am running under Windows 10. Is there a system call of some kind that lets me own the CPU?

http://stackoverflow.com/q/50693257
score: 4
has comment: http://stackoverflow.com/comment/88406295
has comment: http://stackoverflow.com/comment/88398173
tagged with: python
tagged with: web
has comment: http://stackoverflow.com/comment/88398147
favorite count: 0
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/15268953
has body: I have installed Python 3 via Anaconda 3 to my PC which runs Windows10. In trying to install pattern I get an error message: (base) C:\Users\Alienware\Documents&gt;pip install pattern Collecting pattern Using cached https://files.pythonhosted.org/packages/bf/50/d09941d53416f2a86676bd0dc341d5968b599a763b73f5d13f51c57b5641/pattern-2.6.zip Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Users\ALIENW~1\AppData\Local\Temp\pip-install-w36z8q7u\pattern\setup.py", line 40 print n ^ SyntaxError: Missing parentheses in call to 'print' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\ALIENW~1\AppData\Local\Temp\pip-install-w36z8q7u\pattern\ Moreover at Github (https://github.com/clips/pattern) it is stated that: Pattern supports Python 2.7 and Python 3.6+. The Python 3 version is currently only available on the development branch. But how do I access the 'development branch'? On the other hand, I have successfully installed pattern3 to use with Python 3 but I can not find documentation for pattern3 (compatible with Python 3) using Google. Update @Roshan, I am running into an exception. See below:
has comment: http://stackoverflow.com/comment/88397152
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/88397174
has title: Installing Pattern for Python 3
downvote count: 0

http://stackoverflow.com/comment/88162528
comment on: http://stackoverflow.com/a/50576003
type: AnswerComment
has text: What version of Python and what OS/version are you using? I'm using Python 3.6.0 on macOS.
score: 0
type: Comment

http://stackoverflow.com/comment/88098640
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50543293
type: AnswerComment
has text: @ João Castilho so what does this do? row1="|{}|{}|{}|".format(board[0],board[1],board[2]) row2="|{}|{}|{}|".format(board[3],board[4],board[5]) row3="|{}|{}|{}|".format(board[6],board[7],board[8])

http://stackoverflow.com/comment/88261806
has text: This answer should help you: [Get filename and download](https://stackoverflow.com/a/48229071/4985733)
type: QuestionComment
comment on: http://stackoverflow.com/q/50623184
score: 0
type: Comment

http://stackoverflow.com/comment/100795179
has text: Hi I used below code import pandas as pd df1 = pd.read_excel(r" ") df2 = pd.read_excel(r" ") df2['changerequestnumber']=df2['changerequestnumber'].astype(int) f9=df1.merge(df3, left_on='Related CRs', right_on='changerequestnumber') f9.to_excel(r" ") but still i am getting ValueError: You are trying to merge on object and int32 columns. If you wish to proceed you should use pd.concat can you help me on this
type: Comment
comment on: http://stackoverflow.com/a/50649933
type: AnswerComment
score: 0

rasa-core
tags question: http://stackoverflow.com/q/50684711
tag name: rasa-core
type: Tag

http://stackoverflow.com/comment/114972823
comment on: http://stackoverflow.com/a/50599108
has text: Is it possible to alter this in anyway to make the seeking work as quickly as -ss...-to? Using -ss to cut a single section from a long file is very fast.
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/comment/88372917
type: AnswerComment
score: 0
has text: thanks. yes that makes sense. Does converting categorical input to one hot hold true for keras library too? The reason that I am asking is that in this IMDB dataset example the input is clearly categorical and yet it has not been converted to one hot and fed to the model as is. https://machinelearningmastery.com/sequence-classification-lstm-recurrent-neural-networks-python-keras/
type: Comment
comment on: http://stackoverflow.com/a/50680318

http://stackoverflow.com/comment/88332945
type: Comment
comment on: http://stackoverflow.com/a/50661068
has text: So what value would `my_list` hold prior to it's creation? In my answer, I'm assuming this is the first time the OP is creating the variable `name_list`. If so, then `name_list` couldn't be used yet because it doesn't exit.
type: AnswerComment
score: 0

pylint
tags question: http://stackoverflow.com/q/50656874
tags question: http://stackoverflow.com/q/50569453
type: Tag
tags question: http://stackoverflow.com/q/50630822
tags question: http://stackoverflow.com/q/50661107
tags question: http://stackoverflow.com/q/50558480
tags question: http://stackoverflow.com/q/50649830
tag name: pylint

http://stackoverflow.com/a/50683387
has comment: http://stackoverflow.com/comment/88405362
score: 10
has comment: http://stackoverflow.com/comment/88376932
has comment: http://stackoverflow.com/comment/88410285
type: AcceptedAnswer
has body: Regarding 'SAME' padding, the Convolution documentation offers some detailed explanations (further details in those notes). Especially, when using 'SAME' padding, the output shape is defined so: # for `tf.layers.conv2d` with `SAME` padding: out_height = ceil(float(in_height) / float(strides[1])) out_width = ceil(float(in_width) / float(strides[2])) In this case, the output shape depends only on the input shape and stride. The padding size is computed from there to fill this shape requirement (while, with 'VALID' padding, it's the output shape which depends on the padding size) Now for transposed convolutions... As this operation is the backward counterpart of a normal convolution (its gradient), it means that the output shape of a normal convolution corresponds to the input shape to its counterpart transposed operation. In other words, while the output shape of tf.layers.conv2d() is divided by the stride, the output shape of tf.layers.conv2d_transpose() is multiplied by it: # for `tf.layers.conv2d_transpose()` with `SAME` padding: out_height = in_height * strides[1] out_width = in_width * strides[2] But once again, the padding size is calculated to obtain this output shape, not the other way around (for SAME padding). Since the normal relation between those values (i.e. the relation you found) is: # for `tf.layers.conv2d_transpose()` with given padding: out_height = strides[1] * (in_height - 1) + kernel_size[0] - 2 * padding_height out_width = strides[2] * (in_width - 1) + kernel_size[1] - 2 * padding_width Rearranging the equations we get padding_height = [strides[1] * (in_height - 1) + kernel_size[0] - out_height] / 2 padding_width = [[strides[2] * (in_width - 1) + kernel_size[1] - out_width] / 2 note: if e.g. 2 * padding_height is an odd number, then padding_height_top = floor(padding_height); and padding_height_bottom = ceil(padding_height) (same for resp. padding_width, padding_width_left and padding_width_right) Replacing out_height and out_width with their ex…
upvote count: 10
type: Answer
has comment: http://stackoverflow.com/comment/88404413
accepted answer of: http://stackoverflow.com/q/50683039
downvote count: 0
has comment: http://stackoverflow.com/comment/88412843
answers question: http://stackoverflow.com/q/50683039
has comment: http://stackoverflow.com/comment/88378771
has comment: http://stackoverflow.com/comment/88410528

http://stackoverflow.com/a/50700350
type: Answer
has comment: http://stackoverflow.com/comment/88418682
answers question: http://stackoverflow.com/q/50696587
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/50696587
type: AcceptedAnswer
downvote count: 0
has body: This is because Pepper's Autonomous Life is built around activities, and anytime an activity loses focus, Pepper resets everything - language, posture, LEDs and, yes, the tablet. So ideally your code should be inside an application (i.e. a behavior flagged as "interactive"), and as long as it has the focus, the tablet won't get reset. (edit) to create an application that is a standalone Python script, one easy way is using robot jumpstarter, a python script that will generate an app from a template (with all the boilerplate etc.), see here for instructions.

http://stackoverflow.com/comment/88208892
has text: Well by default django wraps every view in a transaction, hence the concurrent updates of other views are not seen by this thread (unless these were already commited before we entered the view).
comment on: http://stackoverflow.com/q/50599893
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50642745
type: Answer
has comment: http://stackoverflow.com/comment/103909081
answers question: http://stackoverflow.com/q/50620954
upvote count: 5
has comment: http://stackoverflow.com/comment/103868523
has body: Not sure if this is the 'right' way to do it but I ended up completely uninstalling anaconda and rebuilding it. When I then made a new virtual environment the problem resolved. If others have the same issue this might work too. By the way the problem first occurred with an update to pyqt5.
downvote count: 0
score: 5
has comment: http://stackoverflow.com/comment/103905816

http://stackoverflow.com/comment/88153748
type: Comment
comment on: http://stackoverflow.com/a/50572080
type: AnswerComment
has text: Yes, this was what I was looking for.
score: 0

http://stackoverflow.com/a/50564055
answers question: http://stackoverflow.com/q/50555557
type: Answer
score: 0
has body: I found the solution, I just needed to modify folder = "C:\Folder"+"/"+f.split(".")[1] to folder = "C:\Folder"+"/"+f.split(".")[1].replace(f.split(".")[2]

http://stackoverflow.com/q/50643118
score: 4
has title: Concatenating a row in a pandas Dataframe
has comment: http://stackoverflow.com/comment/88296551
has comment: http://stackoverflow.com/comment/88296913
has comment: http://stackoverflow.com/comment/88296792
tagged with: dataframe
has answer: http://stackoverflow.com/a/50643489
upvote count: 4
tagged with: pandas
has body: This seems like it should be so much simpler yet here I am. I'm trying to add a row to a data frame (2 data frames to be exact) from another data frame, but I get the following error: TypeError: cannot concatenate object of type "&lt;class 'numpy.float64'&gt;"; only pd.Series, pd.DataFrame, and pd.Panel (deprecated) objs are valid My code for i in range(0,len(k_means_labels_unique)): X = pd.DataFrame(columns=['first occurrence of \'AB\'','similarity to \'AB\'']) y = pd.DataFrame(columns=['Class']) for row in result.iterrows(): data=row[1] if data['cluster ID'] == i: X = pd.concat([X,data['first occurrence of \'AB\''],data['similarity to \'AB\'']]) y = pd.concat([y,data['Class']]) Do I have to transform data['first occurrence of \'AB\''],data['similarity to \'AB\''] into another data frame? This seems horribly inefficient EDIT: I tried y = pd.concat([y,pd.Series(data['Class'])]) but that appended the data as a new column, example for y:
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/50643489
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88296854
tagged with: python
answer count: 1

http://stackoverflow.com/q/50691805
answer count: 3
score: 2
has comment: http://stackoverflow.com/comment/88393236
downvote count: 0
favorite count: 0
tagged with: python-3.x
has title: Return array indices from function
has answer: http://stackoverflow.com/a/50691839
accepted answer: http://stackoverflow.com/a/50691862
tagged with: python
type: AnsweredQuestion
upvote count: 2
type: Question
tagged with: indexing
tagged with: function
possible better answer: http://stackoverflow.com/a/50691884
has answer: http://stackoverflow.com/a/50691884
has answer: http://stackoverflow.com/a/50691862
has body: I have an array and function and I would like the function to return a list of indices in which the difference of two consecutive elements passes a threshold. I have: def func (y, t=100): for i in range(1, len(y)): #Range skips 1st element if abs(y[i] - y[i-1]) &gt; t: return(i) The problem I'm facing is that this function only returns the first index where my if statement is true. How do I get the rest of them?
has comment: http://stackoverflow.com/comment/88393219

http://stackoverflow.com/q/50685458
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/66924516
has title: Specify border appearance in tables using python-docx
has answer: http://stackoverflow.com/a/66924516
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50788449
downvote count: 0
tagged with: python-docx
favorite count: 0
tagged with: border
has body: I am going through the tutorial and documentation of python-docx. However, I can't find any reference to how I can specify and manipulate the border appearance of a table created in a Microsoft Word document. When i use the following code: from docx import Document from docx.shared import Inches document = Document() ################################ ################################ ################################ table = document.add_table(rows=1, cols=3) hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Qty' hdr_cells[1].text = 'Id' hdr_cells[2].text = 'Desc' row_cells = table.add_row().cells row_cells[0].text = 'Str0' row_cells[1].text = 'Str1' row_cells[2].text = 'Str2' row2_cells = table.add_row().cells row2_cells[0].text = 'Str00' row2_cells[1].text = 'Str11' row2_cells[2].text = 'Str22' ################################ ################################ ################################ document.save('demo.docx') The resulting docx file shows the 3x3 table with header. Currently there is no black border (inner or outer) on this table. How can I specify an upper and lower border around the header, a lower border to wrap around the table, as well as an inner vertical border? For example:
tagged with: ms-word
accepted answer: http://stackoverflow.com/a/50788449
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/88133909
type: QuestionComment
has text: Since you single letter are in sequence you could take advantage of the collating sequence with `if cond > ord("A")-1 and cond < ord("D")+1`
type: Comment
comment on: http://stackoverflow.com/q/50561552
score: 0

http://stackoverflow.com/comment/88179274
comment on: http://stackoverflow.com/a/50584423
has text: yup 3000 was insane sorry.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88355104
type: AnswerComment
has text: thanks for your quick and accurate responses and i have also looked at https://stackoverflow.com/help/someone-answers
comment on: http://stackoverflow.com/a/50660363
type: Comment
score: 1

http://stackoverflow.com/comment/88335515
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50660633
has text: How are you running your two programs? Are you sure they're getting run by the same interpreter? The exception you describe is telling you that `multiprocessing.synchronize` can't get access to the C system calls it needs for its implementation. That seems like a very unlikely thing to change, just from running a different Python script. It's much more likely if you're running a completely different interpreter too.
score: 0

http://stackoverflow.com/q/50674271
favorite count: 0
tagged with: python-3.x
tagged with: google-cloud-firestore
tagged with: python
has body: Documentation goes as far as explaining how to write the following data types: data = { u'stringExample': u'Hello, World!', u'booleanExample': True, u'numberExample': 3.14159265, u'dateExample': datetime.datetime.now(), u'arrayExample': [5, True, u'hello'], u'nullExample': None, u'objectExample': { u'a': 5, u'b': True } } I am migrating a Mongo DB collection into FireStore. This is my code so far: import firebase_admin from firebase_admin import credentials from firebase_admin import firestore def initialize_firestore(): cred = credentials.Certificate('admin.json') app = firebase_admin.initialize_app(cred) db = firestore.client() return db db.collection('My_Collection').document('desired_iD').set('Document_to_write') I would like to write a document with reference and location fields plus a custom date.
has answer: http://stackoverflow.com/a/50674330
tagged with: nosql
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
tagged with: firebase
has title: How to write location, reference and timestamp data types on Firestore with Python's SDK?
accepted answer: http://stackoverflow.com/a/50674330
answer count: 1
downvote count: 0

http://stackoverflow.com/q/50612708
has comment: http://stackoverflow.com/comment/88282527
upvote count: 1
tagged with: python
score: 1
tagged with: apply
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/88235571
has body: I'm trying to throw regex at a 500MB text file: with open(f'{trn_path}text.00') as file: df_trn = file.readlines() re1 = re.compile(r' +') def fixup(x): x.replace('&gt;', '').replace('&lt;', '').replace('doc', '').replace(':', '').replace('t_up', '').replace( 'fi.wikipedia.org', '').replace('url="https', '').replace('\xa0','') return re1.sub(' ', html.unescape(x)) df_trn = pd.Series(df_trn) df_trn = df_trn.apply(fixup).values.astype(str) Gives me MemoryError: If I read the file chunksize df_trn.to_csv(f'{trn_path}train.csv', header=False, index=False) df_trn = pd.read_csv(f'{trn_path}train.csv', header=None, chunksize=chunksize) I get AttributeError: 'TextFileReader' object has no attribute 'apply' Any ideas? Thanks!
tagged with: pandas
has title: Pandas .apply MemoryError and 'TextFileReader' object has no attribute 'apply'
favorite count: 0
has comment: http://stackoverflow.com/comment/88235535
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/50696141
accepted answer of: http://stackoverflow.com/q/50696069
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50696069
has body: As the name says, this class is a mixin. It is intended to be used with a view class, specifically a subclass of TemplateView, which will define get_context_data.
type: Answer
has comment: http://stackoverflow.com/comment/88401530
has comment: http://stackoverflow.com/comment/88401616
score: 5
upvote count: 5

http://stackoverflow.com/q/50569899
possible better answer: http://stackoverflow.com/a/50570029
linked to: http://stackoverflow.com/q/44635626
has answer: http://stackoverflow.com/a/50570029
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88149625
has comment: http://stackoverflow.com/comment/88149686
type: Question
has body: Lets say I have a table that look like this: Company Region Date Count Amount AAA XXY 3-4-2018 766 8000 AAA XXY 3-14-2018 766 8600 AAA XXY 3-24-2018 766 2030 BBB XYY 2-4-2018 66 3400 BBB XYY 3-18-2018 66 8370 BBB XYY 4-6-2018 66 1380 I want to get rid of the Date column, then aggregate by Company AND region to find the average of Count and sum of Amount. Expected output: Company Region Count Amount AAA XXY 766 18630 BBB XYY 66 13150 I looked into this post here, and many other posts online, but seems like they are only performing one kind of aggregation action (for example, I can aggregate by multiple columns but can only produce one column output as sum OR count, NOT sum AND count) Rename result columns from Pandas aggregation ("FutureWarning: using a dict with renaming is deprecated") Can someone help? What I did: I followed this post here: https://www.shanelynn.ie/summarising-aggregation-and-grouping-data-in-python-pandas/ however, when i try to use the method presented in this article (toward the end of the article), by using dictionary: aggregation = { 'Count': { 'Total Count': 'mean' }, 'Amount': { 'Total Amount': 'sum' } } I would get this warning: FutureWarning: using a dict with renaming is deprecated and will be removed in a future version return super(DataFrameGroupBy, self).aggregate(arg, *args, **kwargs) I know it works now but i want to make sure my script works later too. How can I update my code to be compatible in the future?
accepted answer: http://stackoverflow.com/a/50569955
upvote count: 5
has answer: http://stackoverflow.com/a/50570074
tagged with: pandas-groupby
answer count: 3
tagged with: pandas
downvote count: 0
has title: pandas: how to group by multiple columns and perform different aggregations on multiple columns?
favorite count: 0
score: 5
has answer: http://stackoverflow.com/a/50569955
tagged with: python

http://stackoverflow.com/a/50637892
downvote count: 0
answers question: http://stackoverflow.com/q/50637772
type: Answer
accepted answer of: http://stackoverflow.com/q/50637772
has comment: http://stackoverflow.com/comment/88285958
score: 1
upvote count: 1
has body: For your first question, it looks like unclear. You should first figure out where is the bottleneck. If I understand properly, every 1 second your extracting thread add 700 tasks into queue, and then every work thread just take one of these tasks and send a request to a remote server. Am I right? In this case, does the network cause slow down? Could you confirm it? If you think GIL leads to poor performance when using more threads, does that mean there is some calculation bottleneck in your program? And then for your second question, gevent will help you a lot if the slow down is caused by network.
type: AcceptedAnswer

http://stackoverflow.com/q/50665038
tagged with: sqlite
answer count: 1
has title: sqlite selecting multiple tables
has body: I have a database in sqlite with c.300 tables. Currently i am iterating through a list and appending the data. Is there a faster way / more pythonic way of doing this? df = [] for i in Ave.columns: try: df2 = get_mcap(i) df.append(df2) #print (i) except: pass df = pd.concat(df, axis=0 Ave is a dataframe where the column in the list i want to iterate through. def get_mcap(Ticker): cnx = sqlite3.connect('Market_Cap.db') df = pd.read_sql_query("SELECT * FROM '%s'"%(Ticker), cnx) df.columns = ['Date', 'Mcap-Ave', 'Mcap-High', 'Mcap-Low'] df = df.set_index('Date') df.index = pd.to_datetime(df.index) cnx.close return df
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50666716
has comment: http://stackoverflow.com/comment/88343042
type: Question
has comment: http://stackoverflow.com/comment/88341029
score: 0

http://stackoverflow.com/q/50617334
type: UnansweredQuestion
has body: I have 2 lists of ordereddict which i fetch from DB through a function and they look like below First list printed output: OrderedDict([('Items', '1'), ('Itemspaid', 'Rutr'), ('First', 'Het'), ('Second', 'Fru'), ('Third', 'yurn'), ('Flip', 223.513353868968)]) OrderedDict([('Items', '2'), ('Itemspaid', 'Rutr'), ('First', 'Het'), ('Second', 'Fru'), ('Third', 'yurn'), ('Flip', 243.513353868968)]) OrderedDict([('Items', '3'), ('Itemspaid', 'Rutr'), ('First', 'Het'), ('Second', 'Fru'), ('Third', 'yurn'), ('Flip', 263.513353868968)]) OrderedDict([('Items', '4'), ('Itemspaid', 'Rutr'), ('First', 'Het'), ('Second', 'Fru'), ('Third', 'yurn'), ('Flip', 323.513353868968)]) OrderedDict([('Items', '5'), ('Itemspaid', 'Rutr'), ('First', 'Het'), ('Second', 'Fru'), ('Third', 'yurn'), ('Flip', 333.513353868968)]) OrderedDict([('Items', '6'), ('Itemspaid', 'Rutr'), ('First', 'Het'), ('Second', 'Fru'), ('Third', 'yurn'), ('Flip', 343.513353868968)]) OrderedDict([('Items', '7'), ('Itemspaid', 'Rutr'), ('First', 'Het'), ('Second', 'Fru'), ('Third', 'yurn'), ('Flip', 353.513353868968)]) OrderedDict([('Items', '8'), ('Itemspaid', 'Rutr'), ('First', 'Het'), ('Second', 'Fru'), ('Third', 'yurn'), ('Flip', 13.513353868968)]) OrderedDict([('Items', '9'), ('Itemspaid', 'Rutr'), ('First', 'Het'), ('Second', 'Fru'), ('Third', 'yurn'), ('Flip', 123.513353868968)]) OrderedDict([('Items', '10'), ('Itemspaid', 'Rutr'), ('First', 'Het'), ('Second', 'Fru'), ('Third', 'yurn'), ('Flip', 162.513353868968)]) OrderedDict([('Items', '11'), ('Itemspaid', 'Rutr'), ('First', 'Het'), ('Second', 'Fru'), ('Third', 'yurn'), ('Flip', 213.513353868968)]) Second list printed output: OrderedDict([('planneditems', '1'), ('plannedItemspaid', 'pRutr'), ('PlannedFirst', 'pHet'), ('PlannedSecond', 'pFru'), ('PlannedThird', 'pyurn'), ('Flip', 23.513353868968)]) OrderedDict([('planneditems', '4'), ('plannedItemspaid', 'pRutr'), ('PlannedFirst', 'pHet'), ('PlannedSecond', 'pFru'), ('PlannedThird', 'pyurn'), ('Flip', 113.513353…
tagged with: python
has title: Create a new list from 2 lists after custom sort
upvote count: 0
has comment: http://stackoverflow.com/comment/88246275
has comment: http://stackoverflow.com/comment/88245513
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88245657
score: -1
has comment: http://stackoverflow.com/comment/88245603
has answer: http://stackoverflow.com/a/50619329
has comment: http://stackoverflow.com/comment/88245766
answer count: 1
has comment: http://stackoverflow.com/comment/88246137
favorite count: 0

http://stackoverflow.com/q/50608520
has body: I want to merge two datasets that are indexed by time and id. The problem is, the time is slightly different in each dataset. In one dataset, the time (Monthly) is mid-month, so the 15th of every month. In the other dataset, it is the last business day. This should still be a one-to-one match, but the dates are not exactly the same. My approach is to shift mid-month dates to business day end-of-month dates. Data: dt = pd.date_range('1/1/2011','12/31/2011', freq='D') dt = dt[dt.day == 15] lst = [1,2,3] idx = pd.MultiIndex.from_product([dt,lst],names=['date','id']) df = pd.DataFrame(np.random.randn(len(idx)), index=idx) df.head() output: 0 date id 2011-01-15 1 -0.598584 2 -0.484455 3 -2.044912 2011-02-15 1 -0.017512 2 0.852843 This is what I want (I removed the performance warning): In[83]:df.index.levels[0] + BMonthEnd() Out[83]: DatetimeIndex(['2011-01-31', '2011-02-28', '2011-03-31', '2011-04-29', '2011-05-31', '2011-06-30', '2011-07-29', '2011-08-31', '2011-09-30', '2011-10-31', '2011-11-30', '2011-12-30'], dtype='datetime64[ns]', freq='BM') However, indexes are immutable, so this does not work: In: df.index.levels[0] = df.index.levels[0] + BMonthEnd() TypeError: 'FrozenList' does not support mutable operations. The only solution I've got is to reset_index(), change the dates, then set_index() again: df.reset_index(inplace=True) df['date'] = df['date'] + BMonthEnd() df.set_index(['date','id'], inplace=True) This gives what I want, but is this the best way? Is there a set_level_values() function (I didn't see it in the API)? Or maybe I'm taking the wrong approach to the merge. I could merge the dataset with keys df.index.get_level_values(0).year, df.index.get_level_values(0).month and id but this doesn't seem much better.
tagged with: multi-index
type: AnsweredQuestion
downvote count: 0
has title: Shift time in multi-index to merge
score: 6
favorite count: 0
has answer: http://stackoverflow.com/a/50608785
type: Question
tagged with: pandas
tagged with: python
tagged with: merge
has answer: http://stackoverflow.com/a/50608990
upvote count: 6
possible better answer: http://stackoverflow.com/a/50608704
has answer: http://stackoverflow.com/a/50608704
accepted answer: http://stackoverflow.com/a/50608990
answer count: 3
tagged with: datetimeindex

http://stackoverflow.com/q/50615463
has answer: http://stackoverflow.com/a/50616046
has comment: http://stackoverflow.com/comment/88240867
type: Question
tagged with: nmf
has title: Numpy gives "TypeError: can't multiply sequence by non-int of type 'float'"
score: 5
tagged with: python
answer count: 1
has body: The problematic part is: self.H = np.multiply(self.H, np.divide(np.matmul(preprocessing.normalize(self.W).T, np.multiply(self.X, np.power(self.A, self.beta - 2)))), np.matmul(self.W.T, np.power(self.A, self.beta - 1)) + self.sparsity) A, W, H are Panda dataframes. Beta and sparsity are integers. Their initialization are: self.W = pd.DataFrame(np.random.randint(100,size=(self.X.shape[0], self.K))) self.H = pd.DataFrame(np.random.randint(0,100,size=(self.K, self.X.shape[1]))) self.W = preprocessing.normalize(self.W) self.A = self.W.dot(self.H)
tagged with: scipy
accepted answer: http://stackoverflow.com/a/50616046
tagged with: numpy
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/88240939
tagged with: matrix
type: AnsweredQuestion
favorite count: 0

http://stackoverflow.com/a/50672898
has body: The any is redundant, you can do this with just isnull/isna and sum: v = df.isna().sum().lt(300) df[v.index[v]] Or, df.loc[:, df.isna().sum().lt(300)]
upvote count: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50672875
score: 1

http://stackoverflow.com/comment/88107413
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50544593
has text: @jotaen, I speculated about a possible answer in a comment. After Joe confirmed that it worked, I edited the question title and tags to to add IPython and moved my comment to an answer.

http://stackoverflow.com/a/51414104
answers question: http://stackoverflow.com/q/50591068
has body: You need to use a bunch of libvlc calls, not sure what those are with your python wrapper but they should be exposed on the mediaplayer object. https://www.videolan.org/developers/vlc/doc/doxygen/html/group__libvlc__media__player.html#gae46128c21d0d0151aca3ba017d1d6b35 https://www.videolan.org/developers/vlc/doc/doxygen/html/group__libvlc__media__player.html#ga2189c9deefc2154ddc5d5f1871b0a106 https://www.videolan.org/developers/vlc/doc/doxygen/html/group__libvlc__media__player.html#ga193de3e82f6de3f9d8f5ccd8b5f2aa98 https://www.videolan.org/developers/vlc/doc/doxygen/html/group__libvlc__media__player.html#ga024c0f0bba9d3b32a881c40f3cb479bb You need to setup and use these callbacks. C# example using those APIs: https://github.com/ZeBobo5/Vlc.DotNet/blob/develop/src/Vlc.DotNet.Wpf/VlcVideoSourceProvider.cs
score: 0
type: Answer

http://stackoverflow.com/a/64539303
type: Answer
answers question: http://stackoverflow.com/q/50692772
has body: You can always check the status of AWS services and their availability in different regions before using at https://status.aws.amazon.com/.
score: 0

http://stackoverflow.com/q/50687548
tagged with: firebase-admin
score: 0
tagged with: python
favorite count: 0
tagged with: firebase-realtime-database
upvote count: 1
downvote count: 1
tagged with: firebase
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50687595
has title: What is this generated string in firebase?
type: Question
accepted answer: http://stackoverflow.com/a/50687595
has body: I have a mqtt subscriber in python that listens for ESP8266's in different rooms posting their temperature. When they post the temperature I add the data to firebase using the following: // msq.topic == room name // msq.payload is the temperature root.child(msq.topic).push( { 'temperature' : msg.payload.decode("UTF-8"), 'date_time' : str(datetime.now() } ) When I get the data in firebase it looks like this: What is LEB9y19SraBRSGxamvp or where does it come from? (and the other unique ID's) Can I change it to something more meaningful so that it is easier to get data from firebase? Or have I possibly designed this badly? Has anyone any suggestions to make it better?
answer count: 1

vscode-debugger
type: Tag
tags question: http://stackoverflow.com/q/50601935
tag name: vscode-debugger

http://stackoverflow.com/q/50671010
accepted answer: http://stackoverflow.com/a/50671067
upvote count: 1
has body: I am working on a database program that stores objects in a pickle file. The objects have three attributes: Name, Grade, and Average. I have been able to save each Student object to a pickle file, and I can read the file back and display it's contents. However, I cannot figure out how to delete an object from the file using an index number. I want the user to be able to type in a number, and then delete that numbered object (so if I type in 2, the second object is deleted.) Right now my code is able to delete an item from a pickle list, but I cannot get it to work with an object. When I try to delete a student, I get the following error: TypeError: 'Student' object does not support item deletion. Does anyone know how I could delete an object from my pickle file? My code is below: import pickle class Student(): def __init__(self,nam,grd,avg): self.name = nam self.grade = grd self.average = avg def get_details(self): print(self.name, self.grade, self.average) def create_item(): new_student = Student(input("Enter name: "),input("Enter grade: "), input("Enter average: ")) save_object(new_student, 'student_data.pkl') def clear_database(): file = open('student_data.pkl', 'w') file.close() def save_object(obj, filename): with open(filename, 'ab') as output: pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL) def unpickle_database(filename): with open(filename, 'rb') as f: while True: try: yield pickle.load(f) except EOFError: break def display_database(): print("\nName: Grade: Average: ") for student in unpickle_database('student_data.pkl'): property_list = [student.name, student.grade, student.average] print(''.join([v.ljust(20,' ') for v in property_list])) def delete_student(student_to_delete): with open('student_data.pkl', 'rb') as f: db = pickle.load(f) try: del db[student_to_delete] except KeyError: print("{user} doesn't exist in db".format(user=user_to_delete)) while True: user_input = input("\nType \"Clear\" to clear the database. Type \"Add\" to add a student. Type …
has title: How to remove an object stored in a Pickle file with Python
type: Question
tagged with: object
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50671067
favorite count: 0
tagged with: pickle
tagged with: python
type: AnsweredQuestion
score: 1

http://stackoverflow.com/a/50594892
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/88212029
accepted answer of: http://stackoverflow.com/q/50594198
has comment: http://stackoverflow.com/comment/88212673
upvote count: 3
answers question: http://stackoverflow.com/q/50594198
type: AcceptedAnswer
type: Answer
has body: mysql.connect() use current_app everywhere, so you have to call it inside of application context. Method 1: Push an application context temporarily with app.app_context(): cur = mysql.connection.cursor() Normally, you needn't create the global object. Instead, you can create cur object inside view function. Method 2: Call it inside view function @app.route('/') def users(): cur = mysql.connection.cursor() cur.execute('''SELECT user, host FROM mysql.user''') rv = cur.fetchall() return str(rv) If you have a bunch of view functions use this object, you can create a before request handler to create it. Method 3: Call it in before_request function, then you can access cur in all the view function directly @app.before_request def make_db(): cur = mysql.connection.cursor()

http://stackoverflow.com/comment/88192231
type: QuestionComment
has text: I believe I need to introduce a poller to poll SQS whereas SNS would be able to push message and invoke lambda.
score: 0
comment on: http://stackoverflow.com/q/50591308
type: Comment

http://stackoverflow.com/q/50573241
has comment: http://stackoverflow.com/comment/88156059
upvote count: 2
tagged with: http://stackoverflow.com/tag/r
tagged with: jupyter
favorite count: 0
type: UnansweredQuestion
has body: Here is my piece of code and i am installing R library RPostgreSQL in python import rpy2.robjects as robjects import rpy2.robjects.packages as rpackages utils = rpackages.importr('utils') utils.install_packages('RPostgreSQL') but it gives errors : RRuntimeError Traceback (most recent call last) &lt;ipython-input-7-04e0baa1a451&gt; in &lt;module&gt;() ----&gt; 1 utils.install_packages('RPostgreSQL') c:\users\postgres\appdata\local\programs\python\python36\lib\site- packages\rpy2\robjects\functions.py in __call__(self, *args, **kwargs) 176 v = kwargs.pop(k) 177 kwargs[r_k] = v --&gt; 178 return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs) 179 180 pattern_link = re.compile(r'\\link\{(.+?)\}') c:\users\postgres\appdata\local\programs\python\python36\lib\site- packages\rpy2\robjects\functions.py in __call__(self, *args, **kwargs) 104 for k, v in kwargs.items(): 105 new_kwargs[k] = conversion.py2ri(v) --&gt; 106 res = super(Function, self).__call__(*new_args, **new_kwargs) 107 res = conversion.ri2ro(res) 108 return res RRuntimeError: Error in (function (pkgs, lib, repos = getOption("repos"), contriburl = contrib.url(repos, : unable to install packages I have tried many suggestions, and this is my .libpaths and library postgresql is installed in both. Any help ? RStudio "C:/Users/postgres/R/win-library/3.5" "C:/Program Files/R/R-3.5.0/library"
tagged with: python
has comment: http://stackoverflow.com/comment/88156166
score: 2
has comment: http://stackoverflow.com/comment/88156087
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/88156106
has title: rpy2 - unable to install R packages
type: Question
tagged with: rpy2

http://stackoverflow.com/q/50573857
has comment: http://stackoverflow.com/comment/88164712
type: UnansweredQuestion
tagged with: facebook
tagged with: django
tagged with: python
answer count: 0
linked to: http://stackoverflow.com/q/50062703
duplicate of: http://stackoverflow.com/q/50062703
type: Question
score: 0
tagged with: sdk
tagged with: api
has comment: http://stackoverflow.com/comment/88158056
has title: publish_actions permission in facebook sdk for python
has body: I am working on app in django 1.11 with facebook-sdk (v. 2.12 for facebook). I have problem with added permissions to publish content on wall. I got an error: (#200) Requires either publish_actions permission, or manage_pages and publish_pages as an admin with sufficient administrative permission Below is my code: settings.py SOCIAL_AUTH_FACEBOOK_KEY = '###########' SOCIAL_AUTH_FACEBOOK_SECRET = '############' SOCIAL_AUTH_FACEBOOK_API_VERSION = '2.12' code in view.py from social_django.models import UserSocialAuth import facebook facebook_login = UserSocialAuth.objects.get(provider='facebook') oauth_token = facebook_login.extra_data["access_token"] graph = facebook.GraphAPI(oauth_token, version="2.12") profile = graph.get_object(facebook_login.extra_data['id']) graph.put_object(parent_object='me', connection_name='feed', message='Hello, world - test :)') I got an error in last line: graph.put_object(parent_object='me', connection_name='feed', message='Hello, world - test :)')

http://stackoverflow.com/comment/88112691
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50550830
has text: You should include the desired output, especially for things that repeat themselves and for people with multiple roles.

http://stackoverflow.com/comment/88186095
comment on: http://stackoverflow.com/q/50587433
score: 0
type: Comment
type: QuestionComment
has text: ok thank you for the advice, you are right I should figure it out on my own as a learning exercise. i will reply to your comment again when I figure it out!

http://stackoverflow.com/comment/88240219
has text: See https://stackoverflow.com/questions/50425492/django-2-0-tutorial-pt-1-error-404-url-conf-probelm
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50613957
score: 0

http://stackoverflow.com/comment/88352254
type: Comment
type: AnswerComment
has text: https://stackoverflow.com/questions/18817396/what-part-of-speech-does-s-stand-for-in-wordnet-synsets
comment on: http://stackoverflow.com/a/50653989
score: 0

http://stackoverflow.com/a/50824986
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50630668
upvote count: 1
has body: Cloud Datastore (GCD) stores data objects as entities, which may have one or more properties. In your case the property value type is a string 'abc'. However each entity is identified by a key which is a unique identifier within your app's datastore. So in your case you would need to create a key for object my_ds and also define a model class. That could be Handler1 (e.g. class Handler1(ndb.Model): #your code) which defines the property you are trying to call. Additionally, you cannot expect the value to be updated without using the put() function (e.g. my_ds.put() ). In order to use the second handler (Handler2) to create a new object and set the values of the properties you need to learn a bit more about using Webapp2 request handler. I also suggest you follow this tutorial to get started.
type: Answer

http://stackoverflow.com/q/50649919
type: UnansweredQuestion
tagged with: django
upvote count: 1
has body: I am using celery==4.1.1 in my project. In my settings.py, I have the following: from celery.schedules import crontab CELERY_BROKER_URL = "redis://127.0.0.1:6379/1" CELERY_TIMEZONE = 'Asia/Kolkata' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_RESULT_BACKEND = "redis://127.0.0.1:6379/1" CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'mathematica.core.tasks.another_test', 'schedule': crontab(minute=45, hour=00) }, 'task-number-two': { 'task': 'mathematica.core.tasks.test', 'schedule': crontab(hour='*/1') } } The second task mentioned in CELERY_BEAT_SCHEDULE is running perfectly. However, the first task mathematica.core.tasks.another_test which is a simple function returning a string is not running at the specified time, 00:45 (45 minutes past midnight). I have tried a number of ways to run a function at a given time each day but failed to achieve the same. Please suggest ways/hints to achieve the same results.
has comment: http://stackoverflow.com/comment/88310734
tagged with: celery
type: Question
has title: Django Celery Periodic Task at specific time
has comment: http://stackoverflow.com/comment/88329701
score: 1
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51061881

http://stackoverflow.com/a/50655184
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88320534
upvote count: 2
type: Answer
score: 2
has body: You can use the globals function to get the dictionary representing the global scope, and update it: def init_range(lower, upper): globals().update(lower=lower, upper=upper)
accepted answer of: http://stackoverflow.com/q/50655078
answers question: http://stackoverflow.com/q/50655078
downvote count: 0

http://stackoverflow.com/comment/88299896
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50644578
has text: @bipll Even if he didn't use it, I think it is Pythonic. Isn't it?

http://stackoverflow.com/comment/88389414
type: QuestionComment
has text: Why is your Python code in a folder named `perl`, in a file with the extension `.txt`?
score: 2
comment on: http://stackoverflow.com/q/50689857
type: Comment

kinect
type: Tag
tags question: http://stackoverflow.com/q/50674602
tag name: kinect

http://stackoverflow.com/a/50548199
answers question: http://stackoverflow.com/q/50548122
downvote count: 0
score: 1
type: Answer
upvote count: 1
has body: One idea is to iterate characters in your string pairwise using zip (or itertools.zip_longest) and yield an item depending on whether the character is a digit. from itertools import zip_longest, islice foo = '2 hs4q q2w2 ' def gen(x): for i, j in zip_longest(x, islice(x, 1, None), fillvalue=''): if i.isdigit(): yield j * (int(i)-1) else: yield i res = ''.join(list(gen(foo))) # ' hsqqqq qww '

http://stackoverflow.com/a/55142896
upvote count: 2
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/50556604
answers question: http://stackoverflow.com/q/50556604
has comment: http://stackoverflow.com/comment/130682301
type: AcceptedAnswer
downvote count: 0
has body: Based on Fred C's answer, I came up with this solution: from docx.oxml import OxmlElement from docx.oxml.ns import qn def indent_table(table, indent): # noinspection PyProtectedMember tbl_pr = table._element.xpath('w:tblPr') if tbl_pr: e = OxmlElement('w:tblInd') e.set(qn('w:w'), str(indent)) e.set(qn('w:type'), 'dxa') tbl_pr[0].append(e)

http://stackoverflow.com/comment/88143938
comment on: http://stackoverflow.com/q/50566754
score: 0
type: QuestionComment
type: Comment
has text: Thanks for the edit and comment--they do answer my questions. However, if you want to continue asking questions here, you really should show the desired output from your example input, as explained in [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). Your first question is pretty good, otherwise.

http://stackoverflow.com/q/50695467
has answer: http://stackoverflow.com/a/50696725
has title: How to take only(.*)
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50696204
tagged with: python
has answer: http://stackoverflow.com/a/50695771
has comment: http://stackoverflow.com/comment/88401929
has comment: http://stackoverflow.com/comment/88400363
type: Question
has comment: http://stackoverflow.com/comment/88400257
has body: I have a loop in python and in every iteration the program is reading text from the console. In this text there is an Id of characters. The message that I am reading is "Your project is ready. Your ID: dfgdfgfd" So the id will be different in every iteration. After every iteration the ID should go to a list outside the loop. I am trying this, but i think that there is a better way, just to take the ID in (.*) and to append it in a list of ID's, not to take the line and to split it and to take the [6], just to take the Id and to append it. import os import sys import re ListOfProjects={projectA, projectB, projectC, projectE} List_Of_Ids=[] for x in ListOfProjects: IdFullText=sys.stdin.readline() Id=re.compile(r'Your project is ready. Your ID: (.*)') matches = Id.finditer(IdFullText) List_Of_Ids.append(Matches) I want to take in a list only the id, that is different in every iteration. The sentence "Your project is ready. Your ID:" is always the same, but the id in the () will be different every time, like "dfsdf" or 'dsgfsdvc'. I need only this chars
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/88404134

http://stackoverflow.com/comment/88282506
has text: Thanks, I changed it but now another error appears.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50636302

http://stackoverflow.com/a/50691839
score: 2
downvote count: 0
has body: def peak_detect (y_, threshold=100): indicesList = [] for i in range(1, len(y_)): #Range skips 1st element if abs(y[i] - y[i-1]) &gt; threshold: indicesList.append(i) return(indicesList)
answers question: http://stackoverflow.com/q/50691805
upvote count: 2
type: Answer

http://stackoverflow.com/q/50695038
has answer: http://stackoverflow.com/a/50695209
has comment: http://stackoverflow.com/comment/88410465
tagged with: loops
has comment: http://stackoverflow.com/comment/88399456
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88399426
has comment: http://stackoverflow.com/comment/88399348
has title: python For-loop fails when I tried to write a function with it in
has comment: http://stackoverflow.com/comment/88399357
has comment: http://stackoverflow.com/comment/88399405
has comment: http://stackoverflow.com/comment/88410516
has comment: http://stackoverflow.com/comment/88410560
score: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88438431
has comment: http://stackoverflow.com/comment/88399904
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88410593
has comment: http://stackoverflow.com/comment/88399352
has comment: http://stackoverflow.com/comment/88399794
has comment: http://stackoverflow.com/comment/88399354
has comment: http://stackoverflow.com/comment/88410570
has body: As a Python learner (version 2.7, 32 bit), I wrote a function with the loop in a python file named year.py like the following. But the loop doesn't work in Python compiler. def fun(a): a_year = a + 7 b = [a_year, a_year + 9, a_year + 2*9, a_year + 3*9] for i in b: return "Your years are: %d" % i If I run the function in Python compiler like this: import year year.fun(1980) Your years are: 1987 My question is, How should I make it return as following? import year year.fun(1980) Your years are: 1987 Your years are: 1996 Your years are: 2005 Your years are: 2014 Thank you.
has comment: http://stackoverflow.com/comment/88410725
has comment: http://stackoverflow.com/comment/88434767
has comment: http://stackoverflow.com/comment/88435360

http://stackoverflow.com/q/50602137
tagged with: python-multiprocessing
type: Question
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88217323
tagged with: python-3.6
tagged with: optimization
has answer: http://stackoverflow.com/a/50611313
has title: Python Multithread/process to fill in matrix with values
linked to: http://stackoverflow.com/q/3044580
accepted answer: http://stackoverflow.com/a/50611313
favorite count: 0
tagged with: multithreading
has comment: http://stackoverflow.com/comment/88214135
upvote count: 1
tagged with: python
type: AnsweredQuestion
has body: I have this code below, I already optimised the algorithm to make it as fast as possible but it is still too slow. So a was thinking about using multiprocessing (I have no expierience with this kind of stuff), but I tried some things with pool and threading but either it was slower than before or didn't work. So is was wondering how I should do this so that it works and is faster. And if there are other options than multithreading to make kind of code this faster. def calc(indices, data): matrix = [[0] * len(indices) for i in range(len(indices))] for i_a, i_b in list(itertools.combinations(indices, 2)): a_res, b_res = algorithm(data[i_a], data[i_b]) matrix[i_b][i_a] = a_res matrix[i_a][i_b] = b_res return matrix def algorithm(a,b): # Verry slow and complex
score: 1
possible better answer: http://stackoverflow.com/a/50605313
has answer: http://stackoverflow.com/a/50605313

http://stackoverflow.com/q/50689854
possible better answer: http://stackoverflow.com/a/50689926
has answer: http://stackoverflow.com/a/50689926
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/50689931
has body: I'm implementing a game which allows two players to pick alternately from a pile of 27 sticks. Each player may take 1, 2, or 3 sticks on each turn; the player forced to take the final stick loses. I've done most of the code, but I must include validation. Besides taking 1-3 sticks, a player is not allowed to take the final stick. I've tried using a continue statement, but when player two exceeds the limit, the program returns to player 1's turn. Here's what I have so far: count = 27 T = False F = False while count &gt; 1: Playerone = int(input("Player 1's Turn, Enter from 1-3")) if Playerone &lt; 1 or Playerone &gt; 3: print("Error") continue count -= Playerone print(count) if count == 1: print("P1 wins") break if count &lt; 1: print("You can't pick up those many sticks") continue Playertwo = int(input("Player 2's Turn, Enter from 1-3")) if Playertwo &lt; 1 or Playertwo &gt; 3: print("Error") continue count -= Playertwo print(count) if count == 1: print("P2 wins") break if count &lt; 1: print("You can't pick up those many sticks") continue The last if statement is the issue Help would be much appreciated,
tagged with: python
has comment: http://stackoverflow.com/comment/88389495
has title: How do I clear a variable after an if statement?
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/88389573
has comment: http://stackoverflow.com/comment/88389568
accepted answer: http://stackoverflow.com/a/50689931
has answer: http://stackoverflow.com/a/50690182

http://stackoverflow.com/q/50585210
downvote count: 3
tagged with: selenium
tagged with: loops
has comment: http://stackoverflow.com/comment/88179588
type: Question
upvote count: 0
answer count: 1
has title: Loop selenium python
has body: I'm trying to do this thing, I have a list of elements all equal, but if i create a loop that have to click on all the element it stops at the first one and clicking it infinite times, i don0t know how to pass to the next becouse the doesn't have difference on click or in other way. What can i do? This is the loop a=0 while a < 3: driver.find_element_by_xpath("/html/body/span/section/main/section/div[1]/div[1]/div/article[1]/div[2]/section[3]/form/textarea").click() driver.find_element_by_css_selector("textarea._bilrf").send_keys("hi!", Keys.ENTER) a += 1 And this the element
score: -3
has comment: http://stackoverflow.com/comment/88179657
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50585289

http://stackoverflow.com/a/50544576
has comment: http://stackoverflow.com/comment/88100500
upvote count: 3
has comment: http://stackoverflow.com/comment/88100372
has body: First, a couple of general comments. The main parser handles the input upto the subparser invocation, then the subparser is called and given the remaining argv. When it is done, it's namespace is merged back into the the main namespace. The parents mechanism copies Actions from the parent by reference. So your main and subparsers share the same verbose Action object. That's been a problem when the subparser tries to set a different default or help. It may not be an issue here, but just keep it in mind. Even without the parents mechanism, sharing a dest or options flag between main and subparser can be tricky. Should the default of the subparser Action be used? What if both are used? Does the subparser overwrite the main parser's actions? Originally the main namespace was passed to the subparser, which it modified and returned. This was changed a while back (I can find the bug/issue if needed). Now the subparser starts with a default empty namespace, fills it. And these values are then merged into the main. So in your linked SO question, be wary of older answers. argparse may have changed since then. I think what's happening in your case is that the main and subparser verbose are counting separately. And when you get None it's the subparser's default that you see. The __call__ for _Count_Action is: def __call__(self, parser, namespace, values, option_string=None): new_count = _ensure_value(namespace, self.dest, 0) + 1 setattr(namespace, self.dest, new_count) I suspect that in older argparse when the namespace was shared, the count would have been cumulative, but I can't test it without recreating an older style subparser action class. https://bugs.python.org/issue15327 - here the original developer suggests giving the two arguments different dest. That records the inputs from both main and sub. Your own code can then merge the results if needed. https://bugs.python.org/issue27859 argparse - subparsers does not retain namespace. Here I suggest a way of recreating the …
has comment: http://stackoverflow.com/comment/88100265
has comment: http://stackoverflow.com/comment/88100407
score: 3
has comment: http://stackoverflow.com/comment/88100199
accepted answer of: http://stackoverflow.com/q/50543820
has comment: http://stackoverflow.com/comment/88100307
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50543820
type: Answer

http://stackoverflow.com/a/50646951
score: 1
has comment: http://stackoverflow.com/comment/88304519
answers question: http://stackoverflow.com/q/50646910
has comment: http://stackoverflow.com/comment/88304771
upvote count: 1
has body: You can use filter: list1 = [{'numeric_id': 1, 'ref': 'link1'}, {'numeric_id': 2, 'ref': 'link2'}, {'numeric_id': 3, 'ref': 'link3'}, {'numeric_id': 4, 'ref': 'link4'}, {'numeric_id': 5, 'ref': 'link5'}] list2 = [{'numeric_id': 1, 'ref': 'link1'}, {'numeric_id': 2, 'ref': 'link2'}, {'numeric_id': 4, 'ref': 'link4'}, {'numeric_id': 5, 'ref': 'link5'}] new_list1 = list(filter(lambda x:any(c['numeric_id'] == x['numeric_id'] for c in list2), list1)) new_list2 = list(filter(lambda x:any(c['numeric_id'] == x['numeric_id'] for c in list1), list2)) Output: [{'numeric_id': 1, 'ref': 'link1'}, {'numeric_id': 2, 'ref': 'link2'}, {'numeric_id': 4, 'ref': 'link4'}, {'numeric_id': 5, 'ref': 'link5'}] [{'numeric_id': 1, 'ref': 'link1'}, {'numeric_id': 2, 'ref': 'link2'}, {'numeric_id': 4, 'ref': 'link4'}, {'numeric_id': 5, 'ref': 'link5'}]
type: Answer
has comment: http://stackoverflow.com/comment/88304590
downvote count: 0

http://stackoverflow.com/comment/88112066
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50550549
type: Comment
has text: Yes, but it did something completely different than yours.

http://stackoverflow.com/comment/88103757
has text: Thx for the simple and fast answers , helped me alot.
type: Comment
comment on: http://stackoverflow.com/a/50545975
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88247034
score: 1
comment on: http://stackoverflow.com/q/50618573
has text: What is the shape of y_train ?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50670173
downvote count: 0
score: 16
favorite count: 0
accepted answer: http://stackoverflow.com/a/50670201
possible better answer: http://stackoverflow.com/a/62614817
tagged with: django
has title: Import model from another app Django
has answer: http://stackoverflow.com/a/62614817
tagged with: python
has body: I have a problem importing a model from another app. I am using Django 2.0. My project structure looks like this: --api --api --settings.py --urls.py --wsgi.py --product --models.py --chat --models.py --manage.py To show only the problem I have I simplified the structure. If you are missing something important let me know it. The file causing the error: chat/models.py from api.product.models import Product from django.contrib.auth.models import User from django.db import models class Chat(models.Model): product = models.ForeignKey(Product) enquirer = models.ForeignKey(User) product/models.py from django.db import models from django.contrib.auth.models import User class Product(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, related_name='category', on_delete=None) front_image = models.ImageField(upload_to="") title = models.CharField(max_length=100) price = models.PositiveIntegerField() description = models.CharField(max_length=5000) date = models.DateTimeField(auto_now_add=True) settings.py INSTALLED_APPS = [ 'account.apps.AccountConfig', 'product.apps.ProductConfig', 'profileInfo.apps.ProfileInfoConfig', 'chat.apps.ChatConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', ] The error is the following: ModuleNotFoundError: No module named 'api.product' I do not understand why Django even can not find api.product. Is that a common problem ? Thank you for your help.
upvote count: 16
has comment: http://stackoverflow.com/comment/88350107
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50670201
type: Question
answer count: 2

http://stackoverflow.com/q/50643808
tagged with: django
downvote count: 1
has answer: http://stackoverflow.com/a/50643906
has answer: http://stackoverflow.com/a/50643876
possible better answer: http://stackoverflow.com/a/50643870
has answer: http://stackoverflow.com/a/50643870
has answer: http://stackoverflow.com/a/50644024
tagged with: python-2.7
answer count: 4
score: 2
type: AnsweredQuestion
has title: How to concatenate strings in Python using Format?
tagged with: django-rest-framework
favorite count: 0
accepted answer: http://stackoverflow.com/a/50643876
type: Question
tagged with: python
tagged with: python-3.x
upvote count: 3
has body: I want to send dynamic data in my Payload, payload = "{\r\n \"name\": \"{0}\",\r\n \"id\":\"{1}\"}".format(1,2) *** KeyError: '\r\n "name"' But when i try to add static value it's working fine : payload = "{\r\n \"name\": \"just\",\r\n \"id\":\"32\"}" How can i add dynamic data on it? Thanks in advance.

http://stackoverflow.com/comment/88306641
comment on: http://stackoverflow.com/q/50647756
score: 0
type: Comment
type: QuestionComment
has text: @anishtain4 Sorry I don't get what you mean. The tags are `foo, bar`. Do you mean it should be `foo,,bar`?

http://stackoverflow.com/comment/88382685
type: Comment
comment on: http://stackoverflow.com/a/50685780
score: 0
type: AnswerComment
has text: @user3057109 Not natively, but checkout:https://stackoverflow.com/questions/15675261/displaying-a-tree-in-ascii

http://stackoverflow.com/a/50575550
type: AcceptedAnswer
downvote count: 0
has body: (Assuming you meant n-gram words instead of char), not sure if there is chances of duplicate sentences but you can try set of input sentences and may be list comprehension: %%timeit from nltk import ngrams sentence = ['i have an apple', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'i like apples so much','i have an apple', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'i like apples so much','i have an apple', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'i like apples so much','i have an apple', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'so much'] n_grams = [] for i in range(len(sentence)): for n in range(2, 4): for item in ngrams(sentence[i].split(), n): n_grams.append(item) Result: 1000 loops, best of 3: 228 µs per loop Just using list comprehension, it had some improvement: %%timeit from nltk import ngrams sentence = ['i have an apple', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'i like apples so much','i have an apple', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'i like apples so much','i have an apple', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'i like apples so much','i have an apple', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'i like apples so much', 'so much'] n_grams = [item for sent in sentence for n in range(2, 4) for item in ngrams(sent.split(), n)] Result: 1000 loops, best of 3: 214 µs pe…
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50570511
accepted answer of: http://stackoverflow.com/q/50570511

variables
tags question: http://stackoverflow.com/q/50633189
tag name: variables
tags question: http://stackoverflow.com/q/50690751
tags question: http://stackoverflow.com/q/50644641
tags question: http://stackoverflow.com/q/50667401
tags question: http://stackoverflow.com/q/50589456
type: Tag
tags question: http://stackoverflow.com/q/50695766
tags question: http://stackoverflow.com/q/50580548
tags question: http://stackoverflow.com/q/50592479
tags question: http://stackoverflow.com/q/50595901
tags question: http://stackoverflow.com/q/50594766
tags question: http://stackoverflow.com/q/50543696
tags question: http://stackoverflow.com/q/50675341
tags question: http://stackoverflow.com/q/50616162
tags question: http://stackoverflow.com/q/50554492
tags question: http://stackoverflow.com/q/50567789
tags question: http://stackoverflow.com/q/50646663
tags question: http://stackoverflow.com/q/50594324
tags question: http://stackoverflow.com/q/50636379
tags question: http://stackoverflow.com/q/50587901

http://stackoverflow.com/q/50613010
downvote count: 2
type: Question
has title: Passing a C++ object to Python
tagged with: swig
answer count: 2
has comment: http://stackoverflow.com/comment/88267329
score: 30
favorite count: 0
has comment: http://stackoverflow.com/comment/88236771
has answer: http://stackoverflow.com/a/50650532
has answer: http://stackoverflow.com/a/50738937
has body: This question is about how to pass a C++ object to a python function that is called in a (C++) embedded Python interpreter. The following C++ class (MyClass.h) is designed for testing: #ifndef MyClassH #define MyClassH #include &lt;string&gt; using std::string; class MyClass { public: MyClass(const string&amp; lbl): label(lbl) {} ~MyClass(){} string getLabel() {return label;} private: string label; }; #endif A python module, exposing the C++ class, can be generated by the following Swig interface file: %module passmetopython %{ #include "MyClass.h" %} %include "std_string.i" //Expose to Python %include "MyClass.h" Below is a Python script using the python module import passmetopython as pmtp def execute(obj): #This function is to be called from C/C++, with a #MyClass object as an argument print ("Entering execute function") lbl = obj.getLabel(); print ("Printing from within python execute function. Object label is: " + lbl) return True def main(): c = pmtp.MyClass("Test 1") retValue = execute(c) print("Return value: " + str(retValue)) #Test function from within python if __name__ == '__main__': main() This question is about how to get the python execute() function working, when called from c++, with a C++ object as an argument. The following C++ program was written to test the functions (minimum amount of error checking): #include "Python.h" #include &lt;iostream&gt; #include &lt;sstream&gt; #include "MyClass.h" using namespace std; int main() { MyClass obj("In C++"); cout &lt;&lt; "Object label: \"" &lt;&lt; obj.getLabel() &lt;&lt; "\"" &lt;&lt; endl; //Setup the Python interpreter and eventually call the execute function in the //demo python script Py_Initialize(); //Load python Demo script, "passmetopythonDemo.py" string PyModule("passmetopythonDemo"); PyObject* pm = PyUnicode_DecodeFSDefault(PyModule.c_str()); PyRun_SimpleString("import sys"); stringstream cmd; cmd &lt;&lt; "sys.path.append(\"" &lt;&lt; "." &lt;&lt; "\")"; PyRun_SimpleString(cmd.str().c_str()); …
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88264543
tagged with: python
has comment: http://stackoverflow.com/comment/88236845
upvote count: 32
tagged with: c++

http://stackoverflow.com/a/50700117
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50666721
type: Answer
has body: Problem solved. Had to terminate the thread with self.thread.terminate() before calling self.server.server_close()
accepted answer of: http://stackoverflow.com/q/50666721

http://stackoverflow.com/q/50574395
accepted answer: http://stackoverflow.com/a/50574501
duplicate of: http://stackoverflow.com/q/47152691
tagged with: jupyter-notebook
favorite count: 0
has answer: http://stackoverflow.com/a/50574502
tagged with: python
type: AnsweredQuestion
has body: I was trying to make a sub totals and grand totals for a data. But some where i stuck and couldn't make my deserved output. Could you please assist on this. data.groupby(['Column4', 'Column5'])['Column1'].count() Current Output: Column4 Column5 2018-05-19 Duplicate 220 Informative 3 2018-05-20 Actionable 5 Duplicate 270 Informative 859 Non-actionable 2 2018-05-21 Actionable 8 Duplicate 295 Informative 17 2018-05-22 Actionable 10 Duplicate 424 Informative 36 2018-05-23 Actionable 8 Duplicate 157 Informative 3 2018-05-24 Actionable 5 Duplicate 78 Informative 3 2018-05-25 Actionable 3 Duplicate 80 Expected Output: Row Labels Actionable Duplicate Informative Non-actionable Grand Total 5/19/2018 219 3 222 5/20/2018 5 270 859 2 1136 5/21/2018 8 295 17 320 5/22/2018 10 424 36 470 5/23/2018 8 157 3 168 5/24/2018 5 78 3 86 5/25/2018 3 80 83 Grand Total 39 1523 921 2 2485 This is a sample data. Could you please have a look with before my ask. I am getting minuted errors. May be i wasn't gave right data. Please kindly check for once. Column1 Column2 Column3 Column4 Column5 Column6 BI Account Subject1 2:12 PM 5/19/2018 Duplicate Name1 PI Account Subject2 1:58 PM 5/19/2018 Actionable Name2 AI Account Subject3 5:01 PM 5/19/2018 Non-Actionable Name3 BI Account Subject4 5:57 PM 5/19/2018 Informative Name4 PI Account Subject5 6:59 PM 5/19/2018 Duplicate Name5 AI Account Subject6 8:07 PM 5/19/2018 Actionable Name1
linked to: http://stackoverflow.com/q/47152691
downvote count: 1
has answer: http://stackoverflow.com/a/50574501
type: Question
possible better answer: http://stackoverflow.com/a/50575012
has answer: http://stackoverflow.com/a/50575012
score: -1
has title: Sub totals and grand totals in Python
answer count: 3
tagged with: pandas
upvote count: 0
has comment: http://stackoverflow.com/comment/88158315

http://stackoverflow.com/comment/88337470
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50663367
has text: Okay, obviously update doesn't install the one you want, so you'll want to compile it and install manually. (see updated answer).
score: 0

http://stackoverflow.com/comment/88229403
type: QuestionComment
has text: Do any of these answers help? https://stackoverflow.com/q/2940858/866021
comment on: http://stackoverflow.com/q/50609790
score: 1
type: Comment

http://stackoverflow.com/comment/88360265
comment on: http://stackoverflow.com/a/50675242
has text: You're missing a bracket at the end of your second line. Also, I don't think your 'or' is placed correctly, you haven't posted two solutions?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88344010
type: Comment
type: QuestionComment
has text: @roganjosh what can be the problem?
comment on: http://stackoverflow.com/q/50667003
score: 0

http://stackoverflow.com/q/50593621
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50593640
tagged with: python
score: 4
answer count: 1
tagged with: dataframe
has title: Pandas: Sort value and ignore 0
has answer: http://stackoverflow.com/a/50593640
upvote count: 4
type: AnsweredQuestion
has body: I've following data: product profit a 32 b 43 c 23 d 34 e 0 f 0 g -14 h -12 i -9 j -8 k -3 I want to sort values and ignore the zero. df.sort_values(by="profit", ascending=False) The expected output should be: product profit b 43 d 34 a 32 c 23 k -3 j -8 i -9 h -12 g -14
downvote count: 0
tagged with: sorting
favorite count: 0
type: Question

http://stackoverflow.com/q/50581172
score: 0
answer count: 3
tagged with: pandas
has body: I have 2 Pandas DataFrames looking like: df1: 0 1 2 3 0.001 0.001 0.001 300 0.002 0.002 0.002 270 ... df2: 0 1 2 3 0.001 0.001 0.001 210 0.002 0.002 0.002 220 ... As column 0, 1 and 2 are always the same I want to subtrct df1.3 with df2.3. like: df3 = df1.3 - df2.3 It doesn't work, but I think it shows what I want to achieve. I want df3 to look like: 0 90 50 ... Any suggestions?
accepted answer: http://stackoverflow.com/a/50581763
has answer: http://stackoverflow.com/a/50581238
possible better answer: http://stackoverflow.com/a/50581249
has comment: http://stackoverflow.com/comment/88171776
tagged with: python
has answer: http://stackoverflow.com/a/50581763
has comment: http://stackoverflow.com/comment/88172244
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50581249
type: Question
has title: Subtract 2 Dataframe columns and save in new DataFrame

http://stackoverflow.com/comment/88347801
type: QuestionComment
has text: In your case an option could be `list(chain.from_iterable(map(word_tokenize, data_corpus)))`.
score: 1
comment on: http://stackoverflow.com/q/50668970
type: Comment

http://stackoverflow.com/comment/88377449
has text: my goal is to mock the __Puissance private function by using another one which doesn't the same inherited function's process. I know that the mock is possible if it was a global function or an implementation method.
comment on: http://stackoverflow.com/q/50682674
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50659391
has answer: http://stackoverflow.com/a/50665882
answer count: 3
accepted answer: http://stackoverflow.com/a/50664122
favorite count: 0
tagged with: sockets
tagged with: send
possible better answer: http://stackoverflow.com/a/50659763
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/50659763
type: AnsweredQuestion
tagged with: file
has comment: http://stackoverflow.com/comment/88329754
downvote count: 1
has comment: http://stackoverflow.com/comment/88333942
type: Question
has body: Is it possible to send a dict that contains a file(image or document) as a value through a socket? I tried something like bellow but i failed.. with open("cat.jpeg", "rb") as f: myFile = f.read(2048) data = {"id": "1283", "filename": "cat.jpeg", "file": myFile} dataToSend = json.dumps(data).encode("utf-8") This gives a json error, myFile being a byte array can't be serialized. I tried coverting the myFile into a string using the base64 encode but it didn't worked. What partially worked was casting myFile into a string, like str(myFile). The json serializer worked, i send it through the socket, the dict was ok but the myFile data was corrupted so i couldn't recreate the picture. So is it possible using this approach or how should i send the file and the data through a socket to be easily parsed on the other side? LE: Still doesn't work using base64 encoding, myFile is still "bytes" format and json gives this error: TypeError: Object of type 'bytes' is not JSON serializable Client import os import base64 import json import socket currentPath = os.path.dirname(os.path.abspath(__file__)) + "\\downloads\\" with open(currentPath + "cat.png", "rb") as f: l = f.read() print(type(l)) #prints &lt;class 'bytes'&gt; myFile = base64.b64encode(l) print(type(myFile)) #prints &lt;class 'bytes'&gt; data = {"id": "12", "filename": "cat.png", "message": "So cute!", "file": myFile} dataToSend = json.dumps(data).encode("utf-8") #prints TypeError: Object of type 'bytes' is not JSON serializable s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("127.0.0.1", 1234)) s.sendall(dataToSend) s.close() And the Server: import socket import json import os import sys import time import base64 currentPath = os.path.dirname(os.path.abspath(__file__)) + "\\fileCache\\" tempData = bytearray() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("127.0.0.1", 1234)) s.listen(5) conn, addr = s.accept() while True: dataReceived = conn.recv(2048) if sys.getsizeof(dataReceived) &gt; 1…
has answer: http://stackoverflow.com/a/50664122
score: 3
has comment: http://stackoverflow.com/comment/88328956
has title: Send a dictionary containing a file through a socket (python)
upvote count: 4
linked to: http://stackoverflow.com/q/35748549

http://stackoverflow.com/a/50686490
upvote count: 3
downvote count: 1
has comment: http://stackoverflow.com/comment/89007484
has comment: http://stackoverflow.com/comment/89011671
answers question: http://stackoverflow.com/q/50573084
has body: def gap_stat(data,label): k = len(np.unique(label)) n = data.shape[0] p = data.shape[1] D_r = [] C_r = [] for label_number in range(0,k): this_label_index = np.where(label==label_number)[0] temp_sum = 0 pairwise_distance_matrix = euclidean_distances(data[this_label_index],squared=True) D_r.append(np.sum(pairwise_distance_matrix)) C_r.append(float(len(this_label_index))) W_r = np.sum(np.asarray(D_r)/(2*np.asarray(C_r))) gap_stats = np.log(float(p*n)/12)-(2/float(p))*np.log(k)- np.log(W_r) return(gap_stats)
has comment: http://stackoverflow.com/comment/88995007
has comment: http://stackoverflow.com/comment/89273924
type: Answer
has comment: http://stackoverflow.com/comment/88382705
score: 2
has comment: http://stackoverflow.com/comment/89007505
has comment: http://stackoverflow.com/comment/89273888

http://stackoverflow.com/a/73637979
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/50697536
has body: Easier way: df[ (df['column name 1'] == 10) &amp; (df['column name 2'] &gt; 4) ]
score: 0
upvote count: 1

http://stackoverflow.com/a/50657501
has comment: http://stackoverflow.com/comment/88325050
type: Answer
upvote count: 1
score: 1
has body: I think integer division // would do it: df.assign(ranking_class=(df.ranking // 3).astype(int)) club_name tr_begin year ranking ranking_class 0 ADO Den Haag 1357 2010 6.0 2 1 ADO Den Haag 1480 2011 15.0 5 2 ADO Den Haag 1397 2012 9.0 3 3 ADO Den Haag 1384 2013 9.0 3 4 ADO Den Haag 1451 2014 13.0 4
answers question: http://stackoverflow.com/q/50657228
downvote count: 0

http://stackoverflow.com/comment/88204412
type: Comment
type: QuestionComment
has text: No It's not working
comment on: http://stackoverflow.com/q/50597101
score: 0

http://stackoverflow.com/a/50641897
type: Answer
score: 0
has body: The issue isn't so much about how to store a SQLAlchemy object but rather how to store any Object instance. This is from docstring of the pymemcache Client class that you've imported: Values must have a str() method to convert themselves to a byte string. You haven't included a definition of the Users class that you are querying your database with so I can only assume you haven't overridden __str__. Therefore, when pymemcache tries to convert your object into a byte string, it is calling python's default __str__ implementation and storing that.
answers question: http://stackoverflow.com/q/50625163

http://stackoverflow.com/comment/88232934
type: Comment
comment on: http://stackoverflow.com/a/50609751
type: AnswerComment
score: 0
has text: Well get out there and get yourself some rep points. Then come back and revisit this post. Glad I could help.

http://stackoverflow.com/comment/88350261
type: AnswerComment
comment on: http://stackoverflow.com/a/50670176
score: 0
type: Comment
has text: The 2nd time you call Singleton(), why "_instance = None" is not triggered? It is triggered in 1st call. Can you explain this part please? @Jean-François Fabre

http://stackoverflow.com/comment/88244936
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50580209
has text: Link for other question --> https://stackoverflow.com/questions/50617543/how-to-serialize-django-instance-before-save
type: AnswerComment

http://stackoverflow.com/comment/90091575
comment on: http://stackoverflow.com/a/51525098
score: 0
type: Comment
has text: Sure, that's a great use case for the CSV module included in the [Python Standard Library](https://docs.python.org/3.7/library/csv.html). You can easily modify the script to get just a few columns. As the CSV reader keeps them as strings, you can just concatenate them and keep hashing with Adler32.
type: AnswerComment

http://stackoverflow.com/q/50697716
accepted answer: http://stackoverflow.com/a/50697891
tagged with: decision-tree
score: 0
has comment: http://stackoverflow.com/comment/88405041
answer count: 2
has body: I have a data-set about package delivery, with columns such as time of travel, planned shipping time, actual shipping time, delay and planned delivery time. And on the basis of this, I need to predict if the delivery will be on time or not. The following is the data-set: I am planning to use sklearn's LabelEncoder() for categorical features and then fit this data to a DecisionTreeClassifier(). My question is, should I transform the features containing TIME or just leave it? A time value of 1955 means 19:55 and 735 means 07:35. I am using python.
has answer: http://stackoverflow.com/a/50698001
tagged with: prediction
tagged with: classification
tagged with: machine-learning
tagged with: python
has answer: http://stackoverflow.com/a/50697891
possible better answer: http://stackoverflow.com/a/50698001
type: AnsweredQuestion
has title: Binary prediction with data involving starting and ending time
type: Question

http://stackoverflow.com/comment/88177505
has text: Declare it above `if device in row:`
score: 5
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50584191

http://stackoverflow.com/a/50593415
has comment: http://stackoverflow.com/comment/88196468
type: Answer
has comment: http://stackoverflow.com/comment/88196494
upvote count: 1
has body: You could use the same logic you were using, but use the datestrings you are interested in: (df.loc[df['payout'].between('2018-04-01', '2018-04-30'), 'payout'] .dt.to_period('D') .value_counts() .sort_index() .plot(kind="bar") )
score: 1
accepted answer of: http://stackoverflow.com/q/50593341
answers question: http://stackoverflow.com/q/50593341
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50556537
has title: Flatten DataFrame into a single row
accepted answer: http://stackoverflow.com/a/50556569
tagged with: python
upvote count: 14
answer count: 1
tagged with: dataframe
has body: I want to reorganize the following mutli-row DataFrame, 1 2 3 A Apple Orange Grape B Car Truck Plane C House Apartment Garage into this, single-row DataFrame. 1_A 2_A 3_A 1_B 2_B 3_B 1_C 2_C 3_C 0 Apple Orange Grape Car Truck Plane House Apartment Garage Thank you for your help!
has answer: http://stackoverflow.com/a/50556569
score: 14
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/q/50599045
possible better answer: http://stackoverflow.com/a/50599255
tagged with: oop
has answer: http://stackoverflow.com/a/50600307
has answer: http://stackoverflow.com/a/50599255
downvote count: 2
has title: Python: replacing a function within a class of a module
type: Question
upvote count: 40
has answer: http://stackoverflow.com/a/68764656
has answer: http://stackoverflow.com/a/78675488
answer count: 6
tagged with: class
accepted answer: http://stackoverflow.com/a/50600307
tagged with: function
has body: I'm trying to replace a function defined within a class in order to modify its function (as in inner workings) without changing the actual code. I've never done this before, and, hence, am having some problems while replacing it. Changing the code will have me accessing the package within my Python library which is not much of an option. For example, if the module was called testMOD, class testMOD(object): def testFunc(self, variable): var = variable self.something = var + 12 Then I would import testMOD, define a class (mytest = testMOD()), and access the defined function within the class, testFunc, and change it to already defined function. For instance, from somemodule import testMOD mytest = testMOD() def alternativeFunc(self, variable): var = variable self.something = var + 1.2 # A problem here mytest.testFunc = alternativeFunc As you can see, if I just manually overwrite(?) the function in the class with my defined function it won't work properly. It doesn't give any syntax errors, however, the problem is that the replaced function thinks that the 'self' is another variable for the function and says that it requires another argument for the 'variable' variable (I guess that wasn't a good name). I want to make the replacing function to be exactly the same thing as the replaced function, but with additional code or some minor modifications. However, the 'self' is pretty much not working as it should be in a class. Would there be a way to properly implement a defined function to replace a function of an imported class?
favorite count: 0
score: 38
tagged with: python-module
tagged with: python
has answer: http://stackoverflow.com/a/67779209
has answer: http://stackoverflow.com/a/50599174
type: AnsweredQuestion

http://stackoverflow.com/comment/88259923
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50620661
has text: If you're using a decorator to wrap a function, it's way less confusing if you rename the function. For example [here](https://pastebin.com/Ygg27Jae), when you do `print(foo)`, would you rather see `<function wrapper at 0x1234>` or `<function foo at 0x1234>`?
type: AnswerComment

http://stackoverflow.com/a/50664814
type: Answer
has body: Finally, I have divided my file into 100 files each having 0.1 M records and uploaded to the database through this command. FOR /L %i IN (0,1,9) DO ( curl -d @dbn%i.json -H "Content-type: application/json" -X POST http://127.0.0.1:5984/new4/_bulk_docs )
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50662971

http://stackoverflow.com/comment/88150548
type: QuestionComment
has text: in AnotherWindow.Tambahkan, all i want is after 'BtnTambah' is clicked, the ComboBox in MainWindow upadated. nothing's wrong with .show @DiegoContreras
comment on: http://stackoverflow.com/q/50569748
score: 0
type: Comment

http://stackoverflow.com/q/50621387
score: 0
has comment: http://stackoverflow.com/comment/88253592
tagged with: scikit-learn
duplicate of: http://stackoverflow.com/q/46735954
type: UnansweredQuestion
has body: I've completed the training of several regression models for a given dataset, using sklearn. For example, one of them is a RidgeCV regressor (3 input features, 2 output features): reg_1 = sklearn.linear_model.RidgeCV() # fit reg_1 ... print('coef_: {0}'.format(reg_1.coef_)) print('alpha_: {0}'.format(reg_1.alpha_)) coef_: [[0.17864497 0.0852401 0.08863666] [0.17977597 0.09011769 0.08278901]] alpha_: 10.0 I want to include those fitted regressors in production code, but due to several factors (lot of calls, different instances, training data not available...) I don't want / can't train them again. How can I reload the existing regressors? I may guess that I have to somehow copy the private attributes, but it seems a bit rude to do it directly (they are supposed to be private) and I don't know if something else must be done. PS: the other two regressors are KNeighborsRegressor and LinearRegression.
has comment: http://stackoverflow.com/comment/88253294
has comment: http://stackoverflow.com/comment/88253227
tagged with: python
has comment: http://stackoverflow.com/comment/88253165
answer count: 0
linked to: http://stackoverflow.com/q/46735954
has comment: http://stackoverflow.com/comment/88253027
type: Question
has title: How to reload a regressor in sklearn?

http://stackoverflow.com/comment/88393577
has text: AttributeError: 'Person' object has no attribute 'inner_function' Tried with: liz.dance(), same
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50691941

http://stackoverflow.com/q/50569673
downvote count: 0
favorite count: 0
tagged with: windows-7
type: UnansweredQuestion
has title: How do I connect to a Sybase Server using Python 3.1 in Windows 7?
tagged with: python-3.1
tagged with: python
has body: I have thoroughly researched into this topic and I cannot get anything to work. I have tried to run modules I downloaded from this webpage: http://python-sybase.sourceforge.net/download.html The problem is that the latest releases are only supported up to Windows XP Pro. Can anyone help by giving me and many other users in the future some clear installation instructions of what modules they used to get this running? Potential modules include sybpydb, Sybase, pyodbc? SIDE NOTE: Ideally, I'm looking for syntax like this import Sybase db = Sybase.connect('server','name','pass','database') c = db.cursor() c.execute("sql statement") list1 = c.fetchall() print list1
answer count: 0
score: 1
upvote count: 1
type: Question
tagged with: sybase
tagged with: sql

concurrency
tag name: concurrency
tags question: http://stackoverflow.com/q/50685432
tags question: http://stackoverflow.com/q/50599893
tags question: http://stackoverflow.com/q/50561455
type: Tag
tags question: http://stackoverflow.com/q/50623788

http://stackoverflow.com/q/50555464
tagged with: split
has answer: http://stackoverflow.com/a/50555488
has answer: http://stackoverflow.com/a/50555580
accepted answer: http://stackoverflow.com/a/50555488
has comment: http://stackoverflow.com/comment/88154384
score: 2
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/50555580
favorite count: 0
has body: I have a string which I need to split/slice up and set as different variables. Here is an example string: Uploaded 09-09 2015, Size 2.05 GiB, ULed by USERX I need the final output to be something like: date = '09-09 2015' ; size = '2.05' ; user = 'USERX' Here is the code I am using so far, with the variable 'string' representing the original string: date, size, user = string.split(',') date = date.split()[1], date.split()[2] size = size.split()[1] user = user.split()[2] This works, but I can't help but feel that the code is painfully hacky. Is there a better way to do this? Thanks so much, may your code by elegant and error free.
type: Question
upvote count: 2
tagged with: python
tagged with: regex
answer count: 3
has answer: http://stackoverflow.com/a/50555636
has title: How to split a string and select a specific field

http://stackoverflow.com/comment/88297959
comment on: http://stackoverflow.com/q/50643780
has text: Well, for one thing, the first `f = ...` is unnecessary, as you reassign it again in the while loops before using it.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/113101942
has text: Just in case you have None or missing values in one of your dataframes, you need to use `Int64` instead of `int`. See the reference [here](https://pandas.pydata.org/pandas-docs/stable/user_guide/integer_na.html).
type: Comment
comment on: http://stackoverflow.com/a/50649933
score: 3
type: AnswerComment

http://stackoverflow.com/q/50579029
has body: I found multiple (slightly different) ways to define abstract classes in Python. I read the documentation and also could not find an answer here on stackoverflow. The main difference between the three examples (see code below) is: A sets a new metaclass abc.ABCMeta explicitly B inherits from abc.ABC C inherits from objects but defines @abc.abstractmethod classes It seems that A and B are not different (i.e. also B has the new metaclass abc.ABCMeta). However, class C remains of type type. What are the impacts of not defining a metaclass for C? When is it necessary to define the metaclass or is it wrong/bad style to not define the abc.ABCMeta metaclass for an abstract class? Nonetheless, the class C seems to behave as I expect from an ABC. import abc class A(metaclass=abc.ABCMeta): # Alternatively put __metaclass__ = abc.ABCMeta here @abc.abstractmethod def foo(self): raise NotImplementedError class B(abc.ABC): @abc.abstractmethod def foo(self): raise NotImplementedError class C(object): @abc.abstractmethod def foo(self): raise NotImplementedError class Aimpl(A): def foo(self): print("Aimpl") class Bimpl(B): def foo(self): print("Bimpl") class Cimpl(C): #def foo(self): # print("Cimpl") pass Aimpl().foo() # Aimpl print(isinstance(Aimpl, A)) # False print(issubclass(Aimpl, A)) # True print(isinstance(Aimpl, abc.ABCMeta)) # True print(type(A)) # &lt;class 'abc.ABCMeta'&gt; print("---") Bimpl().foo() # Bimpl print(isinstance(Bimpl, B)) # False print(issubclass(Bimpl, B)) # True print(isinstance(Bimpl, abc.ABCMeta)) # True print(type(B)) # &lt;class 'abc.ABCMeta'&gt; print("---") Cimpl().foo() # Cimpl print(isinstance(Cimpl, C)) # False print(issubclass(Cimpl, C)) # True print(isinstance(Cimpl, abc.ABCMeta)) # False print(type(C)) # &lt;class 'type'&gt; print("---")
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50579175
score: 6
tagged with: python
upvote count: 6
accepted answer: http://stackoverflow.com/a/50579175
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/88167290
has title: Differences in three ways to define a abstract class
tagged with: abstract-class

http://stackoverflow.com/comment/88642579
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50676953
has text: This was exactly what I was looking for. BTW, do you know why the function above appends a dot to the name of the header in the first column of my csv? i.e. `".CurrencyType": "Cash"`
score: 0

http://stackoverflow.com/q/50655135
downvote count: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/67715242
has title: how to fix this error : [WinError 267] The directory name is invalid:
has answer: http://stackoverflow.com/a/50655305
score: 1
favorite count: 0
tagged with: qlistwidget
upvote count: 2
type: UnansweredQuestion
tagged with: path
tagged with: python
tagged with: pyqt5
has body: I have a python script that create a GUI application that display a list of existing files after the user select a path. The system display in the QlistWidget fileName and its parentFolder. I want to get the full path of the selected file from the list example : C:\Users\test\Desktop\test_arabic.docx The system display this error : [WinError 267] The directory name is invalid: 'C:\Users\test\Desktop\test_arabic.docx' How to fix this error. Note : I am using self.fullpath variable as a global variable. print("chdir ==&gt; {}".format(os.chdir(PureWindowsPath(self.fullPath)))) the code above is what makes the error. where I am trying to change the current directory path to the selected path of the file. def eventFilter(self, obj, event): try: if self.listWidgetPDFlist.viewport() == obj and event.type() == QtCore.QEvent.MouseMove: #********* it = self.listWidgetPDFlist.itemAt(event.pos()) print("it ==&gt;{}".format(it.text())) ##********* Item=str(it.text()) print("item ==&gt; {}".format(Item)) print("full path ==&gt;{}".format(PureWindowsPath(self.fullPath))) print("chdir ==&gt; {}".format(os.chdir(PureWindowsPath(self.fullPath)))) parentFile =Path().resolve().parent print("parent file ==&gt;{}".format(parentFile)) selectedFile = os.path.join(str(parentFile,Item)) print("selectedFile ==&gt;{}".format(selectedFile)) if self.hoverItem != it: message = selectedFile QtWidgets.QToolTip.showText(QtGui.QCursor.pos(), message, self.listWidgetPDFlist.viewport(), self.listWidgetPDFlist.visualItemRect(it)) self.hoverItem = selectedFile except Exception as e: print(e) return QtWidgets.QMainWindow.eventFilter(self, obj, event)

http://stackoverflow.com/comment/88192117
has text: How did you install Python and Django?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50591127

http://stackoverflow.com/q/50671899
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88353706
tagged with: python
score: 1
has title: why is the output not a float
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88353582
tagged with: arrays
has comment: http://stackoverflow.com/comment/88353988
has body: I am wondering why y is being returned as an array. If it helps, x is a numpy array. I have not gotten to the bit where I have to store the y values in an array yet, but I am trying to find the average of N_obs_photon(t) over a finely scaled grid to give a smoothed graph of N_obs_photon(t) over a coarsely scaled grid. I think that the part with the sum(array)/len(array) should be giving me a float but instead it is returning an array (more correctly 1001 arrays). Even if I try setting x to some array with only one value, y is still being returned as an array. And how should I write it so that I am being given the average for y? x = np.linspace(0,1,1001) ftc = 11 L = 10**(-3) i = x/L j = np.arange(0,11001,1) #end number is max(i)*ftc + 1 '''reference: fine_grid_number = j coarse_grid_number = i coase_grid_width = L fine_grid_width = L/ftc #denominator is ftc coarse_grid_position = i*L fine_grid_position = j*L/ftc #denominator is ftc''' #Plan is to create an array of y values, then plot x vs y for n in i: q = np.arange(-0.5*(ftc-1),0.5*ftc,1) #temp_array = np.empty([]) temp_array = [] for w in q: t = ftc*n + w #t is fine grid number t = t*L/ftc #convert to fine grid position if t &lt; 0: #drop t when it would be less than zero t = 0 temp_array.append(t) #add to array else: t = N_obs_photon(t) #take through function temp_array.append(t) #add to array y = sum(temp_array)/len(temp_array) #average the array print(y) #test if y is a number #store result in y array
upvote count: 1
favorite count: 0
tagged with: python-3.x
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/88149799
has text: Have you tried doing `py` or `python` or `python3` in the console? Maybe it's already in the path.
comment on: http://stackoverflow.com/q/50569960
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88382075
score: 0
type: Comment
type: QuestionComment
has text: I appreciate you letting me know that I had figured it out correctly. Your help has been great!
comment on: http://stackoverflow.com/q/50613848

http://stackoverflow.com/a/50657541
answers question: http://stackoverflow.com/q/50657425
type: AcceptedAnswer
upvote count: 1
type: Answer
has body: Tensorboard 1.7.0 seems to occupy about 150MB on the GPU. See this open Tensorboard issue. Looks like it's in the process of being resolved. An option in the interim is to limit the percentage of memory Tensorflow is allowed to allocate per process upfront as detailed in this answer. This way you can ensure a certain percentage of memory is reserved for other tasks on the GPU that you might want to run during training. gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.8) sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
accepted answer of: http://stackoverflow.com/q/50657425
downvote count: 0
score: 1

http://stackoverflow.com/a/50567559
type: Answer
accepted answer of: http://stackoverflow.com/q/50566754
has body: You could also try something like this: from itertools import takewhile with open('data.txt') as in_file: items = [line.strip() for line in in_file.read().split()] # ['start', 'id=1', 'date=21.05.2018', 'summ=500', 'end', 'start', 'id=7', 'date=23.05.2018', 'summ=500', 'owner=guest'] pos = [i for i, item in enumerate(items) if item == 'start'] # [0, 5] blocks = [list(takewhile(lambda x: x != 'end', items[i+1:])) for i in pos] # [['id=1', 'date=21.05.2018', 'summ=500'], ['id=7', 'date=23.05.2018', 'summ=500', 'owner=guest']] print([dict(x.split('=') for x in block) for block in blocks]) Which Outputs: [{'id': '1', 'date': '21.05.2018', 'summ': '500'}, {'id': '7', 'date': '23.05.2018', 'summ': '500', 'owner': 'guest'}]
score: 0
answers question: http://stackoverflow.com/q/50566754
type: AcceptedAnswer

http://stackoverflow.com/a/58993356
score: 1
answers question: http://stackoverflow.com/q/50654533
upvote count: 1
has body: After installing with --upgrade flag (which upgraded to higher minor version 1.43 -> 1.44) it worked fine pip install --upgrade autopep8
type: Answer
downvote count: 0

http://stackoverflow.com/comment/88424801
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50693223
has text: `Attempted to set non-positive ylimits for log-scale axis; No handles with labels found to put in legend.` With two error messages from your code, it is difficult to give you an advice. I still think that the example in the link does, what you want.

http://stackoverflow.com/comment/88120190
score: 2
type: AnswerComment
has text: Posting answers to trivial typo errors isn't really recommended; these questions are unlikely to help future visitors.
type: Comment
comment on: http://stackoverflow.com/a/50554672

http://stackoverflow.com/comment/88212659
has text: The top answer in the link you provided suggests to use virtual environment and install only the required libraries, which I think is exactly what I'm doing?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50600766
type: AnswerComment

dictionary
tags question: http://stackoverflow.com/q/50643654
tags question: http://stackoverflow.com/q/50698390
tags question: http://stackoverflow.com/q/50610730
tags question: http://stackoverflow.com/q/50631799
tags question: http://stackoverflow.com/q/50565860
tags question: http://stackoverflow.com/q/50564348
tags question: http://stackoverflow.com/q/50681654
tags question: http://stackoverflow.com/q/50643212
tags question: http://stackoverflow.com/q/50635116
tags question: http://stackoverflow.com/q/50593062
tags question: http://stackoverflow.com/q/50643953
tags question: http://stackoverflow.com/q/50600755
tags question: http://stackoverflow.com/q/50563100
tags question: http://stackoverflow.com/q/50584218
tags question: http://stackoverflow.com/q/50689146
tags question: http://stackoverflow.com/q/50682430
tags question: http://stackoverflow.com/q/50556583
tags question: http://stackoverflow.com/q/50658641
tags question: http://stackoverflow.com/q/50585267
tags question: http://stackoverflow.com/q/50552803
tags question: http://stackoverflow.com/q/50631216
tags question: http://stackoverflow.com/q/50670655
tags question: http://stackoverflow.com/q/50648481
tags question: http://stackoverflow.com/q/50639495
tags question: http://stackoverflow.com/q/50596029
tags question: http://stackoverflow.com/q/50621172
tags question: http://stackoverflow.com/q/50567883
tags question: http://stackoverflow.com/q/50648853
tags question: http://stackoverflow.com/q/50684079
tags question: http://stackoverflow.com/q/50566754
tags question: http://stackoverflow.com/q/50641788
tags question: http://stackoverflow.com/q/50653865
tags question: http://stackoverflow.com/q/50646910
tags question: http://stackoverflow.com/q/50548728
tags question: http://stackoverflow.com/q/50546540
tags question: http://stackoverflow.com/q/50618621
tags question: http://stackoverflow.com/q/50680028
tags question: http://stackoverflow.com/q/50615191
tags question: http://stackoverflow.com/q/50590792
tags question: http://stackoverflow.com/q/50562688
tags question: http://stackoverflow.com/q/50561076
tags question: http://stackoverflow.com/q/50556890
tags question: http://stackoverflow.com/q/50615059
tags question: http://stackoverflow.com/q/50666614
tags question: http://stackoverflow.com/q/50586007
tags question: http://stackoverflow.com/q/50644186
tags question: http://stackoverflow.com/q/50579671
tag name: dictionary
tags question: http://stackoverflow.com/q/50613346
tags question: http://stackoverflow.com/q/50594257
tags question: http://stackoverflow.com/q/50684578
tags question: http://stackoverflow.com/q/50607128
tags question: http://stackoverflow.com/q/50690751
tags question: http://stackoverflow.com/q/50574633
tags question: http://stackoverflow.com/q/50670548
tags question: http://stackoverflow.com/q/50684708
tags question: http://stackoverflow.com/q/50564591
tags question: http://stackoverflow.com/q/50573650
tags question: http://stackoverflow.com/q/50653441
tags question: http://stackoverflow.com/q/50694011
tags question: http://stackoverflow.com/q/50581464
tags question: http://stackoverflow.com/q/50569412
tags question: http://stackoverflow.com/q/50681662
tags question: http://stackoverflow.com/q/50644315
tags question: http://stackoverflow.com/q/50628407
tags question: http://stackoverflow.com/q/50559529
tags question: http://stackoverflow.com/q/50656043
tags question: http://stackoverflow.com/q/50652803
tags question: http://stackoverflow.com/q/50620529
tags question: http://stackoverflow.com/q/50638043
tags question: http://stackoverflow.com/q/50593632
tags question: http://stackoverflow.com/q/50683701
tags question: http://stackoverflow.com/q/50665866
tags question: http://stackoverflow.com/q/50690452
tags question: http://stackoverflow.com/q/50575802
tags question: http://stackoverflow.com/q/50606764
tags question: http://stackoverflow.com/q/50563844
tags question: http://stackoverflow.com/q/50580544
tags question: http://stackoverflow.com/q/50611834
tags question: http://stackoverflow.com/q/50693541

http://stackoverflow.com/comment/88456539
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50651053
has text: As I promised, I'm sharing a runnable example (already edited at "Code"). I suggest to use positive integers at the entries. Thank you! PS: I had noticed that the problem is when I use the graph commands. You can comment the code inside the "Graph" function and replace it with "pass" to see what I'm talking about.
score: 0

http://stackoverflow.com/comment/88324167
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50656274
has text: When I try: from linearmodels import FamaMacBeth mod = FamaMacBeth(df['VW'], df['cpi']) res = mod.fit(cov_type='kernel', kernel='Parzen') I get the error:"Series can only be used with a 2-level MultiIndex"
score: 0

http://stackoverflow.com/q/50565663
accepted answer: http://stackoverflow.com/a/50565712
tagged with: loops
answer count: 1
has comment: http://stackoverflow.com/comment/88141497
has body: The below snippet of code has a for loop with csv file names inside the [] brackets. TRAIN_CSV = './train1.csv' # this comtains 100 entries TEST_CSV = './test1.csv' # this contains 50 entries train_df = pd.read_csv(TRAIN_CSV) test_df = pd.read_csv(TEST_CSV) for dataset in [train_df, test_df]: # what does this mean here do something What does the for loop do here when supplied with the csv filenames in the [] brackets ?
has comment: http://stackoverflow.com/comment/88141756
downvote count: 5
type: AnsweredQuestion
upvote count: 0
score: -5
has comment: http://stackoverflow.com/comment/88141806
favorite count: 0
has comment: http://stackoverflow.com/comment/88141705
type: Question
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/50565712
has title: What does for loop with [ ] in python do?

http://stackoverflow.com/comment/88296008
has text: :) your answer is somewhat the same as info in that video that I put as mandatory before re-asking question :) - "when you see class with 2 methods, one of them is __init__ - you know - it's not a class, it's method :D
comment on: http://stackoverflow.com/a/50642473
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50690549
has answer: http://stackoverflow.com/a/70295139
has comment: http://stackoverflow.com/comment/88390931
has comment: http://stackoverflow.com/comment/88391003
has comment: http://stackoverflow.com/comment/88390969
has comment: http://stackoverflow.com/comment/88391130
tagged with: binary-search
has comment: http://stackoverflow.com/comment/88390982
linked to: http://stackoverflow.com/q/34569966
has comment: http://stackoverflow.com/comment/88391004
tagged with: python
has title: How to find multiple values using Binary Search in Python
has body: I am using a standard binary search algorithm that takes an integer value as an argument, and searches through a list for the integer. However, I want to be able to find the indexes of the location of each integer in the list that matches the search value. What I have so far is: def bin_search(x): my_list = [57,68,76,77,82,86,89,89,89,98,100] bottom = 0 top = len(my_list)-1 found = False location = -1 while(bottom &lt;= top) and not(found): middle = int((bottom + top)//2) if(my_list[middle] == x): location = middle found = True else: if x &lt; my_list[middle]: top = middle - 1 else: bottom = middle + 1 return location print(bin_search(89)) Any help in making this binary search able to find two values would be appreciated!
type: Question
has answer: http://stackoverflow.com/a/50691120
score: 0
has comment: http://stackoverflow.com/comment/88391070
has comment: http://stackoverflow.com/comment/88391029
has answer: http://stackoverflow.com/a/60769603
has answer: http://stackoverflow.com/a/57734309
has comment: http://stackoverflow.com/comment/88391020
has comment: http://stackoverflow.com/comment/88391940
has comment: http://stackoverflow.com/comment/88390960
has comment: http://stackoverflow.com/comment/88390989
has comment: http://stackoverflow.com/comment/88390953
has comment: http://stackoverflow.com/comment/88391386
answer count: 4
has comment: http://stackoverflow.com/comment/88391102
has comment: http://stackoverflow.com/comment/88390956
type: UnansweredQuestion

http://stackoverflow.com/comment/104371615
has text: Hi, thank you for your suggestions on this, but why exactly would you suggest two different Serializers?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50635445

http://stackoverflow.com/a/50633389
accepted answer of: http://stackoverflow.com/q/50633124
answers question: http://stackoverflow.com/q/50633124
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88277391
has body: As a complement to chepner's answer, this C++ code exhibits the exact same behaviour as you have in Python: #include &lt;iostream&gt; class B { public: void test() { call(); } virtual void call() { std::cout &lt;&lt; "Called from B" &lt;&lt; std::endl; } }; class C: public B { public: void call() { std::cout &lt;&lt; "Called from C" &lt;&lt; std::endl; } }; int main() { C c; c.test(); // will print Called from C return 0; } If you come from C++ think that all members are public, and all methods virtual.
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/88277075

http://stackoverflow.com/a/50588095
downvote count: 0
answers question: http://stackoverflow.com/q/50588059
score: 3
has body: This is one way using pd.Series.apply: df['ranks'] = df['ranks'].apply(lambda x: x[0]['rank']) df['search_volume'] = df['search_volume'].apply(lambda x: x['search_volume']) This assumes your ranks series contains lists, and your search_volume series contains dictionaries.
type: AcceptedAnswer
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/50588059

http://stackoverflow.com/q/50663331
has body: I try to download blackwidow.git and i set it up like katoolin: $ git clone https://github.com/1N3/BlackWidow.git &amp;&amp; cp BlackWidow/BlackWidow.py /usr/bin/BlackWidow But I get an error message: cp: cannot stat 'BlackWidow/BlackWidow.py': No such file or directory What is this error caused by (note: both katoolin and blackwidow are written in python)?
downvote count: 4
answer count: 1
favorite count: 0
has title: Why does git clone fail to stat files on Linux Mint?
type: UnansweredQuestion
tagged with: python
upvote count: 0
score: -4
has answer: http://stackoverflow.com/a/50663366
tagged with: git
type: Question

http://stackoverflow.com/q/50565322
has answer: http://stackoverflow.com/a/50574746
downvote count: 0
has comment: http://stackoverflow.com/comment/88146749
type: AnsweredQuestion
has title: Why did the numpy core size shrink from 1.14.0 to 1.14.1?
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88144588
accepted answer: http://stackoverflow.com/a/50574746
type: Question
has body: When creating an AWS lambda package I noticed that the ZIP became a lot smaller when I updated from numpy 1.14.0 to 1.14.3. From 24.6MB to 8.4MB. The directory numpy/random went from 4.3MB to 1.2MB, according to Ubuntus Disc Usage analyzer. When I, however, compare the directories with meld they seem to be identical. So I had a closer look at this and found that only one file (mtrand.cpython-36m-x86_64-linux-gnu.so) differs that much. I guess it is a similar reason why the core became smaller. Could somebody explain why this became so much smaller?
has comment: http://stackoverflow.com/comment/88141005
tagged with: python
has comment: http://stackoverflow.com/comment/88145349
answer count: 1
tagged with: shared-libraries
upvote count: 1
tagged with: numpy

http://stackoverflow.com/q/50697041
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88405385
tagged with: netcdf4
has comment: http://stackoverflow.com/comment/88403290
answer count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/88404027
has body: I'm trying to access a NASA TRMM dataset through netcdf. However, after installing various packages, I still get stuck on ncdump, which I need to analyse the structure of the data in the given file (following this example) . I'm running it on jupyter notebook and my code is as follows: import gdal import urllib import netCDF4 as nc import datetime as dt #Python standard library datetime module import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid url = 'https://disc2.gesdisc.eosdis.nasa.gov:443/opendap/TRMM_L1/TRMM_1B11/2015/001/1B11.20150101.97563.7.HDF'; ncfile = nc.Dataset(url, "r"); ncdump -k ncfile Resulting in a Syntax Error (invalid syntax). Any tips or advice?
has title: Invalid syntax ncdump for netcdf python
downvote count: 0
tagged with: jupyter-notebook
favorite count: 0

http://stackoverflow.com/a/50601255
score: 3
has comment: http://stackoverflow.com/comment/88258124
accepted answer of: http://stackoverflow.com/q/50600624
has body: Here is a solution that uses Sequence which acts like a generator in Keras: class MySequence(Sequence): def __init__(self, num_batches): self.num_batches = num_batches def __len__(self): return self.num_batches # the length is the number of batches def __getitem__(self, batch_id): return get_batch(data, batch_id, self.batch_size, seq_length) I think this is cleaner and doesn't modify your original function. Now you pass an instance of MySequence to model.fit_generator.
has comment: http://stackoverflow.com/comment/99338284
answers question: http://stackoverflow.com/q/50600624
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/99336131

http://stackoverflow.com/q/50583193
has answer: http://stackoverflow.com/a/50583343
has title: Removing \n from scraped table
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/13298907
has body: I tried extracted table using python but cannot remove \n despite using replace, remove, rsplit, lsplit functions. Please help. Following is my code. from urllib.request import urlopen from bs4 import BeautifulSoup import requests import pandas as pd url = "https://shared.websol.barchart.com/quotes/quote.php?page=quote&amp;sym=ng&amp;x=13&amp;y=8&amp;domain=if&amp;display_ice=1&amp;enabled_ice_exchanges=&amp;tz=0&amp;ed=0" res = requests.get(url) soup = BeautifulSoup(res.text, 'lxml') soup.prettify() Header = soup.findAll('tr', limit=2)[1].findAll('th') column_headers = [th.getText() for th in soup.findAll('tr', limit=2)[1].findAll('th')] print(column_headers) data_rows = soup.findAll('tr')[2:] i = range(len(data_rows)) for td in data_rows: row = td.get_text() print(row) My code output is below. Copied only few lines. ['Contract', 'Last', 'Change', 'Open', 'High', 'Low', 'Volume', 'Prev. Stl.', 'Time', 'Links'] \n Cash (NGY00)\n 2.890s\n +0.020\n 0.000\n 2.890\n 2.890\n 0\n 2.870\n 05/25/18\n Q / C / O\n \n Jun \'18 (NGM18)\n 2.946\n +0.007\n 2.946\n 2.968\n 2.908\n 2331\n 2.939\n 19:13\n Q / C / O\n \n Jul \'18 (NGN18)\n 2.974\n +0.011\n 2.974\n 3.000\n 2.937\n 23859\n 2.963\n 19:37\n Q / C / O\n \n Aug \'18 (NGQ18)\n 2.989\n +0.006\n 2.983\n 3.016\n 2.957\n 4434\n 2.983\n 18:25\n Q / C / O\n \n Sep \'18 (NGU18)\n 2.977\n +0.010\n 2.970\n 2.998\n 2.942\n 2313\n 2.967\n 18:07\n Q / C / O\n \n Oct \'18 (NGV18)\n 2.975\n +0.005\n 2.969\n 2.999\n 2.944\n 2259\n 2.970\n 19:01\n Q / C / O\n \n Nov \'18 (NGX18)\n 3.013\n +0.005\n 3.007\n 3.034\n 2.983\n 1774\n 3.008\n 19:18\n Q / C / O\n \n Dec \'18 (NGZ18)\n 3.113\n +0.007\n 3.106\n 3.131\n 3.082\n 1287\n 3.106\n 17:59\n Q / C / O\n \n Jan \'19 (NGF19)\n 3.198\n +0.011\n 3.177\n 3.212\n 3.165\n 1737\n 3.187\n 17:51\n Q / C / O\n \n Feb \'19 (NGG19)\n 3.156\n +0.008\n 3.137\n 3.170\n 3.126\n 776\n 3.148\n 17:39\n Q / C / O\n \n Mar \'19 (NGH19)\n 3.042\n +0.002\n 3.042\n 3.063\n 3.017\n 2891\n 3.040\n 18:27\n Q / C / O\n …
duplicate of: http://stackoverflow.com/q/13298907
tagged with: python
has answer: http://stackoverflow.com/a/50583453
has comment: http://stackoverflow.com/comment/88175704
score: 0
type: UnansweredQuestion

http://stackoverflow.com/a/50608170
has comment: http://stackoverflow.com/comment/88226237
score: 2
downvote count: 0
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/50607266
has body: re.match(r"(/dev/)(xv|s)(d[a-z])", device) won't work because you need to escape the parentheses in (xv|s). Plus match only tries to match at the start of the string. You want re.sub to mimic sed Anyway, it's very easy to convert the sed command. Just split according to % in your pattern and use a raw string prefix for the replacement for \1 and such (or python escape sequences get in the way) so with your exact search &amp; replace expressions: re.sub("(/dev/)(xv|s)(d[a-z])[0-9]*",r"\1(xv|s)\3","/dev/sda1 /dev/xvdb3") prints: /dev/(xv|s)da /dev/(xv|s)db

http://stackoverflow.com/comment/88127333
score: 0
comment on: http://stackoverflow.com/q/50558056
has text: Possible duplicate of [Removing elements from a list containing specific characters](https://stackoverflow.com/questions/3416401/removing-elements-from-a-list-containing-specific-characters)
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50695000
tagged with: pandas
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/50695252
has answer: http://stackoverflow.com/a/50695465
tagged with: python
has title: How to change dataframe values when you need select different columns for every row
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50695465
has body: I have a dataframe in the following form: W1 W2 W3 W4 W5 W6 W7 W8 0 0 1 0 1 1 1 1 0 0 1 0 0 1 1 1 0 1 0 0 1 1 0 0 1 0 0 0 1 1 0 1 There is a parameter DIFF = 3. I'm looking at every row for columns from W1 to W4 and search for last 1. It will be in columns W3, W3, W2, W1. Subsequently I change to 0 next 3 (DIFF) elements on the right side of this 1 in the whole row. See example, I marked those elements by x : W1 W2 W3 W4 W5 W6 W7 W8 0 0 1 x x x 1 1 0 0 1 x x x 1 1 0 1 x x x 1 0 0 1 x x x 1 1 0 1 And final result: W1 W2 W3 W4 W5 W6 W7 W8 0 0 1 0 0 0 1 1 0 0 1 0 0 0 1 1 0 1 0 0 0 1 0 0 1 0 0 0 1 1 0 1 Now, I have very convoluted solution that uses iterrows(), but I'm looking for a pandastic one.
upvote count: 3
type: Question
score: 3
has answer: http://stackoverflow.com/a/50695252
answer count: 2

http://stackoverflow.com/a/50613325
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50613151
answers question: http://stackoverflow.com/q/50613151
has body: Using join with ffill: df1.join(df2).ffill().astype(int) A B C D 0 1 2 3 4 1 1 2 3 4 2 1 2 3 4 3 1 2 3 4
score: 0

http://stackoverflow.com/comment/88228621
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50609353
type: Comment
has text: The first part doesn't work for me because Eclipse doesn't recognise the character directly. And same issue with the second part - when I print the result it is still the same curly comma and fails comparison test.

http://stackoverflow.com/q/50615812
type: UnansweredQuestion
tagged with: python
tagged with: python-unittest
type: Question
answer count: 2
has title: Flask app created twice during python unittest
has body: I have an app.py file which creates an flask app def create_app(): app = Flask(__name__) return app I am trying to write an unittest for my module and below is the file from app import create_app class TestCase(unittest.TestCase): def setUp(self): self.app = create_app() self.client = self.app.test_client() ctx = self.app.app_context() ctx.push() def test_healthcheck(self): res = self.client.get("/") self.assertEqual(res.status_code, 200) def test_tenant_creation(self): res = self.client.post("/tenants") self.assertEqual(res.status_code, 200) When i run individual test methods it is working fine. But when i run the entire test case , the create app is called again which causes issues since my create app has dependencies which needs to be called only once. Is it possible to create app only once ?
tagged with: flask
score: 0
linked to: http://stackoverflow.com/q/17353213
has comment: http://stackoverflow.com/comment/88242916
has answer: http://stackoverflow.com/a/50616646
has answer: http://stackoverflow.com/a/50615879

http://stackoverflow.com/q/50663034
tagged with: python
has comment: http://stackoverflow.com/comment/88336545
type: AnsweredQuestion
tagged with: tkinter
has body: I have a problem in which I am running a Tkinter GUI program (a quiz game). While the user has a choice of 4 buttons and can choose one, I need a countdown timer that will change the question when the time is zero. I need it as a subprocess or separate thread because the user will not be able to choose an answer otherwise. This is different from other questions about timers because the answers to those questions include [Object] = threading.Timer(numCount, callback), but the Timer does not return its value as it counts. Is there any way to do this? I have already tried multiple methods, including the threading module, and the pygame clock (:D).
score: 1
tagged with: multithreading
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50663103
has title: Function that counts down as a subprocess
answer count: 2
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: timer
possible better answer: http://stackoverflow.com/a/50663108
has answer: http://stackoverflow.com/a/50663103
has answer: http://stackoverflow.com/a/50663108

http://stackoverflow.com/comment/88284489
has text: `min(my_randoms)`.
type: Comment
comment on: http://stackoverflow.com/q/50637158
type: QuestionComment
score: 2

http://stackoverflow.com/q/50639418
has answer: http://stackoverflow.com/a/50639934
tagged with: http://stackoverflow.com/tag/json
type: Question
answer count: 1
score: 0
tagged with: python
has body: I need to convert XML to json without root in python. Here is an example of XML <?xml version="1.0" encoding="UTF-8"?> <Member_ID>926494</Member_ID> <First_Name>Corissa</First_Name> <Last_Name>Aguiler</Last_Name> F 39 5,3 130 <Hours_Sleep>8</Hours_Sleep> <Calories_Consumed>2501</Calories_Consumed> <Exercise_Calories_Burned>990</Exercise_Calories_Burned> 9/11/2017 I need to convert into JSON in the following format { "Member_ID": 926494, "First_Name": "Corissa", "Last_Name": "Aguiler", "Gender": "F", "Age": 39, "Height": "5,3", "Weight": 130, "Hours_Sleep": 8, "Calories_Consumed": 2501, "Exercise_Calories_Burned": 990, "Date": "9/11/2017" }, I am trying to use the parker convention from xmljson library but all the examples I'm finding are using string as input. I can't seem to figure out how to pass the actual .xml file instead of a string For example: from xmljson import parker, Parker from xml.etree.ElementTree import fromstring from json import dumps dumps(parker.data(fromstring('<x>12</x>'))) '{"a": 1, "b": 2}'
tagged with: http://stackoverflow.com/tag/xml
tagged with: python-3.x
type: UnansweredQuestion
has title: How to convert an xml to json without root in Python?

http://stackoverflow.com/q/50577444
type: AnsweredQuestion
has title: Encoding Error with Beautiful Soup: Character Maps to Undefined (Python)
linked to: http://stackoverflow.com/q/18337407
type: Question
possible better answer: http://stackoverflow.com/a/50577538
answer count: 2
tagged with: encoding
has answer: http://stackoverflow.com/a/50577538
has answer: http://stackoverflow.com/a/50584538
tagged with: beautifulsoup
score: 0
tagged with: http://stackoverflow.com/tag/html
has body: I've written a script that is supposed to retrieve html pages off a site and update their contents. The following function looks for a certain file on my system, then attempts to open it and edit it: def update_sn(files_to_update, sn, table, title): paths = files_to_update['files'] print('updating the sn') try: sn_htm = [s for s in paths if re.search('^((?!(Default|Notes|Latest_Addings)).)*htm$', s)][0] notes_htm = [s for s in paths if re.search('_Notes\.htm$', s)][0] except Exception: print('no sns were found') pass new_path_name = new_path(sn_htm, files_to_update['predecessor'], files_to_update['original']) new_sn_number = sn htm_text = open(sn_htm, 'rb').read().decode('cp1252') content = re.findall(r'(&lt;table&gt;.*?&lt;\/table&gt;.*)(?:&lt;\/html&gt;)', htm_text, re.I | re.S) minus_content = htm_text.replace(content[0], '') table_soup = BeautifulSoup(table, 'html.parser') new_soup = BeautifulSoup(minus_content, 'html.parser') head_title = new_soup.title.string.replace_with(new_sn_number) new_soup.link.insert_after(table_soup.div.next) with open(new_path_name, "w+") as file: result = str(new_soup) try: file.write(result) except Exception: print('Met exception. Changing encoding to cp1252') try: file.write(result('cp1252')) except Exception: print('cp1252 did\'nt work. Changing encoding to utf-8') file.write(result.encode('utf8')) try: print('utf8 did\'nt work. Changing encoding to utf-16') file.write(result.encode('utf16')) except Exception: pass This works in the majority of cases, but sometimes it fails to write, at which point the exception kicks in and I try every feasible encoding without success: updating the sn Met exception. Changing encoding to cp1252 cp1252 did'nt work. Changing encoding to utf-8 Traceback (most recent call last): File "C:\Users\Joseph\Desktop\SN Script\update_files.py", line 145, in update_sn file.write(result) File "C:\Users\Joseph\AppData\Local\Programs\Python\Python36\lib\encodings\cp1252.py", line 19, in encode return codecs.charm…
accepted answer: http://stackoverflow.com/a/50584538
has comment: http://stackoverflow.com/comment/88164075
tagged with: python

http://stackoverflow.com/q/50664568
tagged with: dataframe
tagged with: inheritance
tagged with: class
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/88341585
type: UnansweredQuestion
has title: Building a class of DataFrame type with an append method, can not change the instance of the class
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/88341672
type: Question
has body: I'm trying to create a class that inherit from pd.DataFrame with an self-defined append method in it. class test(pd.DataFrame): def __init__(self,df,init_balance=1000000): super(test, self).__init__(df) test.balance=init_balance def appd(self): df1=pd.DataFrame({"A": range(4)}) self=self.append(df1) return self What I want is the instance of the class to be a DataFrame-like data ,and when i use the method inside of the class such as the appd method, the instance should renew itself. df= pd.DataFrame() inst1=test(df) inst1.appd() But the thing is I can't change the instance(inst1) of the class, it is still a empty data, although the append method can return a dataframe with data in it if use inst2=inst1.append().

http://stackoverflow.com/q/50629513
type: UnansweredQuestion
tagged with: python
tagged with: sphinx
score: 1
upvote count: 1
tagged with: networkx
type: Question
tagged with: conda
has title: Errors importing Networkx package
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50629774
favorite count: 0
has body: For some reason I'm unable to import networkx. Here is the error I get when I try to import within Python in interactive mode. &gt;&gt;&gt; import networkx Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\wkong\AppData\Roaming\Python\Python36\site-packages\networkx\__init__.py", line 128, in &lt;module&gt; import networkx.drawing File "C:\Users\wkong\AppData\Roaming\Python\Python36\site-packages\networkx\drawing\__init__.py", line 6, in &lt;module&gt; from . import nx_pydot File "C:\Users\wkong\AppData\Roaming\Python\Python36\site-packages\networkx\drawing\nx_pydot.py", line 27, in &lt;module&gt; from pkg_resources import parse_version File "C:\Users\wkong\AppData\Local\Continuum\anaconda3\envs\eda\lib\site-packages\pkg_resources\__init__.py", line 3086, in &lt;module&gt; @_call_aside File "C:\Users\wkong\AppData\Local\Continuum\anaconda3\envs\eda\lib\site-packages\pkg_resources\__init__.py", line 3070, in _call_aside f(*args, **kwargs) File "C:\Users\wkong\AppData\Local\Continuum\anaconda3\envs\eda\lib\site-packages\pkg_resources\__init__.py", line 3114, in _initialize_ for dist in working_set File "C:\Users\wkong\AppData\Local\Continuum\anaconda3\envs\eda\lib\site-packages\pkg_resources\__init__.py", line 3114, in &lt;genexpr&gt; for dist in working_set File "C:\Users\wkong\AppData\Local\Continuum\anaconda3\envs\eda\lib\site-packages\pkg_resources\__init__.py", line 2637, in activate declare_namespace(pkg) File "C:\Users\wkong\AppData\Local\Continuum\anaconda3\envs\eda\lib\site-packages\pkg_resources\__init__.py", line 2174, in declare_name _handle_ns(packageName, path_item) File "C:\Users\wkong\AppData\Local\Continuum\anaconda3\envs\eda\lib\site-packages\pkg_resources\__init__.py", line 2094, in _handle_ns loader = importer.find_module(packageName) File "&lt;frozen importlib._bootstrap_external&gt;", line 426, in _find_module_shim ImportWarning: Not importing directory C:\Users\wkong\AppData\Roaming\Python\Python36…

http://stackoverflow.com/comment/88260023
has text: `current_demand Temp_Mean humidity_Mean` I am getting `NaN` in this column name
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50621816

http://stackoverflow.com/comment/88353209
has text: Thanks, perfect solution! I wonder if you could expand why the example that I first got that observer patter scheme from used decorates? Is there any advantage?
score: 0
comment on: http://stackoverflow.com/a/50662709
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88327598
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50658719
has text: You can use collections module also.

http://stackoverflow.com/a/50655629
answers question: http://stackoverflow.com/q/50649556
has comment: http://stackoverflow.com/comment/88326078
has comment: http://stackoverflow.com/comment/88324985
downvote count: 0
type: Answer
has body: you can't use clim for what you want. instead: from matplotlib.colors import ListedColormap from matplotlib.cm import get_cmap inferno = get_cmap('inferno').colors new_cmap = ListedColormap(inferno+inferno[::-1])
upvote count: 1
score: 1

http://stackoverflow.com/a/50681988
has comment: http://stackoverflow.com/comment/88440828
has body: As I understand your question you want to give each entry a flag 'machine' or 'person', based on the "name" tag. Assigning such a flag (or just directly writing to the appropriate file) could be done with for instance something like with open(file1, 'w') as _file1, open(file2, 'w') as _file2, open(file3, 'w') as _file3: for distro in distros: yourstring = distro['name'] + ',' + str(distro['positionTS']) + ',' + str(distro['position']) if distro['name'].startswith(('forklift','crane',...)): _file1.write(yourstring) elif distro['name'].startswith(('guest','employee',...)): _file2.write(yourstring) else: _file3.write(yourstring) The three files that have been opened for writing together will contain all the entries in the end, split up between machines, people, and neither of both. Does that solve your issue?
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50681795
upvote count: 2
answers question: http://stackoverflow.com/q/50681795
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/88599073

http://stackoverflow.com/a/50557193
type: AcceptedAnswer
type: Answer
has body: It seems that what was causing this problem was having items with different shapes in the list. In this instance, PNG images with 3 and 4 channel. Removing the alpha channel (the fourth channel) from all PNG images solved this for me.
answers question: http://stackoverflow.com/q/50545324
accepted answer of: http://stackoverflow.com/q/50545324
score: 0

http://stackoverflow.com/q/50565710
accepted answer: http://stackoverflow.com/a/50565747
type: AnsweredQuestion
has body: I am trying to remove ; from a column in a DataFrame, but when I use the .replace(';', ' ') method it does not replace the semicolumn, here is how i am doing it: for i in excel_file['dateTime']: i.replace(';', ' ') This is how my 'dateTime' column looks like: 11-06-18; 18-06-18; 18-09-18; 14-06-18; 20-06-18; 13-06-18; 21-06-18; 19-06-18; 19-06-18; 20-06-18; 11-06-18; 22-06-18;
score: -1
type: Question
has comment: http://stackoverflow.com/comment/88141576
answer count: 2
upvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50565747
has title: .replace() in a DataFrame does not replace
tagged with: pandas
has answer: http://stackoverflow.com/a/50565801
tagged with: python
possible better answer: http://stackoverflow.com/a/50565801
downvote count: 1

http://stackoverflow.com/comment/88129415
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50559374
has text: Yes. A string is iterable. I am just following the question.
type: AnswerComment

http://stackoverflow.com/a/66515275
type: Answer
has body: had a similar problem. My Problem was to upload the image to some other destination once the model is saved though admin. Solved it by implementing Admin class on admin.py e.g if you have a model namely Shop then in your admin.py would be like @admin.register(Shop) class ShopAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): instance = form.instance instance.save() image_path = instance.banner_image.path move_image(image_path)
answers question: http://stackoverflow.com/q/50604451
score: 0

http://stackoverflow.com/q/50627310
has title: Extract data from span tag within a div tag
answer count: 1
has comment: http://stackoverflow.com/comment/88264712
has body: I have the html code below and I'm trying to extract the 3:40 as text to use in my python script. How would I go about grabbing that info? example element
tagged with: http://stackoverflow.com/tag/html
tagged with: python
favorite count: 0
upvote count: 0
downvote count: 5
has comment: http://stackoverflow.com/comment/88264730
type: AnsweredQuestion
score: -5
has answer: http://stackoverflow.com/a/50627509
accepted answer: http://stackoverflow.com/a/50627509
type: Question

http://stackoverflow.com/comment/88128619
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50559000
score: 1
has text: @student The accepted solution in the link you provided is the exact thing I'm trying, but it doesn't work in code section - maybe it only works in markdown section.

http://stackoverflow.com/a/50661134
answers question: http://stackoverflow.com/q/50661080
has body: One thing you can do is ans = ans.capitalize() after you get the user input. Then remove the ans != 'y' since that's causing your loop to break.
score: 0
type: Answer

http://stackoverflow.com/a/50595685
has body: Instead of mysql = MySQL() use mysql = MySQL(app) so that your mysql object will be connected to your app. (You can follow what this means by starting here: https://github.com/admiralobvious/flask-mysqldb/blob/master/flask_mysqldb/init.py#L8)
upvote count: 1
score: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50594198

http://stackoverflow.com/q/50574561
has comment: http://stackoverflow.com/comment/88158577
has comment: http://stackoverflow.com/comment/88158564
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has title: using index in calculations, pandas
tagged with: python
has comment: http://stackoverflow.com/comment/88158535
duplicate of: http://stackoverflow.com/q/18368442
has comment: http://stackoverflow.com/comment/88158496
type: Question
duplicate of: http://stackoverflow.com/q/18835077
has body: I have a df that contains a date index and another column which is a different date. I would like to add a column to my df that is the difference between these two dates in days. How can one use the index in the computation directly without having to bring it into the df as a column? MWE: df = pd.DataFrame(data = {"val": [1,2,3,4,5], "some_date": np.arange("2000-02-01", "2000-02-06", dtype="datetime64[D]")}, index = pd.date_range(start = "2000-01-01", end = "2000-01-05", periods = 5, name="date")) #would like to do something like this df["delta"] = df["some_date"] - df["date"] #produces an error What's the best way to access the index in calculations of this type?
linked to: http://stackoverflow.com/q/18368442
has comment: http://stackoverflow.com/comment/88158521
score: 0
tagged with: pandas

http://stackoverflow.com/comment/88115113
comment on: http://stackoverflow.com/a/50551709
has text: I think we're having a language barrier here :) What I'm trying to tell is, there are no 2 identical phone numbers, they just have identical parts. When you look at the phone number +123(444 - 555 - 7777 - 66) instead of asking the user for just the (444..66) part, require a full phone number including the country code + 123 ( 44 . 66) that way everyone phone number will be unique. Is this better ?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50671044
tagged with: python
tagged with: django
linked to: http://stackoverflow.com/q/43067696
upvote count: 1
accepted answer: http://stackoverflow.com/a/50681372
tagged with: celery
type: AnsweredQuestion
score: 1
type: Question
answer count: 1
downvote count: 0
favorite count: 0
has body: Before any explanations, here is the tree of my project | projectname |____|__init__.py |____|celery.py |____|settings.py |____|urls.py |____|wsgi.py |app1 |app2 Here's my celery.py from celery import Celery from celery import shared_task os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings') app = Celery('projectname') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() from app1.models import * @share_task def tasks(): ''' ''' Every time I try importing models to the celery.py file with this line from app1.models import * I got: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. And the local server stops working all of a sudden. This post is related to a similar problem, but not sure it's the case here. What I want is to import some models to the file, so I can use them for some queries. I got a little clue about what can be wrong, but not sure. views import stuff from models.py views import stuff from celery.py like the task to be executed celery.py tries to import stuff from models. So that circle like a snake that bites its own tail is weird to me.
has answer: http://stackoverflow.com/a/50681372
has title: Apps aren't loaded yet when trying to import model in a celery tasks file

http://stackoverflow.com/q/50584678
has comment: http://stackoverflow.com/comment/88180674
tagged with: python
has comment: http://stackoverflow.com/comment/88180789
answer count: 0
has body: I have a pyspark task on zeppelin which is reading some parquet files and do some reduce and filter on it. I've gotten the follwoing error in the middle of the task in zeppelin (when applying the reduce): from operator import add result = data_rdd.filter(lambda log: log['test'] == "test" and (log['index'] is not None)) .map(lambda log: (int(log['index']),1)).reduceByKey(add).collect() Job aborted due to stage failure: Task 4235 in stage 66.0 failed 4 times, most recent failure: Lost task 4235.3 in stage 66.0 (TID 9583, , executor 2): com.amazonaws.AmazonClientException: Unable to unmarshall error response (The element type "hr" must be terminated by the matching end-tag "".). Response Code: 502, Response Text: Bad Gateway Although I didn't get the error again, my question is anybody knows what happened here? I should notice that the Ceph is not down in that time!
tagged with: apache-zeppelin
type: Question
has comment: http://stackoverflow.com/comment/88178888
tagged with: pyspark
has title: The element type "hr" must be terminated by the matching end-tag " " in Spark
score: 0
has comment: http://stackoverflow.com/comment/88180756
tagged with: apache-spark
type: UnansweredQuestion

http://stackoverflow.com/comment/88217546
type: QuestionComment
has text: The error you're getting means you're attempting to access an element of a `List` that is beyond the length of the `List`. I'm not saying this will work, but try `print(source_dir + content[dst_ind - 1] + "\t" + dir_list[dst_ind - 1])`
type: Comment
comment on: http://stackoverflow.com/q/50602113
score: 0

http://stackoverflow.com/q/50623889
score: 0
type: UnansweredQuestion
tagged with: python
has title: How to highlight some words in a non-readonly field in django admin?
answer count: 0
has comment: http://stackoverflow.com/comment/88258113
tagged with: django
type: Question
tagged with: django-admin
tagged with: django-models
has body: I have a "models.TextField" which is editable in Admin. How can I highlight certain words in it such that when someone opens admin for this model those words are highlighted. In addition, when you change the field value, I want those highlights (probably markdowns in the text) not to be considered when saving the model.
has comment: http://stackoverflow.com/comment/88262132

http://stackoverflow.com/a/50616274
has body: A priority queue is not supposed to be sorted. The priority queue only guarantees that when you call get(), it returns you the highest priority item. Internally, queue.PriorityQueue uses a binary heap to contain the items. The reason it doesn't use a sorted array is because maintaining a sorted array is expensive. Adding and removing items would be O(n) operations. A binary heap makes those O(log n) operations. See https://github.com/python/cpython/blob/2.7/Lib/Queue.py and https://docs.python.org/2/library/heapq.html for details.
accepted answer of: http://stackoverflow.com/q/50616152
answers question: http://stackoverflow.com/q/50616152
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 11
upvote count: 11

http://stackoverflow.com/comment/88381999
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50686164
has text: Well Python interprets files linearly. You can see an import statement as a statement that asks Python to read the file you import into memory, but if your first file asks to import the second file, and the second file asks to import the first, then there is a cyclic problem.
type: Comment

http://stackoverflow.com/q/50591617
has answer: http://stackoverflow.com/a/55560152
has title: pip install pyscf, other packages - throws TypeError: parse() got an unexpected keyword argument 'transport_encoding'
score: 0
tagged with: gentoo
answer count: 1
linked to: http://stackoverflow.com/q/39086278
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88423128
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/88423158
type: Question
has body: I'm attempting to install pyscf along with other modules into my local user instance of /home/user/.local/ but with many of the packages I need to install I'm getting the error below. I have also already tried following the suggestion here. user@computer ~ $ python -m pip install --user --upgrade pyscf Collecting pyscf Exception: Traceback (most recent call last): File "/usr/lib64/python2.7/site-packages/pip/basecommand.py", line 211, in main status = self.run(options, args) File "/usr/lib64/python2.7/site-packages/pip/commands/install.py", line 294, in run requirement_set.prepare_files(finder) File "/usr/lib64/python2.7/site-packages/pip/req/req_set.py", line 334, in prepare_file s functools.partial(self._prepare_file, finder)) File "/usr/lib64/python2.7/site-packages/pip/req/req_set.py", line 321, in _walk_req_to _install more_reqs = handler(req_to_install) File "/usr/lib64/python2.7/site-packages/pip/req/req_set.py", line 461, in _prepare_fil e req_to_install.populate_link(finder, self.upgrade) File "/usr/lib64/python2.7/site-packages/pip/req/req_install.py", line 250, in populate _link self.link = finder.find_requirement(self, upgrade) File "/usr/lib64/python2.7/site-packages/pip/index.py", line 486, in find_requirement all_versions = self._find_all_versions(req.name) File "/usr/lib64/python2.7/site-packages/pip/index.py", line 404, in _find_all_versions index_locations = self._get_index_urls_locations(project_name) File "/usr/lib64/python2.7/site-packages/pip/index.py", line 378, in _get_index_urls_lo cations page = self._get_page(main_index_url) File "/usr/lib64/python2.7/site-packages/pip/index.py", line 818, in _get_page return HTMLPage.get_page(link, session=self.session) File "/usr/lib64/python2.7/site-packages/pip/index.py", line 949, in get_page trusted=link.trusted, File "/usr/lib64/python2.7/site-packages/pip/index.py", line 866, in __init__ namespaceHTMLElements=False, File "/home/user/.local/lib64/python2.7/site-packages/html5lib/html5parser.py", lin…

http://stackoverflow.com/a/67806331
type: Answer
answers question: http://stackoverflow.com/q/50674923
score: 0
has body: There is no way to move cursor back in readMore queries (documenation). Your problem is not on Intacct side, but on app code: during parsing response using lxml or any other XML parser. So you need to do error handling (at least try/except) and/or retries there. Please save raw responses from Intacct, so you'll be able to investigate or debug parsing issues.

http://stackoverflow.com/comment/88375216
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50682754
has text: Perfect...now how do add a hyphen in between A and B
score: 0

http://stackoverflow.com/a/50659773
answers question: http://stackoverflow.com/q/50659519
downvote count: 0
has body: shift returns a copy of your dataframe, it does not modify it, so creating a copy is unnecessary. You can further clean up your code by using a list comprehension, and use a bit of algebra to shift by two each column instead of one. x = np.random.randint(1, 10, 10) df = pd.DataFrame(x) dfs = [df.shift(-(2+2*i)) for i in range(3)] pd.concat([df, *dfs], axis=1) 0 0 0 0 0 3 1.0 3.0 8.0 1 9 1.0 6.0 8.0 2 1 3.0 8.0 1.0 3 1 6.0 8.0 9.0 4 3 8.0 1.0 NaN 5 6 8.0 9.0 NaN 6 8 1.0 NaN NaN 7 8 9.0 NaN NaN 8 1 NaN NaN NaN 9 9 NaN NaN NaN This approach does leave you with the same column header for each column, which you could fix using something like: df_result.columns = range(len(df_result.columns))
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/comment/88378597
type: Comment
type: QuestionComment
has text: `.overrideredirect(1)` disables all of the OS/window manager features for resizing or moving the window. The Tk root is resizable by default without having to call `.resizable()`, but you've explicitly turned off the ability to use that feature.
score: 1
comment on: http://stackoverflow.com/q/50684088

http://stackoverflow.com/q/50545172
type: AnsweredQuestion
has title: How to compare a regex object with a list in python?
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/50545233
score: 0
accepted answer: http://stackoverflow.com/a/50545233
tagged with: python
tagged with: regex
has body: My code is: import re x=["Set","Sets","ShowSets","Union","Intersect","SetUnion","SetIntersect"] print (x) while True: text_to_search = input('Introduce an instruction: ') for match1 in re.finditer('Sets?|ShowSet|ShowSets|Union|Intersect|SetUnion|SetIntersect',text_to_search): print("Instruction: ") #x.append(match1) print(match1) for match2 in re.finditer(r':=|{|}|;',text_to_search): print("Operator: ") print(match2) for match3 in re.finditer(r'[a-zA-Z0-9]+',text_to_search): if match3 in x: pass else: print("ID: ") print(match3) print(x) What I'm trying to do in the third for is to print all the words that are not instruction (avoid printing Set, Sets, ShowSets etc) but the problem is that isnt doing the if match3 in x:so the program is printing: ['Set', 'Sets', 'ShowSets', 'Union', 'Intersect', 'SetUnion', 'SetIntersect'] Introduce an instrucción: Set Hi Instruction: &lt;_sre.SRE_Match object; span=(0, 3), match='Set'&gt; ID: &lt;_sre.SRE_Match object; span=(0, 3), match='Set'&gt; ID: &lt;_sre.SRE_Match object; span=(4, 6), match='Hi'&gt; ['Set', 'Sets', 'ShowSets', 'Union', 'Intersect', 'SetUnion', 'SetIntersect'] Instead of: Introduce an instrucción: Set Hi Instruction: &lt;_sre.SRE_Match object; span=(0, 3), match='Set'&gt; ID: &lt;_sre.SRE_Match object; span=(4, 6), match='Hi'&gt; ['Set', 'Sets', 'ShowSets', 'Union', 'Intersect', 'SetUnion', 'SetIntersect']

if-statement
tags question: http://stackoverflow.com/q/50555726
tags question: http://stackoverflow.com/q/50628206
tag name: if-statement
type: Tag
tags question: http://stackoverflow.com/q/50673163
tags question: http://stackoverflow.com/q/50545038
tags question: http://stackoverflow.com/q/50610405
tags question: http://stackoverflow.com/q/50659353
tags question: http://stackoverflow.com/q/50666410
tags question: http://stackoverflow.com/q/50695080
tags question: http://stackoverflow.com/q/50657770
tags question: http://stackoverflow.com/q/50623430
tags question: http://stackoverflow.com/q/50544763
tags question: http://stackoverflow.com/q/50690751
tags question: http://stackoverflow.com/q/50559359
tags question: http://stackoverflow.com/q/50672643
tags question: http://stackoverflow.com/q/50690761
tags question: http://stackoverflow.com/q/50618960
tags question: http://stackoverflow.com/q/50634714
tags question: http://stackoverflow.com/q/50550643

http://stackoverflow.com/comment/88151490
type: Comment
score: 1
has text: Edited the above. The inputs are not converted to a 13x13 image and then prediction is applied on the 13x13 image. But instead the CNN reduces the original image to a 13x13x425, where each of the 13x13 is a prediction to a grid in the original image.
comment on: http://stackoverflow.com/a/50570204
type: AnswerComment

http://stackoverflow.com/comment/91610205
has text: @dmitry You need to attach the debugger to the process running the python process (jupyter kernel in my case) to which these `execute` commands are sent to
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50836626
type: Comment

http://stackoverflow.com/comment/88243545
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50609244
has text: It worked when I changed file = open("newfile.raw", "w") to file = open("newfile.raw", "wb"). Thanks for the replay anyway.

http://stackoverflow.com/q/50592109
tagged with: windows
has body: I have an file that is called: Abrázame.txt I want to decode this so that python understands what this 'á' char is so that it will print me Abrázame.txt This is the following code i have on an Scratch file: import os s = os.path.join(r'C:\Test\AutoTest', os.listdir(r'C:\\Test\\AutoTest')[0]) print(unicode(s.decode(encoding='utf-16', errors='strict'))) The error i get from above is: Traceback (most recent call last): File "C:/Users/naythan_onfri/.PyCharmCE2017.2/config/scratches/scratch_3.py", line 12, in &lt;module&gt; print(unicode(s.decode(encoding='utf-16', errors='strict'))) File "C:\Python27\lib\encodings\utf_16.py", line 16, in decode return codecs.utf_16_decode(input, errors, True) UnicodeDecodeError: 'utf16' codec can't decode byte 0x74 in position 28: truncated data I have looked up the utf-16 character set and it does indeed have 'á' character in it. So why is it that this string cannot be decoded with Utf-16. Also i know that 'latin-1' will work and produce the string im looking for however since this is for an automation project and i wanting to ensure that any filename with any registered character can be decoded and used for other things within the project for example: "Opening up file explorer at the directory of the file with the file already selected." Is looping through each of the codecs(Mind you i believe there is 93 codecs) to find whichever one can decode the string, the best way of getting the result I'm looking for? I figure there something far better than that solution.
tagged with: python
has comment: http://stackoverflow.com/comment/88194072
type: AnsweredQuestion
score: 0
type: Question
has answer: http://stackoverflow.com/a/50592729
has comment: http://stackoverflow.com/comment/88194775
tagged with: character-encoding
has title: Python 2.7: Printing out an decoded string
tagged with: python-2.7
answer count: 1
accepted answer: http://stackoverflow.com/a/50592729
has comment: http://stackoverflow.com/comment/88194275
tagged with: character
has comment: http://stackoverflow.com/comment/88193995

http://stackoverflow.com/q/50674857
has answer: http://stackoverflow.com/a/50674952
score: 4
answer count: 2
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 4
has body: The SQLAlchemy CORE doc for transactions suggests using a with context manager as follows: # runs a transaction with engine.begin() as connection: r1 = connection.execute(table1.select()) connection.execute(table1.insert(), col1=7, col2='this is some data') or with connection.begin() as trans: r1 = connection.execute(table1.select()) connection.execute(table1.insert(), col1=7, col2='this is some data') Either way, how do I know if a transaction was executed and committed, or if it was rolled back?
has title: Using a `with` context manager in SQLAlchemy Core how do I know if a transaction rolled back?
downvote count: 0
has answer: http://stackoverflow.com/a/50675632
tagged with: sqlalchemy
type: Question

http://stackoverflow.com/comment/88325771
has text: inb4 "what have you tried so far?" if all else fails: win32com (pypiwin32) should let you add comments https://stackoverflow.com/questions/47222373/add-comment-to-excel-using-python-win32
type: Comment
score: 2
comment on: http://stackoverflow.com/q/50657822
type: QuestionComment

http://stackoverflow.com/a/50664592
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50664416
has body: You could always try this itertools.combinations() solution to get all contigous subarrays of length 2 or greater: &gt;&gt;&gt; from itertools import combinations &gt;&gt;&gt; array = [1, 2, 3, 4] &gt;&gt;&gt; [array[start:end+1] for start, end in combinations(range(len(array)), 2)] [[1, 2], [1, 2, 3], [1, 2, 3, 4], [2, 3], [2, 3, 4], [3, 4]]
upvote count: 1
type: Answer

http://stackoverflow.com/a/50612133
has comment: http://stackoverflow.com/comment/88242425
type: Answer
answers question: http://stackoverflow.com/q/50610084
has body: As the error message suggests, the namespace weather: is not defined - so in the SPARQL you either need a PREFIX to define weather, like: PREFIX weather: &lt;weatheruri&gt; Or you should put the explicit weather URI instead of the weather: The weather namespace URI (or is it called an IRI?) will be in the XML namespaces in the rdf document - it will end with / or # so if the URI is http://weather.com/ the prefix definition is PREFIX weather: &lt;http://weather.com/&gt;
accepted answer of: http://stackoverflow.com/q/50610084
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/50631635
upvote count: 1
has comment: http://stackoverflow.com/comment/88351459
has comment: http://stackoverflow.com/comment/88279655
accepted answer of: http://stackoverflow.com/q/50631426
score: -1
answers question: http://stackoverflow.com/q/50631426
type: AcceptedAnswer
has body: Well I have just impersonated your someone here :) with your code and the answer is yes it works, after I changed the def myfunc(a: int, b:int): -&gt; str to def myfunc(a: int, b:int) -&gt; str: otherwise it's a syntax error.
downvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/88351379
has comment: http://stackoverflow.com/comment/88352892

http://stackoverflow.com/comment/88131986
type: QuestionComment
comment on: http://stackoverflow.com/q/50560276
score: 0
has text: [PD](https://stackoverflow.com/q/765736/5033247)
type: Comment

http://stackoverflow.com/a/54437010
score: 90
has body: This question is already answered here and this solution works. caching sha2 password is not supported mysql Just try this command : pip install mysql-connector-python
has comment: http://stackoverflow.com/comment/107538994
type: Answer
answers question: http://stackoverflow.com/q/50557234
upvote count: 91
downvote count: 1
has comment: http://stackoverflow.com/comment/117774643
has comment: http://stackoverflow.com/comment/99679279

http://stackoverflow.com/comment/88378836
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50683910
has text: Please provide some code. We need an example of what you have tried to work with. Have you tried anything? Take a look at this link: [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve).
score: 0

http://stackoverflow.com/q/50678753
upvote count: 1
type: Question
tagged with: sqlite
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50679119
has body: I'm hoping for some help with Prettytable. I'm trying to read a file (called "file.db") and draw out a table of interest (called "baseball") and then print the columns within a PrettyTable layout. I'm struggling with getting the SQL output from the file into a Prettytable. Any thoughts? The output below will select the correct file, table in the file, and provides a listing of the data in the relevant rows. But, my Prettytable isn't working. My selected data isn’t displayed within it. All I’m getting is my Prettytable columns that I’m specifying. : import os import sqlite3 import prettytable DIR_NAME = os.path.dirname(__file__) db_path = os.path.join(DIR_NAME, "file.db") print(db_path) try: sqlConn = sqlite3.connect(db_path) except sqlConn.DatabaseError: print("I can't open this database") exit(0) print("Database was processed") db = sqlConn.execute("SELECT * FROM baseball") myTable = prettytable.from_db_cursor(db) cursor = sqlConn.cursor() rows = db.fetchall() print(rows) print(myTable.get_string(fields=["bats", "balls", "uniforms"])) for row in rows: myTable.add_row(row) print(myTable) sqlConn.close()
tagged with: python-3.x
tagged with: python
type: UnansweredQuestion
score: 1
has title: Python: Reading columns and rows from SQLite file into Prettytable?

http://stackoverflow.com/comment/88428964
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50662071
score: 1
has text: @smci : It works !!! Thank you so much :D Suddenly my code became much short

http://stackoverflow.com/a/50644755
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50644066
has body: You can unnest your string with Series after str.split df.set_index('id').t.str.split(r'\n').apply(pd.Series).stack().reset_index(level=1,drop=True).to_frame('t') Out[177]: t id 1 very long text 1 text line 2 1 text line 3 2 short text
downvote count: 0

http://stackoverflow.com/comment/88189103
comment on: http://stackoverflow.com/a/50584600
has text: @SamuelValente Here's another option.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88355734
type: QuestionComment
type: Comment
score: 2
has text: The binary search method looks fine to me. If it’s not working then your list is probably not actually sorted correctly.
comment on: http://stackoverflow.com/q/50672980

http://stackoverflow.com/comment/91681357
score: 0
has text: Possible duplicate of [python multiprocessing on windows, if \_\_name\_\_ == "\_\_main\_\_"](https://stackoverflow.com/questions/20222534/python-multiprocessing-on-windows-if-name-main)
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50593538

http://stackoverflow.com/a/50663578
downvote count: 1
has body: From the Python docs, https://docs.python.org/3.6/library/stdtypes.html#truth-value-testing Any object [of builtin type] can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object. It lists various builtin objects that are considered false: None, False, 0, [],{}`. Every variable has a value, that is, references an object. There's no such thing as an uninitialized variable in Python. You'll get a NameError if you try use a variable that hasn't been assigned. None is a good default value, for example in: def foo(x, y=None): if y is None: y = 'a special value' ... A numpy array is not a builtin type, and doesn't work well with this truth-value-testing. An ndarray always has a value. Here are some cases: A single element array, regardless of dimensions (0,1,...) works in an if: In [73]: if np.array([0]): print('yes') # np.array(False), etc In [74]: if np.array([1]): print('yes') yes But multielement array will produce a ValueError, regardless of the values: In [75]: if np.array([1,2]): print('yes') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-75-1212b980c1b6&gt; in &lt;module&gt;() ----&gt; 1 if np.array([1,2]): print('yes') ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() An empty array (0 elements) is also a special case: In [77]: if np.array([]): print('yes') /usr/local/bin/ipython3:1: DeprecationWarning: The truth value of an empty array is ambiguous. Returning False, but in future this will result in an error. Use `array.size &gt; 0` to check that an array is not empty. #!/usr/bin/python3 That ValueError comes up often on SO. Typically it's in: if x&lt;0: ... where x is an array. &lt; te…
answers question: http://stackoverflow.com/q/50660741
type: Answer
upvote count: 2
score: 1

http://stackoverflow.com/comment/88399575
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50566855
has text: Try something, post a real question.
type: QuestionComment

http://stackoverflow.com/comment/88405756
comment on: http://stackoverflow.com/q/50698135
type: Comment
type: QuestionComment
score: 0
has text: `__init__.py` file?

http://stackoverflow.com/a/50543448
type: Answer
has comment: http://stackoverflow.com/comment/88097977
upvote count: 7
has comment: http://stackoverflow.com/comment/88111507
has comment: http://stackoverflow.com/comment/125298715
answers question: http://stackoverflow.com/q/50543326
score: 7
downvote count: 0
has body: I think it would go something like the examples in: Pandas left outer join multiple dataframes on multiple columns dfe = pd.merge(dFA, dFB, how='left', on=['a','b'], indicator=True) dfe[dfe['_merge'] == 'left_only']

http://stackoverflow.com/q/50680753
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/50712762
tagged with: plot
has title: How to update Pretext in Bokeh with a Select tool
has body: I have a bokeh plot that updates my plot through a select tool. The select tool contains subjects that update the plot where the values are x='Polarity'and y='Subjectivity'. Here is a dummy data for what I want: import pandas as pd import random list_type = ['All', 'Compliment', 'Sport', 'Remaining', 'Finance', 'Infrastructure', 'Complaint', 'Authority', 'Danger', 'Health', 'English'] df = pd.concat([pd.DataFrame({'Subject' : [list_type[i] for t in range(110)], 'Polarity' : [random.random() for t in range(110)], 'Subjectivity' : [random.random() for t in range(110)]}) for i in range(len(list_type))], axis=0) My code for updating the plot looks like this: options = [] options.append('All') options.extend(df['Subject'].unique().tolist()) source = ColumnDataSource(df) p = figure() r = p.circle(x='Polarity', y='Subjectivity', source = source) select = Select(title="Subject", options=options, value="All") output_notebook() def update_plot(attr, old, new): if select.value=="All": df_filter = df.copy() else: df_filter = df[df['Subject']==select.value] source1 = ColumnDataSource(df_filter) r.data_source.data = source1.data select.on_change('value', update_plot) layout = column(row(select, width=400), p) #show(layout) curdoc().add_root(layout) I want to add a 'Pretext' that has a df.describe(), that can update with the plot through the select tool. I tried this by adding these codes but it displays nothing: stats = PreText(text='', width=500) t1 = select.value def update_stats(df, t1): stats.text = str(dft1, select.value+'_returns'.describe()) select.on_change('value', update_plot, update_stats) layout = column(row(select, width=400), p, stats) curdoc().add_root(layout) show(layout) Anyone know a solution? Thanks!
score: 0
tagged with: bokeh
answer count: 1
accepted answer: http://stackoverflow.com/a/50712762
tagged with: dataframe
type: AnsweredQuestion

http://stackoverflow.com/a/50635991
upvote count: 1
has body: Calling client.recv(1024) will block and return 1 to 1024 bytes unless the client disconnects, in which case it will return an empty bytestring: def handle_client(client): while True: message = client.recv(BUFFER_SIZE) if not message: # client disconnected break ...
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50635835
answers question: http://stackoverflow.com/q/50635835
score: 1

http://stackoverflow.com/q/50644295
tagged with: python
tagged with: text
tagged with: fonts
type: Question
has answer: http://stackoverflow.com/a/50644484
score: 0
answer count: 1
has title: Receiving error builtins.AttributeError: 'pygame.font.Font' object has no attribute 'SysFont' for font and can't figure out why?
tagged with: pygame
has body: I'm working with pygame and I have text through out my code using font = font.SysFont("candara", 35) using this font, the program is working smoothly and the text shows up but when I added another font font2 = font.SysFont("arial", 25) I'm getting an error and the text won't work. builtins.AttributeError: 'pygame.font.Font' object has no attribute 'SysFont' This is where I'm using my new font def button4(X): draw.rect(X,PINK,(50,70,200,50)) buttonText = font2.render("Home Country",False,(0,0,0)) screen.blit(buttonText,(55,80)) and this is the beginning of my code; from pygame import * import os os.environ['SDL_VIDEO_WINDOW_POS'] = "%d, %d" %(0, 0) init() Any suggestions would be greatly appreciated, thank you.
type: UnansweredQuestion

http://stackoverflow.com/comment/88106424
comment on: http://stackoverflow.com/q/50547819
score: 0
type: QuestionComment
has text: Can you add the content of `builder.py` to your question? This is going to be awfully hard to debug if we can't see what you're doing.
type: Comment

http://stackoverflow.com/q/50645781
has answer: http://stackoverflow.com/a/50646377
has title: How to get a line file from a class in an other class?
tagged with: class
has comment: http://stackoverflow.com/comment/88302368
favorite count: 0
tagged with: parsing
has comment: http://stackoverflow.com/comment/88302282
accepted answer: http://stackoverflow.com/a/50646377
tagged with: python
has answer: http://stackoverflow.com/a/50645929
downvote count: 1
has comment: http://stackoverflow.com/comment/88302278
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88302434
possible better answer: http://stackoverflow.com/a/50645929
score: -1
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88302375
upvote count: 0
has comment: http://stackoverflow.com/comment/88302522
has body: My question is really simple. Let me explain my problem with an exemple code. I have developed a specific file parser and each line represents an object. file = open("file.txt", "r") class Reader(object): def __init__(self): self.i = 1 // first line def readFile(self): for line in file: test2() // do things.. class Line(): def printLine(self): f.readline() // Need to read the current line from the readFile() loop test() So, what I would like to know is how can I get access to the current line from readFile() in test2().printLine() without reopening the file ?

http://stackoverflow.com/comment/88257447
has text: itemformat _does_ accept a formatted string. The `itemconfigure` is working, but the string you're computing isn't associated with anything in the canvas. It looks the same as the variable name, but it's just a string. The canvas has no idea that you've stored the id of an object in a variable with a name that matches the string.
comment on: http://stackoverflow.com/q/50614498
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50550496
favorite count: 0
has body: I need to get the response body content for a POST request using Selenium Chrome driver and browsermob proxy. Currently this content is not included in my file HAR output when i read it although i can see the response in the browser network traffic. How can i make it so response traffic is captured? (sorry new to programming and can't see much python documentation for BMP) server.start() proxy = server.create_proxy() chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--proxy-server={0}".format(proxy.proxy)) driver = webdriver.Chrome(executable_path="chromedriver.exe", chrome_options=chrome_options) proxy.new_har("req", options={'captureHeaders': True,'captureContent':True}) driver.get('https://www.example.com/something') result_har = json.dumps(proxy.har, ensure_ascii=False) with open("haroutput.har", "w") as harfile: harfile.write(result_har) server.stop() driver.quit()
upvote count: 10
tagged with: python
tagged with: selenium-chromedriver
type: UnansweredQuestion
tagged with: selenium
tagged with: browsermob
has title: BrowserMob Proxy Python - How to get response body?
downvote count: 0
score: 10
has answer: http://stackoverflow.com/a/51296804
type: Question
answer count: 1

http://stackoverflow.com/a/50612209
has body: You need to make certain that the selection object that is used for interaction is the same within each sub-chart. There are a few ways to ensure this, but the easiest is to call interactive() only once in a base chart, and then modify that base chart for each panel of the plot. For example: import altair as alt from vega_datasets import data cars = data.cars() chart = alt.Chart(cars).mark_point().encode( x='Horsepower', color='Origin' ).interactive() alt.vconcat( chart.encode(y='Miles_per_Gallon'), chart.encode(y='Acceleration') )
type: AcceptedAnswer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/50578340
answers question: http://stackoverflow.com/q/50578340
type: Answer
upvote count: 1

http://stackoverflow.com/comment/119066795
score: 0
comment on: http://stackoverflow.com/a/58410129
type: Comment
has text: Thanks for the awesome algorithm. Can I connect with you to discuss it.
type: AnswerComment

http://stackoverflow.com/q/50563867
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88139137
type: Question
accepted answer: http://stackoverflow.com/a/50564047
upvote count: 5
score: 5
answer count: 1
downvote count: 0
favorite count: 0
tagged with: pandas
tagged with: python
has body: I have a dataframe like this, print(df['Date']): 0 2018-05-14 1 2018-05-14 2 2018-05-14 3 2018-05-15 But when I wrote it to excel, I had no idea why it showed: 2018-05-14 00:00:00 2018-05-14 00:00:00 2018-05-14 00:00:00 2018-05-15 00:00:00 I don't need time and I want 'yyyy/mm/dd' format, I added format, but it didn't work: writer = pd.ExcelWriter('output.xlsx',engine='xlsxwriter') df.to_excel(writer,sheet_name='Sheet1',index=False) workbook = writer.book worksheet = writer.sheets['Sheet1'] date_format = workbook.add_format({'num_format': 'yyyy/mm/dd'}) worksheet.set_column('A:A', 15,date_format) So, I added datetime_format in ExcelWriter: writer = pd.ExcelWriter('output.xlsx',engine='xlsxwriter',datetime_format='yyyy/mm/dd') it did work, but why? 1. Why can't I use add_format to change? 2. If I want a vertical alignment, I used set_align('vcenter'), it still can't work, how to do?
has answer: http://stackoverflow.com/a/50564047
has title: How to write dataframe to excel and change format

http://stackoverflow.com/comment/88150480
type: QuestionComment
has text: Yeah I know, I was thinking more about later on when I will be setting up an "application deep performance monitoring system" when I will just be sending requests to a backend that will report me back the application health (error percentage per function / per batch / exec time / means ) etc.. Thank you for your answers anyway
comment on: http://stackoverflow.com/q/50567925
score: 0
type: Comment

http://stackoverflow.com/comment/88146877
type: QuestionComment
has text: @Micolho i changed it to /news/... but still got the same error
comment on: http://stackoverflow.com/q/50568252
score: 0
type: Comment

http://stackoverflow.com/comment/88178781
comment on: http://stackoverflow.com/q/50583871
type: Comment
type: QuestionComment
score: 0
has text: I can't offer more (it's not my area of expertise) and you will need to decide if those alternatives are worth some attempt (coding needed). But just taking your number + quadratic complexity with some pretty dumb calculation (assuming byte = char) like: ```10kB = 10240 B -> 10240^2 = 104.857.600```, 100ms looks quite fast (to me).

http://stackoverflow.com/comment/88399336
comment on: http://stackoverflow.com/a/50694894
type: AnswerComment
has text: I see what your saying. So for example, if I call the URL endpoint I would still be calling the same function in the API View and same goes for the profile view correct?
type: Comment
score: 1

http://stackoverflow.com/comment/104443536
type: Comment
score: 1
type: AnswerComment
has text: What if you have no clue about all other parameters because they use the default palette?
comment on: http://stackoverflow.com/a/50594298

http://stackoverflow.com/q/50676165
score: 0
answer count: 1
tagged with: yield
has title: Python strange yield behavior in recursive function
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88362077
has answer: http://stackoverflow.com/a/50676204
type: Question
tagged with: recursion
has body: This is just a demo code to understand the yield behavior in a recursive function. I expect it to return an iterable list [5,4,3] but it stops at the first iteration and only returns [5] Can anyone explain why this happens? def yield_test(input): if input &gt; 3: yield_test(input-1) yield input print(list(yield_test(5))) output: [5] Expected output: [5, 4, 3]

http://stackoverflow.com/comment/88106030
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50547526
type: Comment
has text: @PRMoureu everything works fine but the error comes up when i try to zip a file from the TreeView

http://stackoverflow.com/a/50673800
answers question: http://stackoverflow.com/q/50662773
score: 8
accepted answer of: http://stackoverflow.com/q/50662773
type: Answer
has body: Issue In the line imgtk = ImageTk.PhotoImage(image=cv2image), you are passing a numpy array (cv2image) as input to ImageTk.PhotoImage. But the source code of PIL.ImageTk mentions that it requires a PIL image. This is what source code of PIL.ImageTk mentions for init() of PhotoImage. class PhotoImage(object): ..... :param image: Either a PIL image, or a mode string. If a mode string is used, a size must also be given. Solution So basically, you will have to convert the numpy array to a PIL Image and then pass it to ImageTk.PhotoImage(). So, can you replace the line imgtk = ImageTk.PhotoImage(image=cv2image) with imgtk = ImageTk.PhotoImage(image=PIL.Image.fromarray(cv2image))? This would convert the numpy array to a PIL Image and it would be passed into the method. References I extracted the code for converting a numpy array to PIL Image from this source.
downvote count: 1
upvote count: 9
type: AcceptedAnswer

http://stackoverflow.com/comment/88289952
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50638902
score: 0
has text: Adding ["amount"] like that results in TypeError

http://stackoverflow.com/a/59842060
score: 0
answers question: http://stackoverflow.com/q/50663803
has body: Hi since every batch should contain images of the same dimension, your CustomSampler works just fine, it needs to be passed as an argument to mx.gluon.data.DataLoader, with the keyword, batch_sampler. However, as stated in the docs, do remember this: "Do not specify shuffle, sampler, and last_batch if batch_sampler is specified"
type: Answer

http://stackoverflow.com/q/50681241
accepted answer: http://stackoverflow.com/a/50694164
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/88397535
answer count: 1
has answer: http://stackoverflow.com/a/50694164
tagged with: pyinstaller
tagged with: python
has comment: http://stackoverflow.com/comment/88385981
has body: I created an .exe of my python code using pyinstaller and it was working fine. But after importing this specific package "from ciscoconfparse import CiscoConfParse ", pyinstaller is able to create the .exe but when i execute the .exe it throws an error message Please see this image link I tried to do the workaround as mentioned in some other posts but none seem to work and this problem is seen only when i use ciscoconfparse module. Please help how can i get around this problem, it is important to use this module.
has comment: http://stackoverflow.com/comment/88384645
type: AnsweredQuestion
tagged with: ciscoconfparse
has comment: http://stackoverflow.com/comment/88385717
has comment: http://stackoverflow.com/comment/88384585
has title: PyInstaller: IOError: [Errno 2] No such file or directory: with ciscoconfparse library
type: Question
has comment: http://stackoverflow.com/comment/88378780

c#
tags question: http://stackoverflow.com/q/50698638
tags question: http://stackoverflow.com/q/50635797
tag name: c#
tags question: http://stackoverflow.com/q/50564191
tags question: http://stackoverflow.com/q/50696957
tags question: http://stackoverflow.com/q/50683833
tags question: http://stackoverflow.com/q/50599579
tags question: http://stackoverflow.com/q/50685762
tags question: http://stackoverflow.com/q/50664853
type: Tag
tags question: http://stackoverflow.com/q/50670553

http://stackoverflow.com/comment/88143627
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50566577
has text: No problem. I am a little bit frustrated I can't come up with something elegant for the tree search though..hope you have more luck. :)
type: AnswerComment

http://stackoverflow.com/comment/103296364
comment on: http://stackoverflow.com/a/50686741
has text: There is a `weighted_binary_crossentropy` loss function defined here for multi-label problems where there is a lot of negative predictions: https://stats.stackexchange.com/a/313922/198729. However I'm also looking for a `weighted_binary_accuracy` as well.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88174337
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50582647
has text: What's wrong with [`random.gauss`](https://docs.python.org/3/library/random.html#random.gauss) ?

http://stackoverflow.com/comment/88313032
comment on: http://stackoverflow.com/q/50650521
score: 0
type: QuestionComment
type: Comment
has text: I am using `os.path.dirname(__file__)` to get the path of the script that I am running, and as such, I can go to the root of my project easily. Would that be enough to be added to PYTHONPATH, or there is something else that I should do? I did notice no difference (the script fail anyway when running from terminal), if I add the CWD to sys.path with sys,path.insert()

http://stackoverflow.com/comment/88314467
type: Comment
type: QuestionComment
has text: Yea you can ignore all the password stuff - behavior is the same
comment on: http://stackoverflow.com/q/50651684
score: 0

http://stackoverflow.com/comment/88368865
comment on: http://stackoverflow.com/q/50679638
score: 0
has text: Ah, you're only concerned with the column name header: `Month, Data mean, Data count...`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88166485
type: Comment
comment on: http://stackoverflow.com/a/50565951
has text: I guess, Storing all data into memory for 100 columns * single row dataframe. it works
score: 0
type: AnswerComment

http://stackoverflow.com/a/50645448
has comment: http://stackoverflow.com/comment/88301914
type: Answer
accepted answer of: http://stackoverflow.com/q/50645349
upvote count: 3
score: 3
has body: you're passing a generator comprehension to write, which needs strings. If I understand correctly you want to write one representation of tuple per line. You can achieve that with: outfile1.write("".join('{}\n'.format(ele) for ele in bigram)) or outfile1.writelines('{}\n'.format(ele) for ele in bigram) the second version passes a generator comprehension to writelines, which avoids to create the big string in memory before writing to it (and looks more like your attempt) it produces a file with this content: ('a', 'b') ('b', 'b') ('b', 'b') ('b', 'c') ('c', 'c') ('c', 'c') ('c', 'd') ('d', 'd') ('d', 'e')
has comment: http://stackoverflow.com/comment/88301716
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50645349

http://stackoverflow.com/comment/88232818
type: Comment
has text: The <Result 'Customers'> >>> was automated when I pressed enter. The only part that I did is everything before that.
type: QuestionComment
comment on: http://stackoverflow.com/q/50611275
score: 0

http://stackoverflow.com/q/50684578
accepted answer: http://stackoverflow.com/a/50684980
score: 0
has comment: http://stackoverflow.com/comment/88379089
upvote count: 1
tagged with: parent
has comment: http://stackoverflow.com/comment/88379636
tagged with: python
tagged with: dictionary
favorite count: 0
has answer: http://stackoverflow.com/a/50684980
has answer: http://stackoverflow.com/a/50685780
downvote count: 1
has body: I have the following dictionary representing id:parent. {1: 2, 3: 1}. I need to loop and check if id == parent then it is a child. For example here: 1=1 so 3 is the child of 1. I will append it to the dictionary accordingly. Any ideas? d={1:2, 3:1} for node in d:
type: AnsweredQuestion
tagged with: children
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/50685780
linked to: http://stackoverflow.com/q/15675261
has title: I have a python dictionary where i need to find the children of the nodes if available

http://stackoverflow.com/a/50586823
type: Answer
has body: df_train.index = pd.RangeIndex(len(df_train.index)) fixed the problem for me.
answers question: http://stackoverflow.com/q/50586248
score: 0

http://stackoverflow.com/comment/88126743
has text: Nope, it should give you the directory you're working in on the command line
type: AnswerComment
comment on: http://stackoverflow.com/a/50557957
score: 0
type: Comment

http://stackoverflow.com/a/50626835
has body: Skip the first line in the CSV file, that header line, then process the remaining lines. csv_data = csv.reader(file('db_columns.csv')) # retrieve the header line and discard it next(csv_data, None) for row in csv_data: I think the error is from the first line, the string value "ID" is being assigned to a double. That will evaluate to 0 in MySQL, but that conversion will cause MySQL to throw either an error or a warning. The behavior depends on the setting of sql_mode for the session.
type: Answer
answers question: http://stackoverflow.com/q/50626573
score: 0

http://stackoverflow.com/comment/88266582
has text: How first and second differentiating between 0 and 1?
score: 0
comment on: http://stackoverflow.com/a/50628131
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50690383
has body: You missed one possibility: Define a bark method that raises NotImplementedError, as in your option 4, but don't make it abstract. This eliminates PyLint's complaint—and, more importantly, eliminates the legitimate problem it was complaining about. As for your other options: hasattr is unnecessary LBYL, which is usually not Pythonic. The except problem can be handled by doing bark = self.bark inside a try block, then doing bark() if it passes. This is sometimes necessary, but the fact that it's a bit clumsy and hasn't been "fixed" should give you an idea of how often it's worth doing. Inspecting error messages is an anti-pattern. Anything that's not a separate, documented argument value is subject to change across Python versions and implementations. (Plus, what if ManWithSidekick.bark() does self.sidekick.bark()? How would you distinguish the AttributeError there?) So, that leaves 2, 4.5, and 5. I think in most cases, either 4.5 or 5 will be the right thing to do. The difference between them is not pragmatic, but conceptual: If a ScaryCat an animal that barks silently, use option 5; if not, then barking must be an optional part of protection that not all protectors do, in which case use option 4.5. For this toy example, I think I'd use option 4.5. And I think that will be the case with most toy examples you come up with. However, I suspect that most real-life examples will be pretty different: Most real-life examples won't need this deep hierarchy. Of those that do, usually either bark will either be implemented by all subclasses, or won't be called by the superclass. Of those that do need this, I think option 5 will usually fit. Sure, barking silently is not something a ScaryCat does, but parse_frame silently is something a ProxyProtocol does. And there are so few exceptions left after that, that it's hard to speak about them abstractly and generally.
answers question: http://stackoverflow.com/q/50690286
upvote count: 1
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/50695844
tagged with: python-3.x
type: Question
tagged with: python
score: -1
has body: Python - Identify certain keywords in a user's input, to then lead to an answer. For example, user inputs "There is no display on my phone" The keywords 'display' and 'phone' would link to a set of solutions. I just need help finding a general idea on how to identify and then lead to a set of solutions. I would appreciate any help.
has title: Python - Identify certain keywords in a user's input, to then lead to an answer
has comment: http://stackoverflow.com/comment/88401717
answer count: 2
downvote count: 1
has answer: http://stackoverflow.com/a/50710319
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50697442
upvote count: 0
favorite count: 0

http://stackoverflow.com/comment/88255857
type: Comment
type: QuestionComment
score: 0
has text: Sure, there are always alternatives. In fact if you check out the bounty questions, you can have several answers there as to how you can play with dynamic sites. Check out [this one](https://stackoverflow.com/questions/8049520/web-scraping-javascript-page-with-python)
comment on: http://stackoverflow.com/q/50622856

http://stackoverflow.com/comment/88213985
comment on: http://stackoverflow.com/q/50602387
type: Comment
type: QuestionComment
score: 2
has text: fyi: https://docs.python.org/3/tutorial/floatingpoint.html

http://stackoverflow.com/q/50566218
type: Question
has answer: http://stackoverflow.com/a/50567139
answer count: 2
accepted answer: http://stackoverflow.com/a/50566232
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50567139
downvote count: 0
has body: This code: d = {'col1': [1, 2], 'col2': [3, 4]} df = pd.DataFrame(data=d) print(df.loc[0], df.loc[1]) Gives next output: col1 1 col2 3 Name: 0, dtype: int64 col1 2 col2 4 Name: 1, dtype: int64 But I want something like that (because I want to print a lot of pairs of rows in a cycle from two different dataframes): 1 3, 2 4 Notice that I want to see output in a single row.
favorite count: 0
has title: Print pandas row in a single string (jupyter notebook)
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50566232
upvote count: 1

http://stackoverflow.com/comment/88112825
type: Comment
type: QuestionComment
has text: The order of entries could change dependent on day, computer architecture, used python version, environment variables, OS, wheather, stellar constellation etc. so it's always best to force a specific order.
score: 0
comment on: http://stackoverflow.com/q/50550887

http://stackoverflow.com/a/50594273
answers question: http://stackoverflow.com/q/50593797
type: Answer
has comment: http://stackoverflow.com/comment/88214959
has comment: http://stackoverflow.com/comment/88210559
score: 2
has comment: http://stackoverflow.com/comment/88212860
downvote count: 0
has comment: http://stackoverflow.com/comment/88207973
has comment: http://stackoverflow.com/comment/88215476
upvote count: 2
has body: instead of grouping &amp; expanding the mean, filter the dataframe on the conditions, and calculate the mean of DPD: Customer == current row's Customer Deposit_Date &lt; current row's Deposit_Date Use df.apply to perform this operation for all row in the dataframe: df['PreviousMean'] = df.apply( lambda x: df[(df.Customer == x.Customer) &amp; (df.Deposit_Date &lt; x.Deposit_Date)].DPD.mean(), axis=1) outputs: Customer Deposit_Date DPD PreviousMean 0 John 2017-01-01 10 NaN 1 John 2017-02-02 15 10.0 2 John 2017-02-02 20 10.0 3 John 2017-03-03 30 15.0 4 Sue 2017-01-01 10 NaN 5 Sue 2017-02-02 15 10.0 6 Sue 2017-03-02 20 12.5 7 Sue 2017-03-03 7 15.0 8 Sue 2017-04-04 20 13.0

http://stackoverflow.com/comment/88391722
has text: its the same that you proposed
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50690746
type: AnswerComment

http://stackoverflow.com/q/50668190
score: 0
has answer: http://stackoverflow.com/a/50668275
favorite count: 0
has comment: http://stackoverflow.com/comment/88346706
has answer: http://stackoverflow.com/a/50668271
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
has title: Python - Django project - DateTimeField format
downvote count: 1
linked to: http://stackoverflow.com/q/10541640
has body: I want to change the format of the Date in my Django project. Now it looks like this: "June 3, 2018, 2:19 p.m.", and I want something like: "23,Oct 2018 - 18H23m". The model that I have its setting this time: date = models.DateTimeField(auto_now_add=True) How can I format the date to the way I want? Are there any other parameters that allow me to do this? I have just started working with django 2 days ago. I tried to search around but didnt find any answer.
type: Question
answer count: 2

http://stackoverflow.com/a/66734972
type: Answer
downvote count: 0
has body: I had the same problem, and i solved it by adding .\ before so it would be like this .\cloud_sql_proxy.exe -instances=&quot;[YOUR_INSTANCE_CONNECTION_NAME]&quot;=tcp:3306 and I used PowerShell instead of normal cmd
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50549063

http://stackoverflow.com/q/50595573
upvote count: 3
answer count: 3
tagged with: image-stitching
tagged with: python
possible better answer: http://stackoverflow.com/a/54243132
linked to: http://stackoverflow.com/q/34362922
downvote count: 0
has answer: http://stackoverflow.com/a/54243132
tagged with: opencv
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/57376162
type: Question
has body: Based on this question/answer, I have been trying to use OpenCV's Stitcher class in python. My code is basically the same as in the answer. import cv2 stitcher = cv2.createStitcher(False) foo = cv2.imread("D:/foo.png") bar = cv2.imread("D:/bar.png") result = stitcher.stitch((foo,bar)) cv2.imwrite("D:/result.jpg", result[1]) The issue is I want to change the mode from Panoramic to Scans. In the c++ documentation, the create method has an input of mode. However, the createStitcher class in Python only takes one input- whether or not to try gpu. Is there a way to specify the mode in Python? When I tried createStitcherScans, I get an error stitcher = cv2.createStitcherScans(False) "AttributeError: 'module' object has no attribute 'createStitcherScans'" I did find this GitHub issue that seems relevant, regarding Python bindings missing something. But this is over my head and I am not sure how to edit the opencv code to do this properly. I tried adding this to the stitching.hpp: typedef Stitcher::Mode Mode; But nothing happened. createStitcher(1, False) still give me the attribute error. Any help would be greatly appreciated.
has answer: http://stackoverflow.com/a/67214552
has comment: http://stackoverflow.com/comment/90452123
has answer: http://stackoverflow.com/a/57376162
favorite count: 0
has title: How to Set Panorama Mode in OpenCV Python Stitcher Class?

http://stackoverflow.com/comment/88192683
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50586739
has text: **@user3647488**, I have updated my answer with 2 more examples **Example 3.1** & **3.2** which is based on the inputs provided in the above comment. If still there's an issue please let me know. Thanks again to provide inputs and expected output.
type: AnswerComment

http://stackoverflow.com/a/50632695
has body: My answer may not give the solution you are looking for but I will take a stab at it. You have not stated what check is done after you get the return value from the function login_result. If the return value is not asserted, and I guess thats why your code just moves on with the execution. And there is no exception raised within the function, it is designed to return and have the user do something with the result def login(driver): # Check if logged in (or login failed) login_check_elements = driver.find_elements_by_tag_name('button') for login_check in login_check_elements: if login_check.text == "Log in" and login_check.is_enabled(): # If there is a login button on the screen and the button is enabled by default it means # that the driver is on the account page and is not logged in return False else: username, password = find_input_elements(driver) username.send_keys("username") time.sleep(randint(1, 3)) password.send_keys("password") time.sleep(randint(1, 3)) login_button = find_login_button(driver) login_button.click() return True login_result = login(driver) if not login_result: # Error out or do something
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/88285720
answers question: http://stackoverflow.com/q/50629337

http://stackoverflow.com/q/50642883
has comment: http://stackoverflow.com/comment/88296479
has answer: http://stackoverflow.com/a/50643192
type: AnsweredQuestion
tagged with: slice
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/50643192
tagged with: arrays
answer count: 1
score: 0
has body: I have a "large" numpy array like follows: from numpy import array large = array([[-0.047391 , -0.10926778, -0.00899118, 0.07461428, -0.07667476, 0.06961918, 0.09440736, 0.01648382, -0.04102225, -0.05038805, -0.00930337, 0.3667651 , -0.02803499, 0.02597451, -0.1218804 , 0.00561949], [-0.00253788, -0.08670117, -0.00466262, 0.07330351, -0.06403728, 0.00301005, 0.12807456, 0.01198117, -0.04290793, -0.06138136, -0.01369276, 0.37094407, -0.03747804, 0.04444246, -0.01162705, 0.00554793]]) And a "small" array that was subsetted from large. small = array([[-0.10926778, -0.07667476, 0.09440736], [-0.08670117, -0.06403728, 0.12807456]]) Without any other information, how could we identify the column indices in large from which the small array was generated? In this case, the answer is 1, 4, 6 (starting at 0 as done in python). What would be a generalizable way to determine this?
tagged with: python
has title: Identifying column indices that a subsetted np array came from in larger np array

http://stackoverflow.com/a/52237389
answers question: http://stackoverflow.com/q/50655738
has comment: http://stackoverflow.com/comment/115975978
has comment: http://stackoverflow.com/comment/104043334
downvote count: 0
upvote count: 133
has comment: http://stackoverflow.com/comment/126485553
type: Answer
score: 133
has comment: http://stackoverflow.com/comment/126486511
has body: I got this error because I installed pytesseract with pip but forget to install the binary. On Linux sudo apt update sudo apt install tesseract-ocr sudo apt install libtesseract-dev On Mac brew install tesseract On Windows download binary from https://github.com/UB-Mannheim/tesseract/wiki. then add pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe' to your script. (replace path of tesseract binary if necessary) references: https://pypi.org/project/pytesseract/ (INSTALLATION section) and https://github.com/tesseract-ocr/tesseract/wiki#installation

http://stackoverflow.com/q/50603671
has body: eg. correct sample - f.write("\t" +connection_name+ "\t =" + qs.connection_name + "\n") what I'm trying to do - f.write("\t" +current+ "\t=" +qs.current+ "\n") //here current = 'connection_name' How to concatenate in this kind - qs.current so that it prints as qs.connection_name's value
favorite count: 0
has comment: http://stackoverflow.com/comment/88217213
tagged with: python-2.7
upvote count: 3
downvote count: 1
has comment: http://stackoverflow.com/comment/88216560
tagged with: python
has answer: http://stackoverflow.com/a/50603722
accepted answer: http://stackoverflow.com/a/50603722
score: 2
type: AnsweredQuestion
type: Question
has title: How to concatenate variables like this in python
answer count: 1

http://stackoverflow.com/q/50552501
has answer: http://stackoverflow.com/a/50552891
has body: client = docker.from_env() data = client.containers.run("namecontainer:1.0", ['param'],detach=True) file_json = data.get_archive(data, '/wd/out.json') How make it? How get file out.json? I don't understand.
tagged with: docker
answer count: 2
downvote count: 0
has title: How get file from docker container in python
favorite count: 0
accepted answer: http://stackoverflow.com/a/50552891
tagged with: python
type: AnsweredQuestion
upvote count: 3
possible better answer: http://stackoverflow.com/a/78762561
has answer: http://stackoverflow.com/a/78762561
type: Question
score: 3

http://stackoverflow.com/q/50569697
has answer: http://stackoverflow.com/a/75056525
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/75056525
has title: Django - Export List of dictionaries to CSV
has comment: http://stackoverflow.com/comment/88149311
has answer: http://stackoverflow.com/a/50570285
score: 0
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/50570285
has body: I have created a list of dictionaries in views.py, my_list= [ {'user': 1000, 'account1': 100, 'account2': 200, 'account3': 100}, {'user': 1001, 'account1': 110, 'account2': 100, 'account3': 250}, {'user': 1002, 'account1': 220, 'account2': 200, 'account3': 100}, ] I want to export it to csv file. response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="mylist.csv"' writer = csv.writer(response) for data in my_list: writer.writerow(data) return response I know there is a error for "for data in my_list". my_list contains all the keys and values. How to get only keys for my_list? or there is another method to export list to csv? (I'm using django 2 with python3.4)
type: AnsweredQuestion

http://stackoverflow.com/comment/88269263
comment on: http://stackoverflow.com/q/50625567
score: 0
has text: @wwii `sfc_p` is an array containing surface pressure values on a latitude-longitude grid with additional time and ensemble dimensions. Using `sfc_p.values[sfc_p.shape[:]]` I am trying to take every value from this array and for each of them to compute the corresponding 137 (in this case) values for the new vertical dimension.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88200208
has text: @nedimk994 Please consider accepting this answer if it solved your problem.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50576921

http://stackoverflow.com/comment/88171008
type: Comment
comment on: http://stackoverflow.com/a/50580671
type: AnswerComment
has text: If you sort in reverse, you can then use `next(j)` instead of building a list and taking the last item...
score: 0

http://stackoverflow.com/comment/88384030
type: Comment
has text: ohhh you're trying to pass by reference... Python doesn't have that.
score: 0
comment on: http://stackoverflow.com/q/50687047
type: QuestionComment

http://stackoverflow.com/a/53349976
type: Answer
has comment: http://stackoverflow.com/comment/97252377
has body: The accepted answer above is not working in the current Keras version. Here is the version that's working: class ReflectionPadding2D(Layer): def __init__(self, padding=(1, 1), **kwargs): self.padding = tuple(padding) self.input_spec = [InputSpec(ndim=4)] super(ReflectionPadding2D, self).__init__(**kwargs) def compute_output_shape(self, s): """ If you are using "channels_last" configuration""" return (s[0], s[1] + 2 * self.padding[0], s[2] + 2 * self.padding[1], s[3]) def call(self, x, mask=None): w_pad,h_pad = self.padding return tf.pad(x, [[0,0], [h_pad,h_pad], [w_pad,w_pad], [0,0] ], 'REFLECT')
downvote count: 0
has comment: http://stackoverflow.com/comment/97720012
has comment: http://stackoverflow.com/comment/124399140
score: 10
has comment: http://stackoverflow.com/comment/97262355
answers question: http://stackoverflow.com/q/50677544
has comment: http://stackoverflow.com/comment/110930860
upvote count: 10

http://stackoverflow.com/comment/88301765
comment on: http://stackoverflow.com/q/50642738
has text: Related question: https://stackoverflow.com/questions/29323849/mapping-wordnet-senses-to-verbnet
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50617474
score: 1
upvote count: 1
has body: i think you expect this from your code..i did some changes.your while loop didn't stop because it didn't have a reason to stop.it is testing same value again and again against condition def agetest(): age = input("Please enter the customer's age: ") age = int(age) if 0&lt;age &lt;= 3: print("Welcome little buddy, no charges for you!") agetest() elif age &gt; 3 and age &lt; 12: print("The ticket price is $10") agetest() elif age &gt;= 12: print("The ticket price is 15") agetest() elif age == -1: print("thnks") agetest() here is the answer with while loop age=0 while(age!= -1): print("Please enter the customer's age: ") age = int(input()) if 0&lt;age &lt;= 3: print("Welcome little buddy, no charges for you!") elif age &gt; 3 and age &lt; 12: print("The ticket price is $10") elif age &gt;= 12: print("The ticket price is 15") elif age == -1: print("thanks")
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88244822
accepted answer of: http://stackoverflow.com/q/50617261
type: Answer
answers question: http://stackoverflow.com/q/50617261

pyx
tags question: http://stackoverflow.com/q/50621257
tag name: pyx
tags question: http://stackoverflow.com/q/50570100
type: Tag

http://stackoverflow.com/comment/88179535
has text: Does this do the right thing when there are multiple `<BBB>` to be found?
type: AnswerComment
comment on: http://stackoverflow.com/a/50585113
score: 0
type: Comment

http://stackoverflow.com/comment/88387998
type: AnswerComment
has text: E0001:invalid syntax (<string>, line 19) The error throws when I set myamount to payload['amount']
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50689120

http://stackoverflow.com/q/50691734
has title: How to receive and return string in webapp2 from android?
upvote count: 2
tagged with: google-app-engine
tagged with: android
tagged with: python
has answer: http://stackoverflow.com/a/50691978
score: 2
type: AnsweredQuestion
type: Question
tagged with: webapp2
accepted answer: http://stackoverflow.com/a/50691978
has body: I am struggling to receive a string into my webapp2 server. The android device is supposed to send a string nameto the server then the server returns back to the phone "your name is: " + name. The server is only returning to android"your name is: " because the name string seems to be null on the server side. I am not sure if the problem is on android or server side. My code is as follows: ANDROID.java Thread thread = new Thread(new Runnable() { @Override public void run() { try { String name = "Jay"; String serverURL = "http://myapp.appspot.com"; URL url = new URL(serverURL); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); try{ httpURLConnection.setReadTimeout(15000); httpURLConnection.setConnectTimeout(15000); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); OutputStream outputStream = new BufferedOutputStream(httpURLConnection.getOutputStream()); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); String post_data = URLEncoder.encode(name,"UTF-8"); writer.write(post_data); writer.flush(); writer.close(); outputStream.close(); InputStream inputStream = new BufferedInputStream(httpURLConnection.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1")); String result=""; String line=""; while((line = reader.readLine())!= null) result += line; reader.close(); inputStream.close(); } catch (MalformedURLException e) { e.printStackTrace(); } finally { httpURLConnection.disconnect(); } } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); SERVER.py import webapp2 class MainHandler(webapp2.RequestHandler): def post(self): name = self.request.get('content') self.response.out.write("Your name is: " + name) def get(self): self.response.write("Hello World") app = webapp2.WSGIApplication([ ('/', MainHandler) ], debug=True)
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/88251343
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50620609
has text: My bad, I should have read the whole question. I thought he wanted a shortcut to find the max of 3 numbers.
score: 0

http://stackoverflow.com/comment/88310367
type: QuestionComment
comment on: http://stackoverflow.com/q/50649754
score: 0
has text: Can you add a few lines of the content of `AeropuertosArg.csv` to the question?
type: Comment

http://stackoverflow.com/comment/88115822
type: QuestionComment
has text: @HelpMe it's still not an excuse to edit the question with a new question after it's been asked. See [How much change to the question is too much?](https://meta.stackoverflow.com/questions/290297/how-much-change-to-the-question-is-too-much)
score: 0
comment on: http://stackoverflow.com/q/50551020
type: Comment

http://stackoverflow.com/q/50652341
tagged with: python
has comment: http://stackoverflow.com/comment/88315791
answer count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/88315480
has body: I am a novice programmer, but have been working on a plugin for MusicBrainz Picard application using python. The add-in is designed to get artist/track data from last.fm's API to automatically rate tracks. However, I get an error and would be grateful if anybody could help me. The error is: E: 19:37:25 Network request error for https://ws.audioscrobbler.com:443/2.0/?method=artist.getinfo&amp;artist=2%2520Chainz&amp;api_key=0a8b8f968b285654f9b4f16e8e33f2ee&amp;format=json: Error downloading https://ws.audioscrobbler.com:443/2.0/%3Fmethod=artist.getinfo&amp;artist=2%252520Chainz&amp;api_key=0a8b8f968b285654f9b4f16e8e33f2ee&amp;format=json - server replied: Not Found (QT code 203, HTTP code 404) E: 19:37:25 LastFM AutoRate: Track 2 Chainz (Fork) Error parsing response: No JSON object could be decoded Here is the code: PLUGIN_NAME = 'LastFM AutoRate' PLUGIN_AUTHOR = 'Zachary Zuno' PLUGIN_DESCRIPTION = '''Use LastFM to automatically rate your music library.''' PLUGIN_VERSION = "0.1" PLUGIN_API_VERSIONS = ["0.15"] from PyQt4 import QtCore from json import loads from functools import partial from picard import log from picard.metadata import register_track_metadata_processor from picard.webservice import REQUEST_DELAY from picard.webservice import XmlWebService LASTFM_HOST = "ws.audioscrobbler.com" LASTFM_PORT = 443 LASTFM_KEY = "0a8b8f968b285654f9b4f16e8e33f2ee" LASTFM_PATH = "/2.0" REQUEST_DELAY[(LASTFM_HOST, LASTFM_PORT)] = 50 def encode_str(s): # Yes, that's right, Last.fm prefers double URL-encoding s = QtCore.QUrl.toPercentEncoding(s) s = QtCore.QUrl.toPercentEncoding(unicode(s)) return s def result(album, metadata, data, reply, error): listeners = [] playcount = [] try: data = loads(data)["artist"] for k, v in data.items(): if k.startswith("stats"): listeners.append(v["listeners"]) if k.startswith("stats"): playcount.append(v["playcount"]) metadata["listeners"] = listeners metadata["playcount"] = playcount log.debug(u"%s: Track %s (%s) Parsed response (listeners: %s…
type: Question
has comment: http://stackoverflow.com/comment/88315840
upvote count: 2
score: 0
has comment: http://stackoverflow.com/comment/88315749
favorite count: 0
has comment: http://stackoverflow.com/comment/88315533
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88315709
has title: Python URL Encoding Error

http://stackoverflow.com/comment/107892712
type: AnswerComment
has text: Nice @Shivam Bharadwaj , I did it same way
type: Comment
comment on: http://stackoverflow.com/a/54979355
score: 0

http://stackoverflow.com/comment/88349480
comment on: http://stackoverflow.com/a/50669262
type: Comment
has text: Yes, you can just add the costs. If the cost you already have is a tensor, then tensorflow will convert the cost coming from IoU into a tensor and will map the '+' to `tf.add()`. All the gradient's stuff will be automatically managed by TF.
score: 0
type: AnswerComment

http://stackoverflow.com/q/50544556
tagged with: docker
type: Question
tagged with: python
has title: git push heroku masterHow do I Migrate Django App on Heroku from git deploy to container deploy?
has answer: http://stackoverflow.com/a/50546723
score: 0
has comment: http://stackoverflow.com/comment/88103465
tagged with: django
has comment: http://stackoverflow.com/comment/88106163
answer count: 1
tagged with: heroku
has comment: http://stackoverflow.com/comment/88110439
has body: Now that Heroku supports deploying an app straight from you docker image. I would like to migrate my existing Django app, Which is already running on heroku (using the standard deploy methodology: git push heroku master) to a Container based app (see here, but without loosing all the configuration already done (postgreSQL, mainly). The documentation linked above shows how to start from scratch but not how to migrate in cases you already have an app setup the old fashioned way. Is there a easy way to migrate git app to a container app? I have searched a lot and couldn't find any tutorial that did not assume that you where creating a new app from scratch. Can it be done?
has comment: http://stackoverflow.com/comment/88146347
type: UnansweredQuestion

http://stackoverflow.com/comment/88152612
type: QuestionComment
comment on: http://stackoverflow.com/q/50571412
score: 0
has text: But that's what you've told it to do. What do you actually want to happen?
type: Comment

http://stackoverflow.com/comment/88255308
type: QuestionComment
has text: "Further changes to self.A will not automatically update matrix." It will! Because `self.A` is a mutable type, `matrix` and `self.A` point to the same object, so both will be changed when you change one of them.
score: 1
comment on: http://stackoverflow.com/q/50622587
type: Comment

http://stackoverflow.com/q/50635294
has comment: http://stackoverflow.com/comment/88280698
type: Question
has title: How can I get the top 3 strings with the highest value in this program?
has comment: http://stackoverflow.com/comment/88280695
score: -2
has body: I have a python program where I print strings like @SP_YSNSB id=0 0054 log out @SP_23RTY id=0 0387 pop @TRIO_9078 id=0 0098 hench @TRE_4657838.c id=0 0056 pop @WRYE_LKP.CO id=0 0078 ffg The "@SP_23RTY" is the header and "0387 pop" is the number of lines executed before it looped out. How can I print the top 3 headers with the top 3 highest values of lines? The output should be @SP_23RTY id=0 0387 pop @TRIO_9078 id=0 0098 hench @WRYE_LKP.CO id=0 0078 ffg Any help would be appreciated.
downvote count: 2
accepted answer: http://stackoverflow.com/a/50635361
tagged with: python
answer count: 1
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/50635361
favorite count: 0

http://stackoverflow.com/comment/88326160
type: Comment
comment on: http://stackoverflow.com/a/50654995
type: AnswerComment
has text: Yes that is indeed strange. maybe a 3rd person could enlighten us! :) I posted the code I am running
score: 0

http://stackoverflow.com/a/50674462
has comment: http://stackoverflow.com/comment/88371846
score: 5
upvote count: 5
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50606970
type: Answer
accepted answer of: http://stackoverflow.com/q/50606970
has body: is there way (some option) to make the Spark connector behave the way I want it to behave? Yes, you can set the replaceDocument to false. For example, using MongoDB connector for Spark v2.2.2 and Apache Spark v2.3 in Python: df = sqlContext.read.format("com.mongodb.spark.sql.DefaultSource") .option("spark.mongodb.input.uri", "mongodb://host101:27017/dbName.collName").load() df.first() &gt; Row(_id=1.0, age=10.0, foo=20.0) # Create a dataframe d = {'_id': [1, 2], 'val':['a', 'b']} inputdf = pd.DataFrame(data=d) sparkdf = sqlContext.createDataFrame(inputdf) # Write to Spark sparkdf.write.format("com.mongodb.spark.sql.DefaultSource") .mode("append").option("spark.mongodb.output.uri", "mongodb://host101:27017/dbName.collName") .option("replaceDocument", "false") .save() # Result +---+----+----+---+ |_id| age| foo|val| +---+----+----+---+ |1.0|10.0|20.0| a| |2.0|null|null| b| +---+----+----+---+

http://stackoverflow.com/q/50613188
tagged with: python
has answer: http://stackoverflow.com/a/50613637
has title: How do I create new JSON data after every script run
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88236680
has comment: http://stackoverflow.com/comment/88236539
has comment: http://stackoverflow.com/comment/88236661
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/88236649
upvote count: 1
type: Question
has body: I have JSON data stored in the variable data. I want to make it write to a text file after every time it runs so I know which data json that is new instead of re-writting the same Json. Currently, I am trying this: Saving = firstname + ' ' + lastname+ ' - ' + email with open('data.json', 'a') as f: json.dump(Saving, f) f.write("\n") which just adds up to the json file and the beginning of the script where the first code starts, I clean it with Infotext = "First name : Last name : Email" with open('data.json', 'w') as f: json.dump(Infotext, f) f.write("\n") How can I make instead of re-write the same Json, instead create new file with Infotext information and then add up with Saving? Output in Json: "First name : Last name : Email" Hello World - helloworld@test.com Hello2 World - helloworld2@test.com Hello3 World - helloworld3@test.com Hello4 World - helloworld4@test.com Thats the outprint I wish to be. So basically it needs to start with "First name : Last name : Email" And then the Names, Lastname Email will add up below that until there is no names anymore. So basically easy to say now - What I want is that instead of clearing and add to the same json file which is data.json, I want it to create to a newfile called data1.json - then if I rerun the program again tommorow etc - it gonna be data2.json and so on.
has comment: http://stackoverflow.com/comment/88236611
has answer: http://stackoverflow.com/a/50613475
has comment: http://stackoverflow.com/comment/88236464
accepted answer: http://stackoverflow.com/a/50613637
has comment: http://stackoverflow.com/comment/88236396
possible better answer: http://stackoverflow.com/a/50613475
answer count: 3
has answer: http://stackoverflow.com/a/50613279
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88236724
has comment: http://stackoverflow.com/comment/88236729

http://stackoverflow.com/comment/88220825
score: 0
has text: whats the difference between the 0 and 1
comment on: http://stackoverflow.com/q/50603658
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50635604
score: 1
downvote count: 0
has body: edit: for a panda, pandas has DataFrame.clip. see numpy.clip. import numpy as np thing = np.arange(-5, 6) # [-5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5] clipped_thing = np.clip(thing, -3, 3) print(clipped_thing) outputs [-3 -3 -3 -2 -1 0 1 2 3 3 3]
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50635540

http://stackoverflow.com/q/50636379
tagged with: variables
tagged with: string
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I have a list of string like L = ["V01", "V02", "V03"] and I want to convert each element in L to a variable, to which I can assign a pd.DataFrame. df_list = [] for name in L: df_temp = df[df['name'] == name] df_list.append(df_temp) dd = dict(zip(L, df_list)) globals().update(dd) At this point V01, V02, and V03 are recognized as variables and when keyed in, the outputs are the respective pd.DataFrame's. Is there a way for me to reference the new variables V01, V02, and V03 without first printing them out?
has title: python - Convert a string to variable name, to which I can assign a list or pandas.DataFrame
type: Question
score: -1
tagged with: type-conversion
downvote count: 2
tagged with: pandas
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/50636617

http://stackoverflow.com/a/50684174
answers question: http://stackoverflow.com/q/50683765
downvote count: 0
has comment: http://stackoverflow.com/comment/107609215
type: Answer
has comment: http://stackoverflow.com/comment/107609468
upvote count: 6
score: 6
has body: UPDATE: 2020-03-23 for Pandas 1+: many thanks to @aiguofer for the adapted solution: na_vals = pd.io.parsers.STR_NA_VALUES.difference({'NULL','null'}) df = pd.read_csv(io.StringIO(data), na_values=na_vals, keep_default_na=False) Old answer: we can dynamically exclude 'NULL' and 'null' from the set of default _NA_VALUES: In [4]: na_vals = pd.io.common._NA_VALUES.difference({'NULL','null'}) In [5]: na_vals Out[5]: {'', '#N/A', '#N/A N/A', '#NA', '-1.#IND', '-1.#QNAN', '-NaN', '-nan', '1.#IND', '1.#QNAN', 'N/A', 'NA', 'NaN', 'n/a', 'nan'} and use it in read_csv(): df = pd.read_csv(io.StringIO(data), na_values=na_vals)

http://stackoverflow.com/a/50611161
score: 0
has body: Here's another solution using groupby: from itertools import groupby import io txt = """ zone name test_1 vsan xx * fcid 0x170024 [pwwn 10:00:00:00:c9:5f:84:93] [xxx] * fcid 0x170016 [pwwn 50:06:0e:80:16:60:ef:43] [xxxxxx] zone name test_2 vsan xx * fcid 0x170024 [pwwn 10:00:00:00:c9:5f:84:93] [xx] * fcid 0x170017 [pwwn 50:06:0e:80:16:60:ef:63] [xxx] zone name test_3 vsan yy pwwn 10:00:00:90:fa:81:bb:f2 * fcid 0x0b00c0 [pwwn 50:06:0e:80:07:e6:2e:26] """ BLANK, KEY, DATA = 0, 1, 2 def decide_line(line): if (not line) or line.isspace(): return BLANK else: return KEY if line.startswith('zone') else DATA data_map = {} with io.StringIO(txt) as f: #with with open('file.txt') as f: key = None for data_type, lines in groupby(map(str.strip, f), decide_line): if data_type == KEY: key = next(lines).split()[2] elif data_type == DATA: data_map[key] = list(lines)
type: Answer
answers question: http://stackoverflow.com/q/50592769

http://stackoverflow.com/a/50623844
has comment: http://stackoverflow.com/comment/88280564
has body: Follow the guidelines in using expirationTime from the File Resource The time at which this permission will expire (RFC 3339 date-time). Expiration times have the following restrictions: They can only be set on user and group permissions The time must be in the future The time cannot be more than a year in the future
downvote count: 1
has comment: http://stackoverflow.com/comment/88278110
score: -1
answers question: http://stackoverflow.com/q/50620121
upvote count: 0
type: Answer

http://stackoverflow.com/comment/88158702
comment on: http://stackoverflow.com/a/50574462
has text: Thank you very much.It is working as you said. but would be possible to make output without barces '[' and ']' staring and ending and also without 'comma' in between json array.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/50657840
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50657708
has body: Use list index to access the required element and .text to print its text. Ex: from lxml import html import requests page = requests.get('https://www.germaneveryday.com/') tree = html.fromstring(page.content) Word = tree.xpath('//*[@id="main"]/div[1]/div[2]/div/h1/a')[0].text print (Word) Output: heimlich
type: Answer
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/50657708

http://stackoverflow.com/comment/88265901
type: QuestionComment
has text: A parser is do-able, but it's unclear how the desired output formula is supposed to relate to the input if/else pseudo-code, because it can't always be equivalent. A Boolean algebra formula can only return 0 or 1, but your example pseudo-code returns other values, 0.39145907 and 0.10410805. What is the the formula supposed to return in such cases?
score: 1
comment on: http://stackoverflow.com/q/50586329
type: Comment

http://stackoverflow.com/comment/88204407
score: 0
comment on: http://stackoverflow.com/q/50597592
has text: Also, if by "the most well known imports" you mean the python standard library, you're in trouble: it's all open source.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/59423531
has body: Try: sudo apt-get install libmysqlclient-dev and then: sudo apt-get install libmariadbclient-dev
score: -2
answers question: http://stackoverflow.com/q/50604948
downvote count: 2
type: Answer
upvote count: 0

http://stackoverflow.com/comment/88102783
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50545917
has text: change `test = self.buyamountsetting.text() + self.sellamountsetting.text()` to `test = int(self.buyamountsetting.text()) + int(self.sellamountsetting.text())`

http://stackoverflow.com/comment/88166071
type: QuestionComment
comment on: http://stackoverflow.com/q/50577761
has text: No the square brackets don’t work like that. They contain character sets.
score: 0
type: Comment

http://stackoverflow.com/a/50653245
has comment: http://stackoverflow.com/comment/88317033
downvote count: 0
has body: Based on the link you provided, this should work: ["https://" + str(i) + "whatever" + str(i) for i in xrange(1,11)] Gives the following output: ['https://1whatever1', 'https://2whatever2', 'https://3whatever3', 'https://4whatever4', 'https://5whatever5', 'https://6whatever6', 'https://7whatever7', 'https://8whatever8', 'https://9whatever9', 'https://10whatever10'] EDIT: This should work for paste0("https\\",1:10,"whatever",11:20) paste_list = [] for i in xrange(1,11): # replace {0} with the value of i first_half = "https://{0}".format(i) for x in xrange(1,21): # replace {0} with the value of x second_half = "whatever{0}".format(x) # Concatenate the two halves of the string and append them to paste_list[] paste_list.append(first_half+second_half) print paste_list
answers question: http://stackoverflow.com/q/50653208
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/88317103
upvote count: 1
has comment: http://stackoverflow.com/comment/88335134

http://stackoverflow.com/comment/88296661
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50643141
has text: IP767 [02/Sep/2017:00:00:00 +0200] "HEAD /record/280640 HTTP/1.1" 200 - "-" "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Geck... in a pandas dataframe

http://stackoverflow.com/comment/88233363
comment on: http://stackoverflow.com/a/50608693
score: 0
type: AnswerComment
type: Comment
has text: This was the right tool. I solved the problem by doing df / df.max(level=[0,1], axis=1).max() - Much thanks

http://stackoverflow.com/a/66600620
score: 5
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50625975
type: Answer
has body: I had the same issue. It seems that if all of your variables are integers, then it produces this error. So I have changed every integer column to string values. cluster_data = cluster_data.astype(str) cluster_data.dtypes.head() This seems to fix the error.
upvote count: 5
answers question: http://stackoverflow.com/q/50625975

http://stackoverflow.com/q/50610558
type: UnansweredQuestion
tagged with: python
tagged with: xinetd
downvote count: 0
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/88235917
type: Question
has comment: http://stackoverflow.com/comment/88235810
upvote count: 1
has body: I'm trying out an insecure Python "jail" I found somewhere, when I run it locally and and execute it, it works fine. However, when I create a xinetd service for it, I can netcat to it, it does seem to connect but I see no output what so ever. The python file is: #!/usr/bin/python -u from sys import modules modules.clear() del modules _raw_input = raw_input _BaseException = BaseException _EOFError = EOFError __builtins__.__dict__.clear() __builtins__ = None print 'Get a shell, if you can...' while 1: try: d = {'x':None} exec 'x='+_raw_input()[:50] in d print 'Return Value:', d['x'] except _EOFError, e: raise e except _BaseException, e: print 'Exception:', e The xinetd file is: service jail-hard { disable = no id = jail-hard type = unlisted wait = no socket_type = stream protocol = tcp user = root server = /usr/bin/python server_args = /home/jailuser/jail-hard.py port = 51337 } And I just simply connect with "nc ip-address port". Update 1: When I break out the jail and type in any command such as 'ls -la', I do get the output. So it seems there's something wrong with the print statements?
has title: Python "jail" no output over xinetd
favorite count: 0
has comment: http://stackoverflow.com/comment/88236086
has comment: http://stackoverflow.com/comment/88235482

http://stackoverflow.com/a/50682352
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50682184
type: Answer
has body: You can join all item into one , then we using isin , cumcount is to create the identical key for duplicate s1=df1.apply(','.join,1) s2=df2.apply(','.join,1) s3=df3.apply(','.join,1) s1=s1+','+s1.groupby(s1).cumcount().astype(str) s2=s2+','+s2.groupby(s2).cumcount().astype(str) s3=s3+','+s3.groupby(s3).cumcount().astype(str) df1['df2'],df1['df3']=s1.isin(s2).astype(int),s1.isin(s3).astype(int) df1 Out[308]: Key A B df2 df3 0 key1 a1 b1 1 1 1 key1 a1 b1 1 0 2 key1 a1 b2 0 1 3 key2 a2 b2 0 1
score: 0
accepted answer of: http://stackoverflow.com/q/50682184

http://stackoverflow.com/a/50552151
has comment: http://stackoverflow.com/comment/88115747
score: 2
has comment: http://stackoverflow.com/comment/88115219
upvote count: 2
downvote count: 0
has body: You have a typo in your code: example1.xlxs -> This extension does not exist. The correct Excelfile extension is xlsx.
answers question: http://stackoverflow.com/q/50551404
type: Answer

http://stackoverflow.com/tag/r
tags question: http://stackoverflow.com/q/50548935
tags question: http://stackoverflow.com/q/50546811
tags question: http://stackoverflow.com/q/50637376
tags question: http://stackoverflow.com/q/50580600
tags question: http://stackoverflow.com/q/50562069
tags question: http://stackoverflow.com/q/50562784
tags question: http://stackoverflow.com/q/50571460
tags question: http://stackoverflow.com/q/50651784
tag name: r
tags question: http://stackoverflow.com/q/50621641
tags question: http://stackoverflow.com/q/50567516
tags question: http://stackoverflow.com/q/50565080
type: Tag
tags question: http://stackoverflow.com/q/50573241
tags question: http://stackoverflow.com/q/50586097
tags question: http://stackoverflow.com/q/50607838
tags question: http://stackoverflow.com/q/50652935

http://stackoverflow.com/q/50646332
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/88303191
favorite count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/88303562
tagged with: attributes
has comment: http://stackoverflow.com/comment/88304621
answer count: 0
score: 1
tagged with: hdf5
upvote count: 1
type: Question
has body: I am currently trying to run a program that is supposed to read an .HDF5 file and rewrite the components into a csv file: import h5py as hdf import pandas as pd #df = pd.read_hdf('ne2011216lf.hdf5') #Specify file FILE_NAME = 'ne2011216lf.hdf5' file = hdf.File(FILE_NAME, 'r') #.select(n) will let you select the nth parameter stored in the file dat_times = file.select(0).get() dat_heights = file.select(1).get() dat_den = file.select(2).get() dsize = dat_den.shape tsize = dat_times.shape htsize = dat_heights.shape # dat_times df = pd.DataFrame.from_records(dat_den, columns = dat_times, index = dat_heights) df.to_csv('ne2011216lf.hdf5') Running this code displays an error message on the 13th line saying: "Attribute Error: 'File' object has no attribute 'select'" I have no idea how to fix this. can anyone help?
has title: 'File' object has no attribute 'select'

http://stackoverflow.com/q/50606207
downvote count: 0
has title: networkx draws independent figures on top of each other
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50606453
accepted answer: http://stackoverflow.com/a/50606453
tagged with: python
tagged with: networkx
has body: I want to draw some different topology figures in a study. However, I see that after I draw the first figure, I see it inherited in the second figure. I am using anaconda2 and its networkx package. Here is a sample code for different cases. #!/path/to/anaconda2/bin/python import numpy as np import networkx as nx import matplotlib.pyplot as plt import sys val=int(sys.argv[1]) def drawV1(numOfNodes,FilePtr): np.random.seed(0) G = nx.Graph() for ii in range(1,numOfNodes+1): G.add_node(str(ii)) nx.draw(G, with_labels = True) plt.savefig(FilePtr) # save as png def drawV2(numOfNodes,FilePtr): np.random.seed(0) G2 = nx.Graph() for ii in range(1,numOfNodes+1): G2.add_node(str(ii)) nx.draw(G2, with_labels = True) plt.savefig(FilePtr) # save as png if val==1: # Problematic case drawV1(5,'V1_1_1.png') drawV1(10,'V1_1_2.png') if val==2: # it is good when I draw only one figure drawV1(10,'V1_2_1.png') if val==3: # problem again drawV1(10,'V1_3_1.png') drawV2(10,'V2_3_2.png') I run it as ./mycode.py [1,2,3] For example for case 1, I get the following plots: 5 nodes 10 nodes (you will see previous 5 nodes too.)
type: AnsweredQuestion
score: 1
type: Question
upvote count: 1

http://stackoverflow.com/q/50618411
linked to: http://stackoverflow.com/q/51240992
answer count: 3
has answer: http://stackoverflow.com/a/61570169
downvote count: 0
tagged with: sudo
favorite count: 0
tagged with: linux
tagged with: python
possible better answer: http://stackoverflow.com/a/50618680
upvote count: 16
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50618680
tagged with: subprocess
has answer: http://stackoverflow.com/a/50629906
score: 16
has body: I am running with a user that can make root-level calls without having to supply a password. My user currently does something like this pr = subprocess.Popen("sudo sleep 100".split()) sleep(5) pr.kill() but that leads to this error because the user isn't root so it can't kill a root process Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.7/subprocess.py", line 1572, in kill self.send_signal(signal.SIGKILL) File "/usr/lib/python2.7/subprocess.py", line 1562, in send_signal os.kill(self.pid, sig) OSError: [Errno 1] Operation not permitted so I try to do something like this pr = subprocess.Popen("sudo sleep 100".split()) sleep(5) kill_pr = subprocess.Popen("sudo kill {}".format(pr.pid)) but that doesn't kill the process in question. For example, if &gt;&gt; subprocess.Popen("sudo sleep 100".split()).pid 5000 but $ pgrep sleep 5001 so it seems that the pid returned from subprocess.Popen("..").pid is one higher than the actual pid of the process running the command that I want to kill I'm assuming that the pid returned from the Popen call is the parent process, so I try doing something like sudo kill -- -$PID, where $PID is the one returned from Popen, but that just gives me kill: sending signal to -2100 failed: No such process why doesn't the process exist? Essentially, I just need a way to run a command with sudo using python's subprocess, then be able to kill it when I need to. I'm assuming I need to run some type of sudo kill command with the pid of the process I'm trying to kill or something like that but I'm unable to determine exactly how to do this.
type: Question
has title: Killing sudo-started subprocess in python
accepted answer: http://stackoverflow.com/a/50629906
tagged with: kill

http://stackoverflow.com/comment/88353232
comment on: http://stackoverflow.com/q/50669431
type: Comment
type: QuestionComment
score: 0
has text: It doesn’t seem like the model you’ve constructed ever gets compiled or evaluated. Isn’t x in the first line still a tensor? You’ll need to provide that tensor it’s expected inputs to fill the missing placeholders. Do you have some sample value of x (before the code block you shared) to nail down the missing placeholder values?

http://stackoverflow.com/a/50651265
has comment: http://stackoverflow.com/comment/88386026
has comment: http://stackoverflow.com/comment/88386454
has comment: http://stackoverflow.com/comment/88383962
score: 4
answers question: http://stackoverflow.com/q/50650850
has comment: http://stackoverflow.com/comment/88314506
has comment: http://stackoverflow.com/comment/88383393
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88314544
has body: As you found, since NaN is a float, adding NaN to a series may cause it to be either upcasted to float or converted to object. You are right in determining this is not a desirable outcome. There is no straightforward approach. My suggestion is to store your input row data in a dictionary and combine it with a dictionary of defaults before appending. Note that this works because pd.DataFrame.append accepts a dict argument. In Python 3.6, you can use the syntax {**d1, **d2} to combine two dictionaries with preference for the second. default = {'name': '', 'age': 0, 'weight': 0.0, 'has_children': False} row = {'name': 'Cindy', 'age': 42} df = df.append({**default, **row}, ignore_index=True) print(df) age has_children name weight 0 45 True Bob 143.2 1 40 True Sue 130.2 2 10 False Tom 34.9 3 42 False Cindy 0.0 print(df.dtypes) age int64 has_children bool name object weight float64 dtype: object
type: Answer
has comment: http://stackoverflow.com/comment/88386443
has comment: http://stackoverflow.com/comment/88383485
upvote count: 6
accepted answer of: http://stackoverflow.com/q/50650850
downvote count: 2

http://stackoverflow.com/q/50690414
downvote count: 1
tagged with: math
tagged with: pearson-correlation
has title: Calculate three vectors Pearson Correlation
type: Question
score: 0
answer count: 1
has body: I want to calculate the Pearson Correlation of three vectors. Like: np.corrcoef(X,Y,Z) Anyone knows how to do that in Python? Any library available? Big thanks!
favorite count: 0
has comment: http://stackoverflow.com/comment/88390671
tagged with: correlation
has answer: http://stackoverflow.com/a/50690850
type: UnansweredQuestion
upvote count: 1
tagged with: python

http://stackoverflow.com/a/50574094
has comment: http://stackoverflow.com/comment/88158934
downvote count: 0
type: Answer
upvote count: 3
has body: Zip the byte streams together, and use a Counter to get the consensus byte at each position. from functools import partial from collections import Counter from contextlib import ExitStack from mmap import mmap, PROT_READ fnames = ["t1.txt", "t2.txt"] with ExitStack() as stack: fhs = [stack.enter_context(open(f, 'rb')) for f in fnames] out = stack.enter_context(open("fixed", 'wb')) streams = [mmap(f.fileno(), 0, prot=PROT_READ) for f in fhs] for bs in zip(*streams): c = Counter(bs) out.write(c.most_common(1)[0][0])
answers question: http://stackoverflow.com/q/50574021
score: 3

http://stackoverflow.com/a/50672232
type: Answer
accepted answer of: http://stackoverflow.com/q/50595901
downvote count: 0
score: 1
has body: Each of the \newcommands has two required arguments, denoted using {}. As a result, we can access each newcommand's arguments, and access the value of each argument With your definition of slatex.tex above, we can obtain {'\\finDate': 'December 31, 2018', '\\startDate': 'January 1, 2018'} using the following script from pprint import pprint from TexSoup import TexSoup soup = TexSoup(open('slatex.tex')) newcommands = list(soup.find_all('newcommand')) result = {} for newcommand in newcommands: key, value = newcommand.args result[key.value] = value.value pprint(result) *On a side note, TexSoup doesn't yet understand that these redefined variables will have tangible impact on the rest of the document. It treats them as any other command, passively.
has comment: http://stackoverflow.com/comment/89120268
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50595901

http://stackoverflow.com/q/50684882
score: 1
accepted answer: http://stackoverflow.com/a/50684963
has title: python - split beautifulsoup object using reg expressions
upvote count: 1
has comment: http://stackoverflow.com/comment/88379592
type: Question
has body: I am having trouble finding a solution to split the time period and the route that are contained in a 'div' that i have scraped using beautifulsoup. Below is the text I get from the interactive shell. I need to split 'via I-405/I-65/I-525' and '8 min. 46 sec.' Then I need to get rid of 'min' and 'sec' so I can combine to get '8.46'. I am guessing I need to use split with regular expressions? Can someone give me an example of such? Thanks. Here is what I scraped off the webpage: via I-405/I-65/I-525 58 min. 8 sec. Here is what I get running from the shell: >>> soup.find_all('div')[16].get_text() 'via I-405/I-65/I-5258 min. 46 sec.' Here is what I am trying to do with the dictionaries: LinkNames[1] = TempLinkNames[7] LinkNames[2] = TempLinkNames[8] LinkNames[3] = TempLinkNames[9] LinkNames[4] = TempLinkNames[4] LinkNames[5] = TempLinkNames[2] LinkNames[6] = TempLinkNames[5] LinkNames[7] = TempLinkNames[3] LinkNames[8] = TempLinkNames[0] LinkNames[9] = TempLinkNames[1] print(LinkNames) Here is the first item of the dictionary: {'At BTI Road via Ocean Expy (I-525)': '32.48', Here is how I went around it putting the key and values into lists first then manually assigning it to a dictionary. BWPLinkNames = {BWPCombineNames[6]: BWPSingLinkTime[6], BWPCombineNames[7]: BWPSingLinkTime[7], BWPCombineNames[8]: BWPSingLinkTime[8], BWPCombineNames[9]: BWPSingLinkTime[9], BWPCombineNames[4]: BWPSingLinkTime[4], BWPCombineNames[2]: BWPSingLinkTime[2], BWPCombineNames[5]: BWPSingLinkTime[5], BWPCombineNames[3]: BWPSingLinkTime[3], BWPCombineNames[0]: BWPSingLinkTime[0], BWPCombineNames[1]: BWPSingLinkTime[1]} Having trouble outputting dictionary item to spreadsheet. The value are float strings '23.25'. But on the spreadsheet it is showing up incorrectly with error. It only shows up as one digit number, and the number has nothing to do with the actual float string. Using the xlsxwriter for excel and here is how I am outputting them. for key in BWLinkNames.keys(): worksheet.write(row…
has comment: http://stackoverflow.com/comment/88384701
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50684963
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/88384071
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/88335817
comment on: http://stackoverflow.com/q/50662711
has text: Why did you bring `scala` into the mix here?
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/88146780
has text: @Mehdibmp Try to had something to the url, a different path than '' or use '$'!!
comment on: http://stackoverflow.com/q/50568252
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88197861
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50594310
score: 1
has text: As written, `upload.py` has to be in the current working directory of the process that starts your `bash` script, which is not necessarily the directory which *contains* the `bash` script.

http://stackoverflow.com/q/50587318
has title: Speeding up loop over dataframes
linked to: http://stackoverflow.com/q/16476924
accepted answer: http://stackoverflow.com/a/50587640
type: Question
has body: I have written the code given below. There are two Pandas dataframes: df contains columns timestamp_milli and pressure and df2 contains columns timestamp_milli and acceleration_z. Both dataframes have around 100'000 rows. In the code shown below I'm searching for each timestamp of each row of df the rows of df2 where the time difference lies within a range and is minimal. Unfortunately the code is extremly slow. Moreover, I'm getting the following message originating from the line df_temp["timestamp_milli"] = df_temp["timestamp_milli"] - row["timestamp_milli"]: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead How can I speedup the code and solve the warning? acceleration = [] pressure = [] for index, row in df.iterrows(): mask = (df2["timestamp_milli"] &gt;= (row["timestamp_milli"] - 5)) &amp; (df2["timestamp_milli"] &lt;= (row["timestamp_milli"] + 5)) df_temp = df2[mask] # Select closest point if len(df_temp) &gt; 0: df_temp["timestamp_milli"] = df_temp["timestamp_milli"] - row["timestamp_milli"] df_temp["timestamp_milli"] = df_temp["timestamp_milli"].abs() df_temp = df_temp.loc[df_temp["timestamp_milli"] == df_temp["timestamp_milli"].min()] for index2, row2 in df_temp.iterrows(): pressure.append(row["pressure"]) acc = row2["acceleration_z"] acceleration.append(acc)
tagged with: performance
linked to: http://stackoverflow.com/q/24870953
has comment: http://stackoverflow.com/comment/88184375
tagged with: dataframe
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/88184391
answer count: 1
has answer: http://stackoverflow.com/a/50587640
has comment: http://stackoverflow.com/comment/88184011
tagged with: python
has comment: http://stackoverflow.com/comment/88185292
type: AnsweredQuestion

http://stackoverflow.com/q/50589989
has answer: http://stackoverflow.com/a/50590575
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88189447
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88190304
has title: URL Patterns and Views
type: Question
has body: I have an application which requests data based on certain parameters. I use two functions to handle the requests and then create two objects from the responses. I am able to iterate through each object individually and display the data of a particular object on my webpage, but when I try to use both functions simultaneously, only one function iterates through the object. It is my understanding that this issue has something to do with URL patterns, but I am not as to what the best approach would be. Below you will find my urlpatterns, my functions, and the HTML I use to access the view. urls.py urlpatterns = [ path('', views.customer, name='customer'), path('', views.information, name='information'), ] views.py def customer(request): for i, contact in enumerate(contactObj): try: contacts = contactObj context = {'contacts': contacts} except KeyError: print() return render(request, 'uccx/home.html', context) def information(request): for i, ticket in enumerate(ticketObj): try: tickets = ticketObj context = {'tickets': tickets} except KeyError: print() return render(request, 'uccx/home.html', context) home.html {% for ticket in tickets %} {{ ticket.id }} {{ ticket.company.name }} {{ ticket.summary }} {% endfor %}
accepted answer: http://stackoverflow.com/a/50590575
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/88190810
tagged with: rest
tagged with: http://stackoverflow.com/tag/html
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88189641
downvote count: 2

http://stackoverflow.com/q/50693834
has comment: http://stackoverflow.com/comment/88401101
upvote count: 3
downvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50699691
score: 2
type: Question
has body: Below is my code, *** Settings *** Documentation This test case is to verify the registration Library Selenium2Library Library ExcelLibrary *** Variables *** ${SERVER} URL ${BROWSER} Firefox ${DELAY} 10 ${DELAY1} 20 ${CreateAccountLink} //footer[@class='Panel__Footer-kGqwaT kqVeay']//div//a[@href='/signup'] ${UsernameTextBox} //input[@autocomplete='username'] ${Password} test123 ${PasswordTextBox} //input[@minlength='6'] ${SignUpButton} //button[@type='submit'] ${HeaderAccountNameBtn} //button[@class='Header__AccountButton-leDArq bDGoru'] *** Keywords ***`enter code here` Registration Click Link ${CreateAccountLink} Page Should Contain Button ${SignUpButton} Open Excel Current Directory robottestdata.xls ${userName} Read Cell Data By Name Sheet1 username Clear Element Text ${UsernameTextBox} Input Text ${UsernameTextBox} ${userName} Clear Element Text ${PasswordTextBox} Input Password ${PasswordTextBox} ${Password} Click Button ${SignUpButton} Set Selenium Implicit Wait ${DELAY} Page Should Contain Button ${HeaderAccountNameBtn} Capture Page Screenshot filename=-screenshot-registration.png While running the test i am getting the error, UnboundLocalError: local variable 'cellValue' referenced before assignment I found that the error is on 4th line but couldn't find the exact reason.
tagged with: testing
tagged with: robotframework
has comment: http://stackoverflow.com/comment/88397928
has title: Robot Framework : UnboundLocalError: local variable 'cellValue' referenced before assignment
answer count: 1

http://stackoverflow.com/comment/88304590
has text: @AlexPetukhov Glad to help! Please see my recent edit.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50646951

http://stackoverflow.com/comment/88383443
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50684318
has text: Yes, I contacted the CA and they said I am not able to make client certificates with the proper fields. Thus, the CA did not respect my extension fields. Unfortunately, that means that we might not be able to use this CA to make client certs.

http://stackoverflow.com/comment/88120947
has text: I just got it. You're using the fact that `argsort` has an axis argument to compensate for `shuffle`'s lack. Clever
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50554612

http://stackoverflow.com/q/50626979
type: UnansweredQuestion
score: 11
has body: I have a pandas dataframe in which I want to divide each column by the same data series values for each row. Each column and the data series have the same length. The data series has only float numbers but some cells in the dataframe have NaNs. I tried various things but somehow I cannot get it solved. df = df.divide(data_series, axis=1) Any suggestions? many thanks!
has answer: http://stackoverflow.com/a/50627114
has answer: http://stackoverflow.com/a/50627225
upvote count: 11
type: Question
tagged with: pandas
tagged with: divide
favorite count: 0
answer count: 3
has answer: http://stackoverflow.com/a/50627271
tagged with: python
has comment: http://stackoverflow.com/comment/88264122
has comment: http://stackoverflow.com/comment/88264076
has title: How to divide each column of pandas Dataframe by a Series?
downvote count: 0

http://stackoverflow.com/comment/88182849
type: QuestionComment
type: Comment
score: 8
comment on: http://stackoverflow.com/q/50586754
has text: That is one of the more complex applications of decorators. You should start with understanding how a decorator without arguments and without `functools.wraps` works.

http://stackoverflow.com/comment/88366516
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50678250
type: Comment
has text: Thanks for your answer, but it's not quite yet what I was hoping for. In my first example, where the number of arguments were known, the resulting function g had no varargs or keyword arguments. In your first example however you have varargs and in your second example you have kwargs.

http://stackoverflow.com/comment/88351112
type: Comment
has text: Hmm— that seems very weird. Looks like the indices are getting mangled somehow. I can't reproduce it; I get the stated output. Maybe print debug the various components in a fresh notebook?
comment on: http://stackoverflow.com/a/50665264
type: AnswerComment
score: 0

http://stackoverflow.com/a/50672659
has comment: http://stackoverflow.com/comment/88355138
type: Answer
has body: For a local image, Content-Type should be application/octet-stream or multipart/form-data AND JSON should be empty headers = { 'Content-type': 'application/octet-stream', } body = "" #load image filename = 'C:/testPicutre.JPG' f = open(filename, "rb") body = f.read() f.close() conn = httplib.HTTPSConnection('api.projectoxford.ai') conn.request("POST", "/face/v0/detections?%s" % params, body, headers) response = conn.getresponse("") data = response.read() print(data) conn.close()
score: 0
has comment: http://stackoverflow.com/comment/88355191
has comment: http://stackoverflow.com/comment/88355969
answers question: http://stackoverflow.com/q/50672566

http://stackoverflow.com/q/50583871
has answer: http://stackoverflow.com/a/72938945
linked to: http://stackoverflow.com/q/4057513
score: 5
tagged with: python
has comment: http://stackoverflow.com/comment/88178781
type: AnsweredQuestion
has body: I am looking for an efficient implementation of a string similarity metric function in Python (or a lib that provides Python bindings). I want to compare strings with an average of 10kb in size and I can't take any shortcuts like comparing line-by-line, I need to compare the entire thing. I don't really care, what exact metric will be used, as long as the results are reasonable and computation is fast. Here's what I've tried so far: difflib.SequenceMatcher from the standard lib. ratio() gives good results, but takes >100ms for 10kb text. quick_ratio() takes only half the time, but the results are sometimes far of the real value. python-Levenshtein: levenshtein is an acceptable metric for my use case, but Levenshtein.ratio('foo', 'bar') is not faster than the SequenceMatcher. Before I start benchmarking every lib on pypi that provides functions for measuring string similarity, maybe you can point me in the right direction? I'd love to reduce the time for a single comparison to less than 10ms (on commodity hardware), if possible.
type: Question
upvote count: 5
possible better answer: http://stackoverflow.com/a/72112451
has comment: http://stackoverflow.com/comment/88178660
has answer: http://stackoverflow.com/a/72112451
has comment: http://stackoverflow.com/comment/88179110
has title: Most efficient string similarity metric function
has answer: http://stackoverflow.com/a/50585521
has comment: http://stackoverflow.com/comment/88177461
answer count: 3
downvote count: 0
tagged with: string
tagged with: levenshtein-distance
accepted answer: http://stackoverflow.com/a/50585521
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/50644777
has title: Understanding Spacy's Scorer Output
tagged with: python
accepted answer: http://stackoverflow.com/a/50645181
has body: I'm evaluating a custom NER model that I built using Spacy. I'm evaluating the training sets using Spacy's Scorer class. def Eval(examples): # test the saved model print("Loading from", './model6/') ner_model = spacy.load('./model6/') scorer = Scorer() try: for input_, annot in examples: doc_gold_text = ner_model.make_doc(input_) gold = GoldParse(doc_gold_text, entities=annot['entities']) pred_value = ner_model(input_) scorer.score(pred_value, gold) except Exception as e: print(e) print(scorer.scores) It works fine but I don't understand the output. Here's what I get for each training set. {'uas': 0.0, 'las': 0.0, 'ents_p': 90.14084507042254, 'ents_r': 92.7536231884058, 'ents_f': 91.42857142857143, 'tags_acc': 0.0, 'token_acc': 100.0} {'uas': 0.0, 'las': 0.0, 'ents_p': 91.12227805695142, 'ents_r': 93.47079037800687, 'ents_f': 92.28159457167091, 'tags_acc': 0.0, 'token_acc': 100.0} {'uas': 0.0, 'las': 0.0, 'ents_p': 92.45614035087719, 'ents_r': 92.9453262786596, 'ents_f': 92.70008795074759, 'tags_acc': 0.0, 'token_acc': 100.0} {'uas': 0.0, 'las': 0.0, 'ents_p': 94.5993031358885, 'ents_r': 94.93006993006993, 'ents_f': 94.76439790575917, 'tags_acc': 0.0, 'token_acc': 100.0} {'uas': 0.0, 'las': 0.0, 'ents_p': 92.07920792079209, 'ents_r': 93.15525876460768, 'ents_f': 92.61410788381743, 'tags_acc': 0.0, 'token_acc': 100.0} Does anyone know what the keys are? I've looked over Spacy's documentation and could not find anything. Thanks!
score: 18
type: AnsweredQuestion
tagged with: spacy
tagged with: named-entity-recognition
type: Question
upvote count: 18
has answer: http://stackoverflow.com/a/50645181
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/88419402
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50692352
has text: The `w:lsdException` element is part of a latent style definition (not an _actual_ style definition). The documentation I linked to can help you understand that distinction. A table style can only be added using Word, not `python-pptx` (yet anyway). The documentation I linked to also explains that.

http://stackoverflow.com/a/50557839
answers question: http://stackoverflow.com/q/50556965
score: 0
type: Answer
has body: I ended up encoding and decoding the string before putting it into the dict value. .encode('ascii', 'ignore').decode()

http://stackoverflow.com/a/50552118
has body: Use re.match(pattern, value): import re [...] if re.match(r"(\d\d?|100) permit", input): do_something() And the variable input will override the built-in function input(), so change the name to something else. EDIT: As you don't want to use RegExp, you can split the string, pass it to int and then see if it's in the range. if 1 &lt;= int(input.split(" ")[0]) &lt;= 100: do_something()
has comment: http://stackoverflow.com/comment/88116375
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50552003
has comment: http://stackoverflow.com/comment/88183462

http://stackoverflow.com/q/50580427
has title: Importing numbers as string into a dataframe from text
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88169994
score: -1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50581770
has comment: http://stackoverflow.com/comment/88170377
has body: I'm trying to import a text file into Python as a dataframe. My text file essentially consists of 2 columns, both of which are numbers. The problem is: I want one of the columns to be imported as a string (since many of the 'numbers' start with a zero, e.g. 0123, and I will need this column to merge the df with another later on) My code looks like this: mydata = pd.read_csv("text_file.txt", sep = "\t", dtype = {"header_col2": str}) However, I still lose the zeros in the output, so a 4-digit number is turned into a 3-digit number. I'm assuming there is something wrong with my import code but I could not find any solution yet. I'm new to python/pandas, so any help/suggestions would be much appreciated!
has comment: http://stackoverflow.com/comment/88170165
downvote count: 1
tagged with: import
type: Question
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/50581770
tagged with: pandas
upvote count: 0
answer count: 1
tagged with: string
linked to: http://stackoverflow.com/q/13250046

http://stackoverflow.com/comment/88264603
comment on: http://stackoverflow.com/q/50627185
has text: Welcome to Stack Overflow! Welcome to Stackoverflow.com! Please make your question a Minimal, Complete, and Verifiable example [MVCE](https://stackoverflow.com/help/mcve) Also check [how to ask question](https://stackoverflow.com/help/how-to-ask) to make your post answerable.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50612231
has body: for (first, last, age) in myList: print("%10s %10s %d" % (first, last, age)) myList is a list of lists. First we iterate over it using sequence unpacking to unpack the 3 elements. We then format the elements and print them - I use printf-style formatting here, but the newer str.format formatting is also available. (Some background on the difference between the two)
upvote count: 1
answers question: http://stackoverflow.com/q/50612208
has comment: http://stackoverflow.com/comment/88234592
downvote count: 0
has comment: http://stackoverflow.com/comment/88234401
type: Answer
has comment: http://stackoverflow.com/comment/88234428
score: 1

http://stackoverflow.com/q/50592678
linked to: http://stackoverflow.com/q/423379
tagged with: global-variables
has body: I'm trying to run an optimization step and I want to update a global variable from within a function. I'm using an optimization script and I want to save the data when there are any updates but I cannot update the global variable from within a function. Is there a way to update a global variable from within a function call? I am making sure not to run the optimization step in parallel so this technically should be ok. global current_minimum current_minimum = 0 def update(): current_minimum = -0.1 _ = update() print(current_minimum) # 0
type: Question
tagged with: function
has answer: http://stackoverflow.com/a/50592712
upvote count: 3
answer count: 1
downvote count: 1
has title: How to update a global variable from within a function in Python 3?
favorite count: 0
duplicate of: http://stackoverflow.com/q/423379
type: UnansweredQuestion
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/88194790

http://stackoverflow.com/q/50575700
tagged with: python
has title: Range function in python
type: Question
has answer: http://stackoverflow.com/a/50575719
has body: for n in range(2,5): for x in range(2,n): print(n,x) Gives output as: 3 2 4 2 4 3 why the value of n start from 3 not 2?
score: 0
has comment: http://stackoverflow.com/comment/88160534
answer count: 1
type: UnansweredQuestion
tagged with: range

http://stackoverflow.com/q/50602088
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has title: python executable error (mac os)
tagged with: python
answer count: 0
score: 1
upvote count: 1
type: Question
downvote count: 0
tagged with: macos
has body: I distributed a python executable compressed by cx_freeze my users are getting this error while running the python exec dyld: Library not loaded: /Library/Frameworks/Python.framework/Versions/3.6/Python works fine for me when I run "which python3" in terminal I get /Library/Frameworks/Python.framework/Versions/3.6/bin/python3 is there a way i can add something to thr script repack it as executable and distribute it

http://stackoverflow.com/comment/88121247
type: QuestionComment
score: 1
has text: Please, show the traceback.
comment on: http://stackoverflow.com/q/50555220
type: Comment

http://stackoverflow.com/a/50693805
has comment: http://stackoverflow.com/comment/88398368
has body: For a quick solution, you can try the following code. But I would suggest you to look into python's re module. Its pretty handy. import re result = [] pattern = re.compile('[,.?]') with open('input.txt') as f: for line in f.readlines(): r = re.split(pattern, line.strip()) if r: result.append(r) print result
type: Answer
has comment: http://stackoverflow.com/comment/88398256
has comment: http://stackoverflow.com/comment/88398208
has comment: http://stackoverflow.com/comment/88398216
has comment: http://stackoverflow.com/comment/88398226
has comment: http://stackoverflow.com/comment/88409624
answers question: http://stackoverflow.com/q/50693480
score: 0

http://stackoverflow.com/a/50675128
has comment: http://stackoverflow.com/comment/88360104
has comment: http://stackoverflow.com/comment/88360626
answers question: http://stackoverflow.com/q/50674757
type: Answer
has body: Regex are rarely the most efficient tools if you are testing a simple pattern. Just using startswith makes it twice as fast. from timeit import timeit import re size = 10000 data = ['foo','bar','backup_20180406'] * size def find_dates(data): prefix = 'backup_' prefix_size = len(prefix) return [name[prefix_size:] for name in data if name.startswith(prefix)] def find_dates_testing_numbers(data): prefix = 'backup_' prefix_size = len(prefix) for name in data: if name.startswith(prefix): try: yield int(name[prefix_size:]) except ValueError: pass def find_dates_regex(data): regex = re.compile(r"backup_(?P&lt;date&gt;\d+)") return [x.group('date') for x in (regex.match(y) for y in data) if x] def find_dates_pd(data): import pandas as pd regex = r"backup_(?P&lt;date&gt;\d+)" return pd.Series(data).str.extract(regex).dropna() result = find_dates(data) print(timeit('find_dates(data)', globals=globals(), number=1000)) # 4.02514289499959 seconds print(timeit('list(find_dates_testing_numbers(data))', globals=globals(), number=1000)) # 6.0529899510002 seconds print(timeit('find_dates_regex(data)', globals=globals(), number=1000)) # 8.772153561999403 seconds print(timeit('find_dates_pd(data)', globals=globals(), number=1000)) # 19.018224569999802
upvote count: 0
has comment: http://stackoverflow.com/comment/88360689
downvote count: 1
score: -1
has comment: http://stackoverflow.com/comment/88360602

http://stackoverflow.com/q/50681795
downvote count: 0
answer count: 1
score: 1
tagged with: string
favorite count: 0
accepted answer: http://stackoverflow.com/a/50681988
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/88373197
type: AnsweredQuestion
tagged with: python-3.x
has title: Removing multiple characters (forming a word) from a string
upvote count: 1
has comment: http://stackoverflow.com/comment/88373430
type: Question
has answer: http://stackoverflow.com/a/50681988
has comment: http://stackoverflow.com/comment/88373445
has body: I have a challenge which I have tried to solve using split.strings but that seems to not be designed for immutable strings the way I need but mainly for whitespace and single character removal. I have also tried regex but as they are not due in my current python course for a few weeks I am a bit stuck on how they work (although I know the basics of what they are for). So, I have a JSON file that presents machine and people data from a factory and I need to parse the machine data separate from the people data that is gathered within the facility. Converting the JSON file and selecting the required data is working but within one of the parameters called name is a mix of people and machine info I need to separate out. An example of two branches is below: "id": "b4994c877c9c", "name": "forklift_0001", # here is the machine "areaId": "Tracking001", "areaName": "Ajoneuvo", "color": "#FF0000", "coordinateSystemId": "CoordSys001", "coordinateSystemName": null, "covarianceMatrix": [ "id": "b4994c879275", "name": "guest_0001", # here is a person "areaId": "Tracking001_2D", "areaName": "staff1", "color": "#CCFF66", "coordinateSystemId": "CoordSys001", "coordinateSystemName": null, "covarianceMatrix": [ The code I have to convert is below: for f in file_list: print('Input file: ' + f) # Replace with desired operations with open(f, 'r') as f: distros = json.load(f) output_file = 'Output' + str(output_nr) + '.csv' with open(output_file, 'w') as text_file: for distro in distros: print(distro['name'] + ',' + str(distro['positionTS']) + ',' + str(distro['position']), file=text_file) So what I need to do within the distro['name'] array (is it an array??) is to go through the 500k lines and ask it to remove anything that isn't forklift, crane, machine, etc, leaving only them (and later the opposite) and this I cannot figure out. All help sincerely appreciated.

http://stackoverflow.com/comment/88361617
has text: You have backslash `/` at the end of your `path`. Have you tried `127.0.0.1:8000/api/` ?
comment on: http://stackoverflow.com/q/50676008
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88147156
has text: The XML file I'm parsing is about 900MB. I put more thought into this, and realized my script was hugely inefficient. It's pretty quick to parse through the entire file one time. How I had written it originally was that I was looping through the entire file 1000+ times to match against another list. So now I'm parsing one time, and storing what I need in a CSV file for reference later. In the past I've tried this and have parsed through the file and stored the elements I need in a list (instead of writing to CSV). But that really slows down as it runs and takes forever. Always learning!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50557311

http://stackoverflow.com/comment/88229729
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50609790
type: Comment
has text: What's your OS?

http://stackoverflow.com/comment/88194373
type: AnswerComment
type: Comment
has text: Checking for equality may lead to unwanted results when the dtype is float. `np.isclose` might be a better option here.
comment on: http://stackoverflow.com/a/50592420
score: 0

http://stackoverflow.com/a/50575368
answers question: http://stackoverflow.com/q/50575247
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50575247
has body: Once you set both data frames to have same index: df1 = df1.set_index("id") df2 = df2.set_index("id") You can do one very simple operation: mask = df1.index.isin(df2.index) df2["value"] += df1.loc[mask, "value"] Output: value x y z id 1 202 3 4 6 3 404 3 4 6 5 606 3 4 6 5 626 3 4 6 You can always do df2.reset_index() to get back to original setting.
type: Answer
score: 2
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/tag/c
tags question: http://stackoverflow.com/q/50576770
tags question: http://stackoverflow.com/q/50673522
tags question: http://stackoverflow.com/q/50560003
tag name: c
type: Tag
tags question: http://stackoverflow.com/q/50575239
tags question: http://stackoverflow.com/q/50603694
tags question: http://stackoverflow.com/q/50677394
tags question: http://stackoverflow.com/q/50562828
tags question: http://stackoverflow.com/q/50619062
tags question: http://stackoverflow.com/q/50570967
tags question: http://stackoverflow.com/q/50687489
tags question: http://stackoverflow.com/q/50542882
tags question: http://stackoverflow.com/q/50669205

http://stackoverflow.com/q/50594562
has comment: http://stackoverflow.com/comment/88198318
has comment: http://stackoverflow.com/comment/88198267
has comment: http://stackoverflow.com/comment/88198606
has comment: http://stackoverflow.com/comment/88198364
answer count: 3
has comment: http://stackoverflow.com/comment/88198329
has answer: http://stackoverflow.com/a/50594655
has comment: http://stackoverflow.com/comment/88198590
accepted answer: http://stackoverflow.com/a/50594789
has comment: http://stackoverflow.com/comment/88198378
favorite count: 0
has answer: http://stackoverflow.com/a/50594623
has body: cleanedList = [x for x in range(0, 100, 1)] idx = 0 for val in cleanedList: check = abs(cleanedList[idx]) idx = idx + 1 if check % 5 == 0: ##### Conditions changed and change the list cleanedList = a new list that loops over. This is arbitrary example. I want to change the list it is looping now when the conditions fails. I tried this way. I don't think it actually changed the list it is looping now. Please correct me.
downvote count: 2
tagged with: python
possible better answer: http://stackoverflow.com/a/50594623
has comment: http://stackoverflow.com/comment/88198280
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88198503
has title: for loop in Python, change the list it was looping
has comment: http://stackoverflow.com/comment/88198331
type: Question
has answer: http://stackoverflow.com/a/50594789
tagged with: for-loop
has comment: http://stackoverflow.com/comment/88204472
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/88198361

http://stackoverflow.com/comment/88253227
type: QuestionComment
has text: @VivekKumar yes! that's exactly what I need, thanks! If you wish, please post it as an answer so I can mark it as the valid one. Thanks again!
score: 0
comment on: http://stackoverflow.com/q/50621387
type: Comment

http://stackoverflow.com/q/50680923
tagged with: python
answer count: 0
upvote count: 3
type: UnansweredQuestion
tagged with: multithreading
has comment: http://stackoverflow.com/comment/88372567
tagged with: multiprocessing
score: 3
has comment: http://stackoverflow.com/comment/88393116
type: Question
downvote count: 0
has title: why the process not run in python
favorite count: 0
has body: i have a bot(query, key) function to post data, dicts(query, answer) to wrap the return result, and query_pipe(query_list) to process list of query request. But when i put that in multiprocessing.Process, i found that bot(query, key) return nothing. Here's my code. def bot(query, key): data = { 'key' : key, 'info' : query, 'userid' : 'wechat-robot', } try: apiUrl = url page = requests.post(apiUrl, data=data) if page.json()['code'] == '100000': answer = page.json()['text'] return dicts(query, answer) else: return dicts(query, 'failed') except Exception as e: return '500 Error' def dicts(query, answer): return {'query': query, 'answer': answer} def query_pipe(query_list): keys_pool = [] with open('keys.txt', 'r') as f: lines = f.readlines() for line in lines: keys_pool.append(line.strip('\n')) idx = 0 print(bot(query_list[0], keys_pool[0])) p = Process(target=query_pipe, args=(query_data,)) p.start() p.join() But when i run the query_pipe(query_list) which not using multiprocess.Process, query_pipe(query_list) would print the correct output. I feel so confused, so anyone could give me a hint would be highly appreciated.

http://stackoverflow.com/comment/88110807
comment on: http://stackoverflow.com/a/50549713
has text: I installed it on conda and no longer have that error. thank you
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88333695
has text: I know it's annoying, but PyLint is a code *analyzer*. If the interpreter accepts the code, then PyLint is *wrong.* The only thing you can do in that case is to tell PyLint to shut up.
score: 2
comment on: http://stackoverflow.com/q/50661107
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50560270
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50556059
has body: Yes, you can skip the price as well. I am providing you an alternative approach where you can create a List of the available prices and the respective images as follows : Code Block: from selenium import webdriver options = webdriver.ChromeOptions() options.add_argument("start-maximized") options.add_argument('disable-infobars') browser=webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe') browser.get("https://www.amazon.com/gp/goldbox/ref=gbps_ftr_s-4_bedf_page_10?gb_f_deals1=enforcedCategories:2972638011,dealStates:AVAILABLE%252CWAITLIST%252CWAITLISTFULL,includedAccessTypes:,page:10,sortOrder:BY_SCORE,dealsPerPage:32&amp;pf_rd_p=afc45143-5c9c-4b30-8d5c-d838e760bedf&amp;pf_rd_s=slot-4&amp;pf_rd_t=701&amp;pf_rd_i=gb_main&amp;pf_rd_m=ATVPDKIKX0DER&amp;pf_rd_r=ZDV4YBQJFDVR3PAY4ZBS&amp;ie=UTF8") #finds images deal_image = browser.find_elements_by_xpath("//div[@class='a-row priceBlock unitLineHeight']/span//preceding::img[1]") images = [] for image in deal_image: images.append(image.get_attribute('src')) #finds prices deal_price = browser.find_elements_by_xpath("//div[@class='a-row priceBlock unitLineHeight']/span") prices = [] for price in deal_price: prices.append(price.text) #print the information for image, price in zip(images, prices): print(image, price) Console Output: https://images-na.ssl-images-amazon.com/images/I/31zt-ovKJqL._AA210_.jpg $9.25 https://images-na.ssl-images-amazon.com/images/I/610%2BKAfr72L._AA210_.jpg $15.89 https://images-na.ssl-images-amazon.com/images/I/41whkQ1m0uL._AA210_.jpg $31.49 https://images-na.ssl-images-amazon.com/images/I/41cAbUWEdoL._AA210_.jpg $259.58 - $782.99 https://images-na.ssl-images-amazon.com/images/I/51raHLFC8wL._AA210_.jpg $139.56 https://images-na.ssl-images-amazon.com/images/I/41fuZZwdruL._AA210_.jpg $41.24 https://images-na.ssl-images-amazon.com/images/I/51N2rdMSh0L._AA210_.jpg $19.50 - $20.99 https://images-na.ssl-images-amazon.com/images/I/515DbJhCtOL._AA210_.jpg $2…

http://stackoverflow.com/comment/88325999
has text: Did you do a search with that that error and try to relate the results to your circumstances? You really haven't provided enough information. Please take the time to read [mcve] and [ask].
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50657943
type: Comment

http://stackoverflow.com/comment/88360626
type: Comment
comment on: http://stackoverflow.com/a/50675128
score: 0
type: AnswerComment
has text: 100% agree with your comment about avoiding regex if possible. But this is not an answer to the original question

http://stackoverflow.com/q/50641866
tagged with: tensorflow
type: Question
linked to: http://stackoverflow.com/q/46264133
has comment: http://stackoverflow.com/comment/88294134
has answer: http://stackoverflow.com/a/52658859
has title: Binary classifier always returns 0.5
score: 4
upvote count: 4
has body: I am training a classifier that takes a RGB input (so three 0 to 255 values) and returns whether black or white (0 or 1) font would fit best with that colour. After training, my classifier always returns 0.5 (or there about) and never gets any more accurate than that. The code is below: import tensorflow as tf import numpy as np from tqdm import tqdm print('Creating Datasets:') x_train = [] y_train = [] for i in tqdm(range(10000)): x_train.append([np.random.uniform(0, 255), np.random.uniform(0, 255), np.random.uniform(0, 255)]) for elem in tqdm(x_train): if (((elem[0] + elem[1] + elem[2]) / 3) / 255) &gt; 0.5: y_train.append(0) else: y_train.append(1) x_train = np.array(x_train) y_train = np.array(y_train) graph = tf.Graph() with graph.as_default(): x = tf.placeholder(tf.float32) y = tf.placeholder(tf.float32) w_1 = tf.Variable(tf.random_normal([3, 10], stddev=1.0), tf.float32) b_1 = tf.Variable(tf.random_normal([10]), tf.float32) l_1 = tf.sigmoid(tf.matmul(x, w_1) + b_1) w_2 = tf.Variable(tf.random_normal([10, 10], stddev=1.0), tf.float32) b_2 = tf.Variable(tf.random_normal([10]), tf.float32) l_2 = tf.sigmoid(tf.matmul(l_1, w_2) + b_2) w_3 = tf.Variable(tf.random_normal([10, 5], stddev=1.0), tf.float32) b_3 = tf.Variable(tf.random_normal([5]), tf.float32) l_3 = tf.sigmoid(tf.matmul(l_2, w_3) + b_3) w_4 = tf.Variable(tf.random_normal([5, 1], stddev=1.0), tf.float32) b_4 = tf.Variable(tf.random_normal([1]), tf.float32) y_ = tf.sigmoid(tf.matmul(l_3, w_4) + b_4) loss = tf.reduce_mean(tf.squared_difference(y, y_)) optimizer = tf.train.AdadeltaOptimizer().minimize(loss) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print('Training:') for step in tqdm(range(5000)): index = np.random.randint(0, len(x_train) - 129) feed_dict = {x : x_train[index:index+128], y : y_train[index:index+128]} sess.run(optimizer, feed_dict=feed_dict) if step % 1000 == 0: print(sess.run([loss], feed_dict=feed_dict)) while True: inp1 = int(input('')) inp2 = int(input('')) i…
answer count: 2
possible better answer: http://stackoverflow.com/a/50643848
has comment: http://stackoverflow.com/comment/88294014
accepted answer: http://stackoverflow.com/a/52658859
has answer: http://stackoverflow.com/a/50643848
downvote count: 0
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88295357
type: AnsweredQuestion
tagged with: machine-learning

http://stackoverflow.com/comment/88221342
type: AnswerComment
comment on: http://stackoverflow.com/a/50605761
type: Comment
has text: As i said previously on another comment, i don't have any file reader, i only have a csv reader so i can't use the .seek() attribute.
score: 0

http://stackoverflow.com/a/50697221
type: Answer
answers question: http://stackoverflow.com/q/50692358
upvote count: 12
has body: No, there is no other alternative than updating the ChromeDriver binary versions, while the Chrome Browser keeps on getting updated automatically. Reason Each Chrome Browser is released after certain feature additions, modifications and removals from the existing features. To comply with the current set of Browser Features, Chrome Team releases the compatible ChromeDriver binary time to time. These ChromeDriver binaries are capable to interact with the Chrome Browser. Certain version of a ChromeDriver binary supports a specific range of Chrome Browser versions (some of the recent) as below: ChromeDriver v84.0.4147.30 (2020-05-28) Supports Chrome version 84 ChromeDriver v83.0.4103.39 (2020-05-05) Supports Chrome version 83 ChromeDriver v82 was intensionally skipped. ChromeDriver v81.0.4044.138 (2020-05-05) Supports Chrome version 81 ChromeDriver v80.0.3987.106 (2020-02-13) Supports Chrome version 80 ChromeDriver v79.0.3945.36 (2019-11-18) Supports Chrome version 79 ChromeDriver v78.0.3904.70 (2019-10-21) Supports Chrome version 78 ChromeDriver v77.0.3865.40 (2019-08-20) Supports Chrome version 77 ChromeDriver v76.0.3809.126 (2019-08-20) Supports Chrome version 76 ChromeDriver v75.0.3770.8 (2019-04-29) Supports Chrome version 75 ChromeDriver v74.0.3729.6 (2019-03-14) Supports Chrome version 74 ChromeDriver v73.0.3683.68 (2019-03-06) Supports Chrome version 73 ChromeDriver v2.46 (2019-02-01) Supports Chrome v71-73 ChromeDriver v2.45 (2018-12-10) Supports Chrome v70-72 ChromeDriver v2.44 (2018-11-19) Supports Chrome v69-71 ChromeDriver v2.43 (2018-10-16) Supports Chrome v69-71 ChromeDriver v2.42 (2018-09-13) Supports Chrome v68-70 ChromeDriver v2.41 (2018-07-27) Supports Chrome v67-69 ChromeDriver v2.40 (2018-06-07) Supports Chrome v66-68 ChromeDriver v2.39 (2018-05-30) Supports Chrome v66-68 ChromeDriver v2.38 (2018-04-17) Supports Chrome v65-67 ChromeDriver v2.37 (2018-03-16) Supports Chrome v64-66 ChromeDriver v2.36 (2018-03-02) Supports Chrome v63-65 ChromeDriver v2…
type: AcceptedAnswer
score: 10
accepted answer of: http://stackoverflow.com/q/50692358
has comment: http://stackoverflow.com/comment/127867225
downvote count: 2

http://stackoverflow.com/comment/88105284
score: 0
type: QuestionComment
has text: Ugh, you guys were very correct about the working directory being a function of a relative path. Not my finest hour here. The filename was built from os.getcwd() when it should have been built from os.path.dirname(os.path.realpath(\_\_file\_\_)). Thank you for your help.
type: Comment
comment on: http://stackoverflow.com/q/50546852

http://stackoverflow.com/a/50627443
score: 0
has body: The way I see it is to convert a type sensitive case of an fraction before operation, so if some language has peculiar "wording" for specific sets of decimal, you can have a test case that is part of an number of infinite set. Since every living language that I know uses decimal system, we have a nice rule about it, the 100, 1000 and etc are most stable digits for pronounciation , since they are always plural in form. So singular forms are often based up to base 10 (we have that much fingers ) by language barrier, for example in my native language after number 5 all numbers become plural because 5 is one whole hand and every number afterwards needs second hand to count it on. This plural/singular form in then transcribed into linguistics, since 4321 would be written as 4320 and 1 form. I am guessing that most of other languages have some similar elements to their linguistics. So you generally need to check first 2 digits, the 1 place and 10 place to verify your translator. So in the number of n by converting it to int and testing it by n//10+n//1 in that specific translator and then doing simple comparison of strings you could be able to generate pretty good verification for most of the languages. Then it is just inputting the exceptions for different language groups. But I must say this is up most based on logic , I am not a linguist or anything. I hope this helped.
type: Answer
answers question: http://stackoverflow.com/q/50626360

http://stackoverflow.com/comment/88306912
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50648096
has text: Yes , my ValueError is raised. got it to work after I used Patrick's solution

pyspark
tags question: http://stackoverflow.com/q/50624745
tags question: http://stackoverflow.com/q/50692226
tags question: http://stackoverflow.com/q/50606132
tags question: http://stackoverflow.com/q/50612296
tags question: http://stackoverflow.com/q/50572592
tags question: http://stackoverflow.com/q/50584678
tags question: http://stackoverflow.com/q/50668577
tags question: http://stackoverflow.com/q/50608723
tags question: http://stackoverflow.com/q/50629600
tags question: http://stackoverflow.com/q/50633627
tags question: http://stackoverflow.com/q/50593337
tags question: http://stackoverflow.com/q/50613977
tags question: http://stackoverflow.com/q/50606059
tags question: http://stackoverflow.com/q/50613173
tags question: http://stackoverflow.com/q/50686007
tags question: http://stackoverflow.com/q/50637728
type: Tag
tags question: http://stackoverflow.com/q/50692099
tags question: http://stackoverflow.com/q/50576243
tags question: http://stackoverflow.com/q/50632708
tags question: http://stackoverflow.com/q/50601338
tags question: http://stackoverflow.com/q/50553500
tags question: http://stackoverflow.com/q/50686616
tags question: http://stackoverflow.com/q/50689331
tags question: http://stackoverflow.com/q/50548575
tags question: http://stackoverflow.com/q/50573209
tags question: http://stackoverflow.com/q/50625384
tags question: http://stackoverflow.com/q/50676241
tags question: http://stackoverflow.com/q/50596608
tags question: http://stackoverflow.com/q/50603891
tags question: http://stackoverflow.com/q/50658159
tags question: http://stackoverflow.com/q/50689005
tags question: http://stackoverflow.com/q/50696680
tags question: http://stackoverflow.com/q/50619532
tags question: http://stackoverflow.com/q/50663129
tags question: http://stackoverflow.com/q/50564167
tags question: http://stackoverflow.com/q/50580534
tags question: http://stackoverflow.com/q/50568396
tags question: http://stackoverflow.com/q/50648154
tags question: http://stackoverflow.com/q/50683894
tags question: http://stackoverflow.com/q/50565800
tags question: http://stackoverflow.com/q/50558417
tags question: http://stackoverflow.com/q/50636311
tags question: http://stackoverflow.com/q/50653862
tag name: pyspark
tags question: http://stackoverflow.com/q/50677793
tags question: http://stackoverflow.com/q/50639233

http://stackoverflow.com/q/50641631
favorite count: 0
has answer: http://stackoverflow.com/a/50642872
upvote count: 2
has body: When trying to train my tensorflow graph im getting the error message: ValueError: setting an array element with a sequence happening in this line of code, in the feed_dict function: # run the session and train the model _, c = sess.run([optimizer, cost], feed_dict = {input_x: x_train_v, output_y: y_train}) It seems to be a problem with my output variable (y_train). It is a List of size(25) inside a pandas dataframe. Already checked if every list has the same length with print(y_train.shape) #(23904,) print(y_train.apply(type)[0]) #&lt;class 'list'&gt; n = len(y_train[0]) if all(len(x) == n for x in y_train): print("true") #true The variable is created with following code: dataframe['category_number'] = "" for _ in range(len(dataframe)): string = dataframe.at[_, 'Product Categorization Tier 1'].strip() number = category_list.index(string) # saving as category vector vector = [0] * 25 vector[number] = 1 dataframe.at[_,'category_number'] = vector y_train = train_df["category_number"] Edit: Cost Function and Optimizer prediction = neural_network_model(input_x ) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=output_y)) optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) Full Error Message:
tagged with: python
has comment: http://stackoverflow.com/comment/88294446
has comment: http://stackoverflow.com/comment/88295371
accepted answer: http://stackoverflow.com/a/50642872
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88295569
has title: Tensorflow, ValueError: setting an array element with a sequence
has comment: http://stackoverflow.com/comment/88294785
tagged with: tensorflow
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/88294741
has comment: http://stackoverflow.com/comment/88295261
tagged with: pandas
downvote count: 0

http://stackoverflow.com/q/50658806
type: Question
has body: I'm a real python newbie and can't seem to get this animation to look how I want. I've made a similar plot without animation, and that appears nicely in the Jupyter notebook, with little whitespace. However, when I add animation to the plot, it looks really ugly! Here is my code: %%capture %matplotlib inline import matplotlib.animation as animation plt.rcParams["animation.html"] = "jshtml" fig = plt.figure(figsize=(11, 9)) # Set map area and set to display coastlines, country borders etc. ax = plt.axes([0, 0, 0.99, 0.99], projection=ccrs.PlateCarree()) ax.set_extent([-130, -10, 0, 40], ccrs.Geodetic()) ax.background_patch.set_visible(False) ax.outline_patch.set_visible(True) ax.add_feature(cfeature.LAND, facecolor='whitesmoke') ax.coastlines() ax.add_feature(cfeature.BORDERS) # selects which data to plot, from larger dataframe gd = (df_plot.Name == "IRMA") Long_vals = df_plot.loc[gd,'Long'].values Lat_vals = df_plot.loc[gd,'Lat'].values data = np.array([Long_vals,Lat_vals]) # set up empty plot l, = ax.plot([], [], c='red') # define how to add points to plot in animation def update_track(num, data, line): line.set_data(data[..., :num]) return line, anim = animation.FuncAnimation(fig, update_track, fargs=(data, l), frames=60, interval=50, blit=True, repeat=False) At the moment, the bottom of my plot looks like this... with a similar amount of whitespace at the top and sides. Can I make it fit in more flush to the rest of the notebook? Thanks.
downvote count: 0
has title: White space around matplotlib animation
upvote count: 6
favorite count: 0
tagged with: jupyter-notebook
answer count: 0
type: UnansweredQuestion
tagged with: animation
score: 6
tagged with: python
tagged with: plot
tagged with: matplotlib

http://stackoverflow.com/comment/88224823
has text: Is it a C function or a C++ function ? The title says C function, whereas the description paints a different picture.
score: 0
comment on: http://stackoverflow.com/q/50607524
type: Comment
type: QuestionComment

django-rest-framework
tags question: http://stackoverflow.com/q/50643808
tags question: http://stackoverflow.com/q/50570687
tags question: http://stackoverflow.com/q/50584249
tags question: http://stackoverflow.com/q/50563042
tags question: http://stackoverflow.com/q/50654337
tags question: http://stackoverflow.com/q/50678057
tags question: http://stackoverflow.com/q/50626959
tags question: http://stackoverflow.com/q/50625057
tags question: http://stackoverflow.com/q/50689328
tags question: http://stackoverflow.com/q/50563459
type: Tag
tags question: http://stackoverflow.com/q/50585110
tags question: http://stackoverflow.com/q/50642388
tags question: http://stackoverflow.com/q/50686844
tags question: http://stackoverflow.com/q/50638300
tags question: http://stackoverflow.com/q/50577585
tags question: http://stackoverflow.com/q/50582519
tags question: http://stackoverflow.com/q/50651557
tags question: http://stackoverflow.com/q/50678549
tags question: http://stackoverflow.com/q/50648521
tags question: http://stackoverflow.com/q/50631349
tags question: http://stackoverflow.com/q/50618855
tags question: http://stackoverflow.com/q/50624345
tags question: http://stackoverflow.com/q/50698291
tags question: http://stackoverflow.com/q/50560673
tags question: http://stackoverflow.com/q/50689081
tags question: http://stackoverflow.com/q/50577697
tag name: django-rest-framework
tags question: http://stackoverflow.com/q/50694774
tags question: http://stackoverflow.com/q/50673092
tags question: http://stackoverflow.com/q/50688007
tags question: http://stackoverflow.com/q/50575902
tags question: http://stackoverflow.com/q/50595929
tags question: http://stackoverflow.com/q/50545408
tags question: http://stackoverflow.com/q/50551767
tags question: http://stackoverflow.com/q/50618261
tags question: http://stackoverflow.com/q/50676008
tags question: http://stackoverflow.com/q/50629666
tags question: http://stackoverflow.com/q/50602670
tags question: http://stackoverflow.com/q/50546984
tags question: http://stackoverflow.com/q/50678541
tags question: http://stackoverflow.com/q/50645519
tags question: http://stackoverflow.com/q/50621829
tags question: http://stackoverflow.com/q/50651509

http://stackoverflow.com/q/50646663
tagged with: python
has answer: http://stackoverflow.com/a/50646893
downvote count: 2
linked to: http://stackoverflow.com/q/7129285
type: Question
tagged with: function
has body: I must modify the function gp so it will handle + and - grades by adding or subtracting 0.3 points. For example, a B + is worth 3.3 points, and a C- is 1.7 points. Example. &gt;&gt;&gt; gp('A-') 3.7 &gt;&gt;&gt;gp('B+') 3.3 The suggestion is I could just add a bunch of elif clauses to test each grade separately, but a similar design is to use a call to s.startswith to figure out the value of the letter grade, then use s.endswith to see if you should add or subtract 0.3 points. So far this is what I have. def gp(s): A = 4 return A B = 3 return B C = 2 return C D = 1 return D F = 0 return f
has answer: http://stackoverflow.com/a/50646879
has answer: http://stackoverflow.com/a/50646915
score: -1
has comment: http://stackoverflow.com/comment/88303896
has comment: http://stackoverflow.com/comment/88309660
upvote count: 1
tagged with: variables
has comment: http://stackoverflow.com/comment/88304130
favorite count: 0
has title: Modifying a function to return different values
tagged with: return
has answer: http://stackoverflow.com/a/50649495
answer count: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88303913
has answer: http://stackoverflow.com/a/50646872

http://stackoverflow.com/a/50646872
type: Answer
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50646663
has body: Instead of a series of if/elif statements, you can store the numeric values for the grades and the suffixes in dictionaries. Also, you do not have to use startswith or endswith, you could just use s[0] and s[1] to get the first or second character in the string, after checking the length. You can also use s[1:] to get everything starting at the 1th position, even if it's empty. grades = {'A': 4, 'B': 3, 'C': 2, 'D': 1, 'F': 0} signs = {'+': 0.3, '-': -0.3, '': 0} def gp(s): return grades[s[0]] + signs[s[1:]] &gt;&gt;&gt; gp("A+") 4.3 &gt;&gt;&gt; gp("C-") 1.7 &gt;&gt;&gt; gp("F") 0
has comment: http://stackoverflow.com/comment/88304466
upvote count: 3
has comment: http://stackoverflow.com/comment/88304484

http://stackoverflow.com/a/50614452
accepted answer of: http://stackoverflow.com/q/50614187
has body: You can achieve this by using getattr: name1 = sys.argv.pop() # ... values = getattr(myconfig, name1) self.do_x(values['lower_bound'], values['upper_bound']) Please note that getattr is case sensitive, this means that while getattr(myconfig, 'Oink') will yield the correct value, getattr(myconfig, 'oink') will raise an AttributeError If you want to handle invalid values, you can use hasattr: if not hasattr(myconfig, name1): raise ValueError('Invalid value {}'.format(name1)) values = getattr(myconfig, name1) self.do_x(values['lower_bound'], values['upper_bound']) If instead of raising a ValueError you want to use a default value, you can use the default keyword argument for getattr: default = dict(lower_bound=20, upper_bound=50) values = getattr(myconfig, name1, default=default) self.do_x(values['lower_bound'], values['upper_bound'])
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50614187
upvote count: 1

http://stackoverflow.com/comment/88416128
score: 0
has text: Could you help me? I have this error: OpenCV Error: Insufficient memory (Failed to allocate 2072706048 bytes) in cv::OutOfMemoryError, file D:\cv\opencv_3.2.0\sources_with TextModule\modules\core\src\alloc.cpp, line 52 OpenCV Error: Assertion failed (u != 0) in cv::Mat::create, file D:\cv\opencv_3.2.0\sources_withTextModule\modules\core\src\matrix.cpp, line 433 @MIcka
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50673055

http://stackoverflow.com/comment/88238337
type: QuestionComment
type: Comment
has text: @DanielleM.it mean The operating system cannot run %1
comment on: http://stackoverflow.com/q/50614206
score: 0

http://stackoverflow.com/q/50590720
upvote count: 3
tagged with: string-formatting
accepted answer: http://stackoverflow.com/a/50591670
type: Question
score: 3
has comment: http://stackoverflow.com/comment/88190878
has answer: http://stackoverflow.com/a/50590921
has title: Python 2.7 format string padding with more than one char
has comment: http://stackoverflow.com/comment/88423740
has answer: http://stackoverflow.com/a/50590964
answer count: 3
possible better answer: http://stackoverflow.com/a/50590921
downvote count: 0
has body: The Problem I've been able to pad a string with asterisk, however I'd like to see if it is possible to pad it with an asterisk and a space. Example Output What I've been able to get ****************************Hello World*************************** ... trying to get * * * * * * * * * * * * * * Hello World* * * * * * * * * * * * * * Attempts Naively I tried passing a " *" to the fill parameter of the format specs. This returned with an error: Traceback (most recent call last): File "main.py", line 17, in &lt;module&gt; ret_string = '*{:{f}^{n}}'.format(string, f=filler, n=line_len) ValueError: Invalid conversion specification Then I tried using an escape character, "\s*", which yielded the same result. Finally I revisited the documentation 6.1.3.1. Format Specification Mini-Language and see the input spec appears to be limited to a character and not open to strings. Is there a way around this? I thought of making a sort of compound reference ie {{char1}{char2}} but that doesn't seemed to have worked either. Thoughts? The Code import fileinput string = "Hello World" ret_string = "" line_len = 65 filler = " *" for inputstring in fileinput.input(): string = inputstring.strip(" \n") ret_string = '{:{f}^{n}}'.format(string, f=filler, n=line_len) print(ret_string)
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/50591670
tagged with: python
has comment: http://stackoverflow.com/comment/88191054
type: AnsweredQuestion

http://stackoverflow.com/comment/88358300
has text: Have you run `sudo service nginx restart` and `sudo service gunicorn restart` ???
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50674132
type: Comment

http://stackoverflow.com/comment/88365109
type: QuestionComment
has text: What's the full error?
comment on: http://stackoverflow.com/q/50677749
score: 0
type: Comment

http://stackoverflow.com/comment/88124791
comment on: http://stackoverflow.com/a/50556924
type: Comment
has text: I have quite a lot actually ex: I'm is written as im in one dataframe..no apostrophes are used
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88178753
has text: You're misusing global keyword, but they **are changed**. https://ideone.com/p0Y6Ua
comment on: http://stackoverflow.com/q/50584701
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88336162
type: QuestionComment
has text: You shouldn't care, because you are confusing the name of the module with the Python identifier bound to the module. You could write `from dir import A as foobar`, and `print(foobar)` would still print `<class 'dir.a.A'>` Try `import os.path; print(os.path)` sometime.
type: Comment
comment on: http://stackoverflow.com/q/50661802
score: 0

http://stackoverflow.com/a/65121519
upvote count: 2
type: Answer
has body: On Ubuntu under flask webframework this should be working pytesseract.pytesseract.tesseract_cmd = r"/usr/bin/tesseract" img = Image.open(picture_name) print(pytesseract.image_to_string(img))
downvote count: 0
answers question: http://stackoverflow.com/q/50655738
score: 2

http://stackoverflow.com/comment/88128234
score: 1
type: AnswerComment
has text: Wow this is incredible. Thanks so much!
type: Comment
comment on: http://stackoverflow.com/a/50557133

http://stackoverflow.com/q/50601713
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50601857
upvote count: 8
type: Question
has answer: http://stackoverflow.com/a/50601829
tagged with: split
has answer: http://stackoverflow.com/a/50601997
has body: Where should we use X_train,X_test,y_train,y_test= train_test_split(data, test_size=0.3, random_state=42) and where should we use train, test= train_test_split(data, test_size=0.3, random_state=0). The former one return this: value error: not enough values to unpack (expected 4, got 2)
favorite count: 0
answer count: 3
has title: How to split training and test sets?
score: 8
downvote count: 0

http://stackoverflow.com/comment/88119579
comment on: http://stackoverflow.com/q/50554139
type: Comment
type: QuestionComment
has text: Related/dupe: [How to read each line from a file into list word by word in Python](//stackoverflow.com/q/27722068)
score: 0

http://stackoverflow.com/comment/114911789
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50582132
score: 0
has text: @SZhang what was the solution can you please explain a bit? I am facing the same issue.

http://stackoverflow.com/comment/88342830
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50660317
has text: I think that may be what is happening. I’m working on a single large parquet file (so the first partition is also the entire data frame). Spark returns instantaneously and Dask takes a minute or so to return. Perhaps with dask I have to work with smaller partitions of the same data....

http://stackoverflow.com/comment/88381604
type: QuestionComment
has text: Here's a start: https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html
comment on: http://stackoverflow.com/q/50685860
score: 0
type: Comment

http://stackoverflow.com/q/50641849
type: Question
has comment: http://stackoverflow.com/comment/88295860
score: 0
has comment: http://stackoverflow.com/comment/88313379
has comment: http://stackoverflow.com/comment/88294535
has comment: http://stackoverflow.com/comment/88295613
tagged with: web2py
has title: Insertion on MySql Table Fails
has comment: http://stackoverflow.com/comment/88313202
tagged with: pydal
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88294393
has body: Guys I am building an application with web2py and I need to store and query some information from my MySql datababase. I am trying to insert a row in the table search_term. I am following strictly the web2Py DAL and pyDAL documentations. #my table definition CREATE TABLE search_term ( term_id int(11) NOT NULL AUTO_INCREMENT, term varchar(100) NOT NULL, lang varchar(10) NOT NULL, since_date date DEFAULT NULL, until_date date DEFAULT NULL, quantity int(11) DEFAULT NULL, PRIMARY KEY (term_id) ); #in db.py db = DAL('mysql://myUser:myPassWord@localhost/myDB') search_term_table = db.define_table('search_term', Field('term_id', 'integer'), Field('term', 'string', requires=[IS_NOT_EMPTY()]), Field('lang', 'string', requires=[IS_NOT_EMPTY()]), Field('quantity', 'integer', requires=[IS_NOT_EMPTY()]), Field('since_date', 'date', requires=[IS_DATETIME()]), Field('until_date', 'date', requires=[IS_DATETIME()])) #in controller result = search_term_table.insert(term = "sample", lang = 'en', quantity = 300) When I am debugging, everything seems to occur well, but when I execute the select * from search_table in MySQL Workbench, to verify if the data was stored, the table is still empty. Am I doing something wrong? Can someone help me? Thanks a lot!!
has comment: http://stackoverflow.com/comment/88313187
tagged with: python
tagged with: crud
has comment: http://stackoverflow.com/comment/88295290
has comment: http://stackoverflow.com/comment/88295675
tagged with: mysql
has comment: http://stackoverflow.com/comment/88295821

http://stackoverflow.com/comment/88345008
type: AnswerComment
has text: I have edited the question to add corresponding python code along with the Sorting Contours as per your suggestion, but no luck. Can you please help me
type: Comment
comment on: http://stackoverflow.com/a/50666007
score: 0

http://stackoverflow.com/q/50626810
upvote count: 1
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/50627117
accepted answer: http://stackoverflow.com/a/50627117
has comment: http://stackoverflow.com/comment/88264201
answer count: 1
downvote count: 0
favorite count: 0
tagged with: one-hot-encoding
tagged with: python
has body: I have the following test program in Python: import tensorflow as tf sess = tf.InteractiveSession() # Some tensor we want to print the value of a = tf.one_hot(1,5) # Add print operation a = tf.Print(a, [a], message = "This is a: ") # Add more elements of the graph using a b = tf.add(a, a) b.eval() I call the function that shall create a nice one hot encoding. I would expect that the output is: array([0., 1., 0., 0., 0.], dtype=float32) But instead the output is: array([0., 2., 0., 0., 0.], dtype=float32) Why?
type: AnsweredQuestion
score: 1
has title: Why does tensorflow doubles the one_hot on values?

http://stackoverflow.com/comment/88180173
type: QuestionComment
score: 1
has text: Your code works for me, make sure you are using Python 3 as suggested by @zimdero
comment on: http://stackoverflow.com/q/50585361
type: Comment

http://stackoverflow.com/q/50580459
downvote count: 0
has comment: http://stackoverflow.com/comment/88170261
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50711224
has comment: http://stackoverflow.com/comment/88172419
has answer: http://stackoverflow.com/a/50589936
score: 1
has body: I have a sparse matrix and another vector and I want to multiply the matrix and vector so that each column of the vector where it's equal to zero it'll zero the entire column of the sparse matrix. How can I achieve that?
tagged with: scipy
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/50580580
tagged with: linear-algebra
tagged with: sparse-matrix
answer count: 3
upvote count: 1
has title: For a given sparse matrix, how can I multiply it with a given vector of binary values

http://stackoverflow.com/a/61512789
downvote count: 0
score: 4
type: Answer
answers question: http://stackoverflow.com/q/50587634
upvote count: 4
has body: This open plotnine issue describes a similar enhancement request. Currently the mpl_to_plotly function seems to work sometimes (for some geoms?), but not consistently. The following code, seems to work ok. from plotnine import * from plotly.tools import mpl_to_plotly as ggplotly import numpy as np import pandas as pd a = pd.DataFrame({'grid': np.arange(-4, 4), 'test_data': np.random.randint(0, 10,8)}) p2 = ggplot(a, aes(x = 'grid', y = 'test_data')) + geom_point() ggplotly(p2.draw())

http://stackoverflow.com/comment/88381880
comment on: http://stackoverflow.com/a/50686101
type: AnswerComment
score: 0
has text: What's the best way to compare these in this case?
type: Comment

http://stackoverflow.com/a/50641813
upvote count: 2
has comment: http://stackoverflow.com/comment/88342008
has body: Use transform for Series with same size as original DataFrame, binning with cut and aggregate sum: df['DATE_LOCATION'] = pd.to_datetime(df['DATE_LOCATION'], format='%d-%m-%y %H:%M') df = df.sort_values("DATE_LOCATION") s = (df["DATE_LOCATION"].diff().dt.days &gt; 1).cumsum() count = s.groupby(s).transform('size') print (count) 0 2 1 2 2 4 3 4 4 4 5 4 6 2 7 2 8 1 9 3 10 3 11 3 Name: DATE_LOCATION, dtype: int32 bins = pd.cut(count, bins=[0,3,7,15,31], labels=['1-3', '4-7','8-15', '&gt;=16']) df = df.groupby(['PRODUCT_ID', bins])['Sold'].sum().reset_index() print (df) PRODUCT_ID DATE_LOCATION Sold 0 0E4234 1-3 9 1 0E4234 4-7 7 2 0G2342 1-3 11
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88342102
accepted answer of: http://stackoverflow.com/q/50621605
has comment: http://stackoverflow.com/comment/88342026
answers question: http://stackoverflow.com/q/50621605
has comment: http://stackoverflow.com/comment/88356643
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88342058
has comment: http://stackoverflow.com/comment/88341964
has comment: http://stackoverflow.com/comment/88343058
has comment: http://stackoverflow.com/comment/88342076
has comment: http://stackoverflow.com/comment/88341946

http://stackoverflow.com/comment/101589562
comment on: http://stackoverflow.com/a/53561512
has text: Thanks! uninstalled my-connector & installed mysql-connector-python and it worked!
type: AnswerComment
score: 10
type: Comment

http://stackoverflow.com/comment/113777373
comment on: http://stackoverflow.com/a/50610834
score: 0
type: Comment
has text: @ElieG. It is probably a bug in your IDE that does not handle PySide2 stubs since PySide2 is written in C++
type: AnswerComment

http://stackoverflow.com/a/63645287
answers question: http://stackoverflow.com/q/50662773
has comment: http://stackoverflow.com/comment/125016958
has body: in my case , correct with just simply add this line root = tkinter.Tk() complete code : root = tkinter.Tk() image = PIL.Image.open(r"C:\Users\Hamid\Desktop\asdasd\2.jpeg") img = ImageTk.PhotoImage(image) l = Label(image=img) l.pack()
downvote count: 0
has comment: http://stackoverflow.com/comment/133058175
type: Answer
upvote count: 12
score: 12

http://stackoverflow.com/comment/88329787
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50659747
has text: I want the code to ask the user to guess age numbers, weight, and month and let them know if they got the right answer by congratulating them.

http://stackoverflow.com/a/50808482
answers question: http://stackoverflow.com/q/50571191
has body: The Gurobi API does not support sharing a single Gurobi environment across multiple processes or threads. If you want to solve multiple modules in multiple processes or threads, you must explicitly create multiple Gurobi environments in each process or thread.
type: Answer
has comment: http://stackoverflow.com/comment/89092572
has comment: http://stackoverflow.com/comment/89091993
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50571191
score: 1
has comment: http://stackoverflow.com/comment/89082071
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88212235
type: Comment
comment on: http://stackoverflow.com/a/50600551
has text: Actually, it's even more like O(n^4), as you have to check squares of sizes 1..n for all nxn positions, and each square will contain on the order of n points that have to be checked. Still, for n=16 not a problem.
score: 0
type: AnswerComment

http://stackoverflow.com/q/50572315
downvote count: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88986773
accepted answer: http://stackoverflow.com/a/50572805
score: 0
tagged with: numpy-indexing
has title: Numpy 2d array - select multiple elements without a for loop
answer count: 1
has body: I maintain some code and I run across something like: travel_time_vec = np.zeros(...) for v in some_indexes: # some_indexes is a list of row indexes traveltimes = traveltime_2d_array[v, list_of_column_indexes] best_index = np.argmin(traveltimes) travel_time_vec[v] = traveltimes[best_index] I would like to drop the for loop and do all the operations below at once - but naively asking for traveltime_2d_array[some_indexes, list_of_column_indexes] results in: {IndexError}shape mismatch: indexing arrays could not be broadcast together with shapes (4,) (8,)
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88154135
has answer: http://stackoverflow.com/a/50572805
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88154230
linked to: http://stackoverflow.com/q/22927181
upvote count: 1

string
tags question: http://stackoverflow.com/q/50599934
tags question: http://stackoverflow.com/q/50667036
tags question: http://stackoverflow.com/q/50659242
tags question: http://stackoverflow.com/q/50693203
tags question: http://stackoverflow.com/q/50657239
tags question: http://stackoverflow.com/q/50684170
tags question: http://stackoverflow.com/q/50548051
tags question: http://stackoverflow.com/q/50636379
tags question: http://stackoverflow.com/q/50610455
tags question: http://stackoverflow.com/q/50660221
tags question: http://stackoverflow.com/q/50666340
tags question: http://stackoverflow.com/q/50590720
tags question: http://stackoverflow.com/q/50554589
tags question: http://stackoverflow.com/q/50594257
tags question: http://stackoverflow.com/q/50580427
tags question: http://stackoverflow.com/q/50614187
tags question: http://stackoverflow.com/q/50647587
tags question: http://stackoverflow.com/q/50689672
tags question: http://stackoverflow.com/q/50561412
tags question: http://stackoverflow.com/q/50574633
tags question: http://stackoverflow.com/q/50610739
tags question: http://stackoverflow.com/q/50626817
tags question: http://stackoverflow.com/q/50685524
tags question: http://stackoverflow.com/q/50547739
tags question: http://stackoverflow.com/q/50606874
tags question: http://stackoverflow.com/q/50612328
tags question: http://stackoverflow.com/q/50670954
tags question: http://stackoverflow.com/q/50549831
tags question: http://stackoverflow.com/q/50633935
tags question: http://stackoverflow.com/q/50664026
tags question: http://stackoverflow.com/q/50559529
tags question: http://stackoverflow.com/q/50576329
tags question: http://stackoverflow.com/q/50592013
tag name: string
tags question: http://stackoverflow.com/q/50658713
tags question: http://stackoverflow.com/q/50683701
tags question: http://stackoverflow.com/q/50623709
tags question: http://stackoverflow.com/q/50557093
tags question: http://stackoverflow.com/q/50596147
tags question: http://stackoverflow.com/q/50612447
tags question: http://stackoverflow.com/q/50683716
tags question: http://stackoverflow.com/q/50563844
tags question: http://stackoverflow.com/q/50583871
tags question: http://stackoverflow.com/q/50624851
tags question: http://stackoverflow.com/q/50573813
tags question: http://stackoverflow.com/q/50693145
tags question: http://stackoverflow.com/q/50580481
tags question: http://stackoverflow.com/q/50684429
tags question: http://stackoverflow.com/q/50663716
type: Tag
tags question: http://stackoverflow.com/q/50656196
tags question: http://stackoverflow.com/q/50677372
tags question: http://stackoverflow.com/q/50588648
tags question: http://stackoverflow.com/q/50633385
tags question: http://stackoverflow.com/q/50608513
tags question: http://stackoverflow.com/q/50667909
tags question: http://stackoverflow.com/q/50628617
tags question: http://stackoverflow.com/q/50642819
tags question: http://stackoverflow.com/q/50562784
tags question: http://stackoverflow.com/q/50552360
tags question: http://stackoverflow.com/q/50583901
tags question: http://stackoverflow.com/q/50597592
tags question: http://stackoverflow.com/q/50669309
tags question: http://stackoverflow.com/q/50548728
tags question: http://stackoverflow.com/q/50697388
tags question: http://stackoverflow.com/q/50557621
tags question: http://stackoverflow.com/q/50652473
tags question: http://stackoverflow.com/q/50548122
tags question: http://stackoverflow.com/q/50687768
tags question: http://stackoverflow.com/q/50681795
tags question: http://stackoverflow.com/q/50686078
tags question: http://stackoverflow.com/q/50555529
tags question: http://stackoverflow.com/q/50584760
tags question: http://stackoverflow.com/q/50672948
tags question: http://stackoverflow.com/q/50602508
tags question: http://stackoverflow.com/q/50600841
tags question: http://stackoverflow.com/q/50683765

http://stackoverflow.com/a/50600426
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50600105
downvote count: 0
has body: You don't. If you're accepting so many arguments that the boilerplate is large, you're doing it wrong. You do def sanitize(x): # do sanitation things return new_x def test_func(a, b): a = santize(a) b = santize(b)
type: Answer

http://stackoverflow.com/comment/88219754
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50605094
has text: How do I get the URL?

systemd
tags question: http://stackoverflow.com/q/50560161
tag name: systemd
type: Tag

http://stackoverflow.com/a/50674132
answers question: http://stackoverflow.com/q/50673930
has comment: http://stackoverflow.com/comment/88358140
has comment: http://stackoverflow.com/comment/88358227
has comment: http://stackoverflow.com/comment/88358004
has comment: http://stackoverflow.com/comment/88358077
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88358169
accepted answer of: http://stackoverflow.com/q/50673930
has body: You have updated the settings.py in only local system and you have not uploaded the updated settings code to production. I went through your url and error it is showing that. see your ALLOWED_HOSTS it only contains '206.189.179.58' and 'maginate.net' and 'www.maginate.net' is not added in ALLOWED_HOSTS. Just try changing and uploading. Update after seeing code You have put your settings.py and local_settings.py inside portfolio directory but it should be inside portfolio/portfolio It will work fine.
type: Answer
has comment: http://stackoverflow.com/comment/88358196
has comment: http://stackoverflow.com/comment/88358052
has comment: http://stackoverflow.com/comment/88358300
has comment: http://stackoverflow.com/comment/88358353
score: 2
has comment: http://stackoverflow.com/comment/88358030
upvote count: 2

http://stackoverflow.com/a/50692103
score: 1
has comment: http://stackoverflow.com/comment/88394104
has comment: http://stackoverflow.com/comment/88393969
upvote count: 1
answers question: http://stackoverflow.com/q/50691616
downvote count: 0
type: Answer
has body: The GeneratorExit is raised whenever a generator or coroutine is closed. Even without the context manager, we can replicate the exact condition with a simple generator function that prints out the exception information when it errors (further reducing the provided code to show exactly how and where that exception is generated). import sys def dummy_gen(): for idx in range(5): try: yield idx except: print(sys.exc_info()) raise for i in dummy_gen(): raise ValueError('foo') Usage: (&lt;class 'GeneratorExit'&gt;, GeneratorExit(), &lt;traceback object at 0x7f96b26b4cc8&gt;) Traceback (most recent call last): File "&lt;stdin&gt;", line 2, in &lt;module&gt; ValueError: foo Note there was also an exception that was raised inside the generator itself, as noted that the except block was executed. Note that the exception was also further raise'd after the print statement but note how that isn't actually shown anywhere, because it is handled internally. We can also abuse this fact to see if we can manipulate the flow by swallowing the GeneratorExit exception and see what happens. This can be done by removing the raise statement inside the dummy_gen function to get the following output: (&lt;class 'GeneratorExit'&gt;, GeneratorExit(), &lt;traceback object at 0x7fd1f0438dc8&gt;) Exception ignored in: &lt;generator object dummy_gen at 0x7fd1f0436518&gt; RuntimeError: generator ignored GeneratorExit Traceback (most recent call last): File "&lt;stdin&gt;", line 2, in &lt;module&gt; ValueError: foo Note how there is an internal RuntimeError that was raised that complained about the generator ignoring the GeneratorExit function. So we from this we can clearly see that this exception is produced by the generator itself inside the generator function, and the ValueError that is raised outside that scope is never present inside the generator function. Since a context manager will trap all exceptions as is, and the context manager is inside the generator function, whatever exception raised…

http://stackoverflow.com/q/50623788
has answer: http://stackoverflow.com/a/50623876
type: Question
has body: I am currently trying to implement the Bully Algorithm in NodeJS. In this algorithm, I have a while loop which, when called by the main script, check for the states of nodes. I would like to run the main file and the while loop simultaneously. Is there a way to do this ? I know that in Python for example, we can use gevent and spawn(). Is there a way to achieve such thing in NodeJS ? In Python, I have a group (self.pool) in which I 'push' self.check() which runs the while loop allowing me to check for nodes. self.check_servers_greenlet = self.pool.spawn(self.check())
tagged with: javascript
score: 0
has answer: http://stackoverflow.com/a/50624298
answer count: 2
has title: Concurrency in NodeJS
type: UnansweredQuestion
tagged with: multithreading
tagged with: python
tagged with: node.js
tagged with: concurrency

http://stackoverflow.com/a/50708589
type: AcceptedAnswer
downvote count: 0
has body: Assuming you want to use the jsonify function, you can do this by defining a custom JSONEncoder as so, from quart.json import JSONEncoder class CustomJSONEncoder(JSONEncoder): def default(self, obj): if isinstance(obj, Color): return obj.t elif isinstance(obj, ObjA): return { 'name': obj.name, '_color': self.default(obj._color), } else: return JSONEncoder.default(self, obj) app = Quart(__name__) app.json_encoder = CustomJSONEncoder Note I've changed the __color variable to _color to avoid issues with name mangling.
accepted answer of: http://stackoverflow.com/q/50695772
type: Answer
answers question: http://stackoverflow.com/q/50695772
score: 2
upvote count: 2

http://stackoverflow.com/comment/88151661
score: 1
comment on: http://stackoverflow.com/q/50570808
type: QuestionComment
type: Comment
has text: Anyway, 18 is the correct number there.

http://stackoverflow.com/a/50674542
has comment: http://stackoverflow.com/comment/88415676
score: 0
answers question: http://stackoverflow.com/q/50669646
has comment: http://stackoverflow.com/comment/88406743
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50669646
type: Answer
has body: You need to inherit IO https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html#inheritIO() Sets the source and destination for subprocess standard I/O to be the same as those of the current Java process. This is a convenience method. An invocation of the form pb.inheritIO() Then, your Process execution can take following form public class ProcessSample { public static void main(String [] arg) throws Exception { ProcessBuilder pb = new ProcessBuilder("python", "script.py").inheritIO(); Process p = pb.start(); p.waitFor(); } } and, with your script name = raw_input("What is your name? ") print "your name is "+name you can do &gt; javac ProcessSample.java &gt; java -cp . ProcessSample What is your name? a your name is a Inheriting IO for stdout You can always pass some values to Python code while at the same time read values from stdout - by inheriting it. import java.io.*; public class PythonProcessRedirect { public static void main(String [] arg) throws Exception { ProcessBuilder pb = new ProcessBuilder("python", "script_raw.py"); pb.redirectErrorStream(true); pb.redirectOutput(ProcessBuilder.Redirect.INHERIT); Process p = pb.start(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter( p.getOutputStream() )); String input = "2\n"; writer.write(input); writer.flush(); p.waitFor(); } } Note that for continuous flow of data you need to flush it import sys import time sys.stdout.write("give some input: ") sys.stdout.flush() time.sleep(2) line = sys.stdin.readline() sys.stdout.write("you typed: " + line) sys.stdout.flush(); otherwise, data will be available not sooner than Python flushes it (e.g. by filling buffer up to the limit). Stream Gobbler You can also go with Stream Gobbler and run separate threads for stdin/stdout/stderr. import java.io.*; public class PythonProcessStreamGobblerIO { public static void main(String [] arg) throws Exception { final Process p = Runtime.getRuntime().exec("python ./script_os.py" ); new Thread() { public …

http://stackoverflow.com/comment/88361387
type: Comment
comment on: http://stackoverflow.com/q/50650491
score: 0
has text: @BPL This is what we've ended up doing, cheers as well :)
type: QuestionComment

http://stackoverflow.com/q/50545339
tagged with: machine-learning
tagged with: python
has body: I am learning to do classification for Cover Type data for 7 classes. I train my model with GradientBoostingClassifier from scikit-learn. When I try to plot my loss function this goes like this: Is this kind of plot shows me that my model suffers from high variance? If yes, what should I do? And I don't know why in the middle of iterations 200 until 500, the plot is shaped like a rectangle. (EDIT) To edit this post, I'm not sure what's wrong with my code becaue I just used the regular code to fit the training data. I'm using jupyter notebook. So I'm just going to provide the code Y = train["Cover_Type"] X = train.drop({"Cover_Type"}, axis=1) #split training data dan cross validation from sklearn.model_selection import train_test_split X_train, X_val, Y_train, Y_val = train_test_split(X,Y,test_size=0.3,random_state=42) from sklearn.metrics import mean_squared_error from sklearn.datasets import make_friedman1 from sklearn.ensemble import GradientBoostingClassifier params = {'n_estimators': 1000,'learning_rate': 0.3, 'max_features' : 'sqrt'} dtree=GradientBoostingClassifier(**params) dtree.fit(X_train,Y_train) #mau lihat F1-Score from sklearn.metrics import f1_score Y_pred = dtree.predict(X_val) #prediksi data cross validation menggunakan model tadi print Y_pred score = f1_score(Y_val, Y_pred, average="micro") print("Gradient Boosting Tree F1-score: "+str(score)) # I got 0.86 F1-Score import matplotlib.pyplot as plt # Plot training deviance # compute test set deviance val_score = np.zeros((params['n_estimators'],), dtype=np.float64) for i, Y_pred in enumerate(dtree.staged_predict(X_val)): val_score[i] = dtree.loss_(Y_val, Y_pred.reshape(-1, 1)) plt.figure(figsize=(12, 6)) plt.subplot(1, 2, 1) plt.title('Deviance') plt.plot(np.arange(params['n_estimators']) + 1, dtree.train_score_, 'b-', label='Training Set Deviance') plt.plot(np.arange(params['n_estimators']) + 1, val_score, 'r-', label='Validation Set Deviance') plt.legend(loc='upper right') plt.xlabel('Boosting Itera…
upvote count: 1
downvote count: 1
type: Question
score: 0
answer count: 2
tagged with: scikit-learn
favorite count: 0
has title: Train Loss and validation loss GradientBoostingClassifier
has answer: http://stackoverflow.com/a/55607308
has answer: http://stackoverflow.com/a/50545575
type: UnansweredQuestion

http://stackoverflow.com/comment/104061126
type: AnswerComment
has text: Thanks, I realized that one of the characters in my filename was not latin although it looked like it!
type: Comment
comment on: http://stackoverflow.com/a/53762112
score: 1

http://stackoverflow.com/comment/88274532
score: 0
has text: I guess this error is because length of A is less than length of B in the excel file
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50610328

http://stackoverflow.com/comment/88104813
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50547033
has text: Makes sense ! Thank you for taking the time to explain, Paula, code works and I understood !
type: AnswerComment

http://stackoverflow.com/comment/88238656
comment on: http://stackoverflow.com/a/50614213
type: AnswerComment
score: 0
type: Comment
has text: @coldspeed That was all I was curious about. You've been around longer than I had, and I was wondering if there were any hard and fast reasons. Is that mentioned in any documentation/guidelines anywhere? If not, is it reasonable to add it? I think the Python2/3 debate was the core of our misunderstanding last time too.

http://stackoverflow.com/q/50638076
has comment: http://stackoverflow.com/comment/88286155
answer count: 0
has comment: http://stackoverflow.com/comment/88286268
has comment: http://stackoverflow.com/comment/88286186
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88288644
has body: I am trying to convert a 4-columns xlsx to csv, retaining the 4-columns format. Every solution I tried (csv and pandas modules) keeps merging the 4 columns into 1, separating them with ',' (or any separator I choose). Is there any way to write into separated columns? Thank you in advance Edit: Example of my xlsx number1 number11 name1 name11 number2 number22 name2 name22 ... number(n) number(nn) name(n) name(nn) With the answers I tried I get: number1,number11,name1,name11 number2,number22,name2,name22 .... number(n),numer(nn),name(n),name(nn) I want to keep the 4-column format just like if I write it on excel and save it .csv(comma seperated) The blocks of code I have tried: csv: import csv def to_csv(ws, csvname): with open(csvname, 'w', newline="") as f: c = csv.writer(f, dialect=csv.excel) for r in ws.rows: c.writerow([cell.value for cell in r]) pandas: import pandas def pd_to_csv(file): data_xls = pd.read_excel(file, index_col=None, encoding='iso8859_7') data_xls.to_csv(str(name[0:-5]) + '.csv', index=False, encoding='iso8859_7')
has comment: http://stackoverflow.com/comment/88288763
linked to: http://stackoverflow.com/q/47894861
type: Question
has comment: http://stackoverflow.com/comment/88288581
has comment: http://stackoverflow.com/comment/88289113
score: 0
tagged with: http://stackoverflow.com/tag/xlsx
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/88286188
has title: Convert xlsx to csv without merging the columns - Python
has comment: http://stackoverflow.com/comment/88291040
tagged with: python
has comment: http://stackoverflow.com/comment/88288528

http://stackoverflow.com/a/50689172
answers question: http://stackoverflow.com/q/50689079
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/88388554
has body: If we change your code slightly, we can use id to see how the references change (or don't change): L1=[2] L2=['a'] print("Before, L1:", L1, id(L1)) print("Before, L2:", L2, id(L2)) def f(a,b): print("Inside, Before, a:", id(a)) print("Inside, Before, b:", id(b)) a[0] =[3] #Using index-based assignment b = ['b'] #Direct assignment print("Inside, After, a:", id(a)) print("Inside, After, b:", id(b)) #Pass L to f f(L1,L2) print("After, L1:", L1, id(L1)) print("After, L2:", L2, id(L2)) Output: Before, L1: [2] 1870498294152 # L1 Before, L2: ['a'] 1870498294280 # L2 Inside, Before, a: 1870498294152 # L1 Inside, Before, b: 1870498294280 # L2 Inside, After, a: 1870498294152 # L1 Inside, After, b: 1870498239496 # Something different, not L2 After, L1: [[3]] 1870498294152 # L1 After, L2: ['a'] 1870498294280 # L2 Note, the numbers aren't significant in themselves other than to help distinguish references to different objects. Running this yourself (or if I ran it again), would cause the ids to change. With a, you're modifying/mutating a but not attempting to re-assign the reference. That's fine. With b, you're re-assigning the reference. This will work inside the function (as the "Inside, After, b:" print call shows), but this change will not be reflected outside of the function. b will be restored to reference the original object, ['a']. As to why... meaning I am unsure why direct assignment changes the memory location. Inside your function, a and b are just references to objects. Initially, they reference (the objects referenced by) L1 and L2 respectively because by calling f, you're passing references to those objects. a[0] = [3] first dereferences a (or L1 in this case), then the [0] index, and sets that value. In fact, if you look at id(a[0]) before and after that call then that would change. a is a list of references. Try it: print(id(a[0])) # One thing a[0] =[3] #Using index-based assignment print(id(a[0])) # Something different This is fine. When you exit the function L…
accepted answer of: http://stackoverflow.com/q/50689079
type: Answer

http://stackoverflow.com/comment/88375178
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50682404
has text: @WSS A simple comment would have sufficed; no need to provide cryptic links to a screen shot.
type: Comment

http://stackoverflow.com/comment/88118504
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50553442
has text: Thanks for the advice, I just started learning python today and already went ahead implementing this: http://nifty.stanford.edu/2017/guerzhoy-SAT-synonyms/ as a challenge without any knowledge of the language.

http://stackoverflow.com/comment/88595852
has text: @hegdep you could also take the most left most right and a third one from the reduced convex hull. I'd actually make a simple curve_fit to the reduced convex hull. If the values are in the range of 1, which seems to be the case, it should work without initial guess. You can then take the result of that fit as starting point for the iteration.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50694476
type: AnswerComment

http://stackoverflow.com/comment/88225918
type: QuestionComment
comment on: http://stackoverflow.com/q/50608037
has text: "How can I set the turtle to a part of the screen so that it starts there"
score: 0
type: Comment

http://stackoverflow.com/a/50674669
type: Answer
score: 8
has comment: http://stackoverflow.com/comment/88360173
has comment: http://stackoverflow.com/comment/88359805
upvote count: 8
has comment: http://stackoverflow.com/comment/88359816
has body: This is a comment to @MSeifert answer. There are some more things to gain performance. As in every numerical code it is recommendable to think about which datatype is precise enough for your problem. Often float32 is also enough, sometimes even float64 isn't enough. I want also to mention the fastmath keyword here, which can give another 1.7x speed up here. [Edit] For a simple summation I looked into the LLVM-code and found that the sumation was splitted up in partial sums on vectorization. (4 partial sums for double and 8 for float using AVX2). This has to be investigated further. Code import llvmlite.binding as llvm llvm.set_option('', '--debug-only=loop-vectorize') @nb.njit def euclidean_distance_square_numba_v3(x1, x2): res = np.empty(x2.shape[0], dtype=x2.dtype) for o_idx in range(x2.shape[0]): val = 0 for i_idx in range(x2.shape[1]): tmp = x1[0, i_idx] - x2[o_idx, i_idx] val += tmp * tmp res[o_idx] = val return res @nb.njit(fastmath=True) def euclidean_distance_square_numba_v4(x1, x2): res = np.empty(x2.shape[0], dtype=x2.dtype) for o_idx in range(x2.shape[0]): val = 0. for i_idx in range(x2.shape[1]): tmp = x1[0, i_idx] - x2[o_idx, i_idx] val += tmp * tmp res[o_idx] = val return res @nb.njit(fastmath=True,parallel=True) def euclidean_distance_square_numba_v5(x1, x2): res = np.empty(x2.shape[0], dtype=x2.dtype) for o_idx in nb.prange(x2.shape[0]): val = 0. for i_idx in range(x2.shape[1]): tmp = x1[0, i_idx] - x2[o_idx, i_idx] val += tmp * tmp res[o_idx] = val return res Timings float64 x1 = np.random.random((1, 512)) x2 = np.random.random((1000000, 512)) 0.42 v3 @MSeifert 0.25 v4 0.18 v5 parallel-version 0.48 distance.cdist float32 x1 = np.random.random((1, 512)).astype(np.float32) x2 = np.random.random((1000000, 512)).astype(np.float32) 0.09 v5 How to explicitly declare types In general I wouldn't recommend this. Your input arrays can be C-contigous (as the testdata) Fortran contigous or strided. If you know that your data is always C-contiguos you can write …
answers question: http://stackoverflow.com/q/50658884
has comment: http://stackoverflow.com/comment/88359179
downvote count: 0
has comment: http://stackoverflow.com/comment/88360169
has comment: http://stackoverflow.com/comment/88361141
has comment: http://stackoverflow.com/comment/88359071

http://stackoverflow.com/comment/138281436
type: AnswerComment
has text: Please only provide new answers, especially to old questions. The same answer was already posted 5 years ago.
type: Comment
comment on: http://stackoverflow.com/a/78416482
score: 0

http://stackoverflow.com/comment/88359323
score: 0
has text: Maybe `re.findall(r"(?i)BACKUP_(\d+)", " ".join(os.listdir(folder)))` will do?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50674757

http://stackoverflow.com/a/51305952
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/50576247
upvote count: 1
has body: From the django-paypal repo view the sandbox code, in particular the templates folder, settings.py and urls.py. I followed the instructions and added the necessary paypal keys to settings.py as well as the urls.py but failed to copy the templates, since that was documented less carefully. For me simply adding at the very least the same templates as the sandbox made the screen you are viewing be replaced with working paypal buttons. In particular, the sandbox/templates/checkout/payment_details.html seems to be what gets rendered in place of this reminder message you are seeing — note that the template has both Express and Flow options, so use only what your site is set to use.

awk
tag name: awk
type: Tag
tags question: http://stackoverflow.com/q/50694428
tags question: http://stackoverflow.com/q/50597714

http://stackoverflow.com/comment/88328584
has text: you need to create regex expressions for the different cases you find. Then you need to apply them. Start with reading https://docs.python.org/3/library/re.html then move your text over to http://www.regex101.com and try out your regexxes. Iterate until you are statisfied.
comment on: http://stackoverflow.com/q/50659268
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88630602
type: Comment
has text: Actually, as of pip 10 you'll get a warning when installing any library that clashes. e.g. `nameko 2.9.0 has requirement kombu<4,>=3.0.1, but you'll have kombu 4.2.1 which is incompatible.` The installation still proceeds though.
comment on: http://stackoverflow.com/a/50683098
score: 0
type: AnswerComment

http://stackoverflow.com/q/50618403
has answer: http://stackoverflow.com/a/50618491
tagged with: callable
has comment: http://stackoverflow.com/comment/88247013
score: 0
answer count: 2
tagged with: push
has title: I am getting 'tuple' object is not callable as an error
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50618496
tagged with: stack
has body: brackets = set([(()())]) Stack = [] StackSize = 20 ch=(['(',')']) arr=[] Here I have generated a set of brackets which is showing an error. How can it be corrected?
type: Question

http://stackoverflow.com/a/50575651
has body: The error you are getting coz of this part of the code, elif a_options == 2: a_update=raw_input("select a word to update:") a_renew_word = raw_input("the new word") if a_update in empt_list: empt_list[a_update]=a_renew_word else: print "sorry" # print a_list[a_options-1] Since list indices must be integers, you should have an integer passed as a list index in the below code. Below is one more way to do it, if a_update in empt_list: #updated code lst_index=empt_list.index(a_update) empt_list[lst_index]=a_renew_word else: print "sorry" The way you have mentioned could have worked, if the empt_list was a dictionary but not list. Since dictionaries stores data in the form of key, value pairs so they can take both integers and strings as keys.
score: 0
answers question: http://stackoverflow.com/q/50570258
type: Answer

http://stackoverflow.com/q/50608418
has comment: http://stackoverflow.com/comment/88226933
has comment: http://stackoverflow.com/comment/88226871
has answer: http://stackoverflow.com/a/50608752
favorite count: 0
has body: I'm trying to translate the following R code to Python and am stuck because of the row-indexing... df$col3[index+1] &lt;− df$col2[index] # what he want :col2 in certain index assign its value to col3 by index increment 1. Fictitiuous example df = pd.DataFrame({'id' : [1, 1, 1, 2, 2, 3, 4, 4, 4, 4, 5, 5], 'id_old' : [1, 1, 2, 2, 3, 4, 4, 4, 4, 5, 5, 5], 'col1' : np.random.normal(size = 12), 'col2' : np.random.randint(low = 20, high = 50, size = 12), 'col3' : np.repeat(20, 12)}) print(df) myindex = np.where(df.id != df.id_old) # tuple print(myindex) print(np.add(myindex, 1)) replacement_values = df.iloc[myindex]'col2' Output id id_old col1 col2 col3 0 1 1 0.308380 23 20 1 1 1 1.185646 35 20 2 1 2 -0.432066 27 20 3 2 2 0.115055 32 20 4 2 3 0.683291 34 20 5 3 4 -1.916321 42 20 6 4 4 0.888327 34 20 7 4 4 1.312879 29 20 8 4 4 1.260612 27 20 9 4 5 0.062635 22 20 10 5 5 0.081149 23 20 11 5 5 -1.872873 32 20 (array([2, 4, 5, 9]),) [[ 3 5 6 10]] This is what I tried : df.loc[np.add(myindex, 1), 'col3'] = replacement_values df.loc[df.index.isin(np.add(myindex + 1)), 'col3'] = replacement_values Desired result : id id_old col1 col2 col3 0 1 1 0.308380 23 20 1 1 1 1.185646 35 20 2 1 2 -0.432066 27 20 3 2 2 0.115055 32 27 4 2 3 0.683291 34 20 5 3 4 -1.916321 42 34 6 4 4 0.888327 34 42 7 4 4 1.312879 29 20 8 4 4 1.260612 27 20 9 4 5 0.062635 22 20 10 5 5 0.081149 23 22 11 5 5 -1.872873 32 20 I guess I'm overlooking something basic, or am I completely on the wrong path? Thanks a lot for your help!
has title: Replace certain values depending on condition in pandas
upvote count: 2
has comment: http://stackoverflow.com/comment/88226790
has comment: http://stackoverflow.com/comment/88226717
tagged with: python
has answer: http://stackoverflow.com/a/50608657
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/50608703
accepted answer: http://stackoverflow.com/a/50608703
has comment: http://stackoverflow.com/comment/88226724
has comment: http://stackoverflow.com/comment/88226884
has comment: http://stackoverflow.com/comment/88226768
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/88226740
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88226644
possible better answer: http://stackoverflow.com/a/50608657
tagged with: replace
answer count: 3
tagged with: pandas

chronological
type: Tag
tags question: http://stackoverflow.com/q/50689991
tag name: chronological

http://stackoverflow.com/q/50631468
has answer: http://stackoverflow.com/a/50631514
tagged with: python
tagged with: lambda
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
has title: pandas apply upper() works on each of two string columns separately, but not together
upvote count: 2
has answer: http://stackoverflow.com/a/50631531
answer count: 2
accepted answer: http://stackoverflow.com/a/50631531
tagged with: pandas
has comment: http://stackoverflow.com/comment/88273283
has body: I have a simple dataframe along these lines: a b 0 horse cat 1 dog elephant running: df.loc[:,'a'].apply(lambda x: x.upper()) or df.loc[:,'b'].apply(lambda x: x.upper()) gets the animals in the respective column capitalized. However, running df.loc[:,'a':'b'].apply(lambda x: x.upper()) or df.loc[:,['a','b']].apply(lambda x: x.upper()) results in "AttributeError: ("'Series' object has no attribute 'upper'", 'occurred at index a')". Obviously, I would like to know how to fix it (i.e., be able to uppercase both columns at once). But I would also like to know how a column can have the attribute 'upper' on its own, but lose it when the lambda is applied to it as part of multiple columns.
possible better answer: http://stackoverflow.com/a/50631514
favorite count: 0

http://stackoverflow.com/a/50658417
has comment: http://stackoverflow.com/comment/88326935
has comment: http://stackoverflow.com/comment/88327231
has comment: http://stackoverflow.com/comment/88328838
has comment: http://stackoverflow.com/comment/88348658
has comment: http://stackoverflow.com/comment/88327305
type: Answer
has comment: http://stackoverflow.com/comment/88328633
has comment: http://stackoverflow.com/comment/88327293
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88328501
has comment: http://stackoverflow.com/comment/88326899
has body: You can "transform" first column into eastern time on-fly - something like in below example #standardSQL WITH t AS ( SELECT TIMESTAMP '2018-05-07 22:40:00+00:00' AS ts ) SELECT ts, STRING(ts, '-04:00') timestamp_eastern FROM t I am dealing with ... stubbornness ... You can create view which will consists of all the logic you need in place so client will query that view instead of original table #standardSQL CREATE VIEW `project.dataset.your_view` AS SELECT ts, STRING(ts, '-04:00') timestamp_eastern FROM `project.dataset.your_table` I do think it odd that big query can't display a time in a timezone A timestamp represents an absolute point in time, independent of any time zone or convention such as Daylight Savings Time. Time zones are used when parsing timestamps or formatting timestamps for display. The timestamp value itself does not store a specific time zone. A string-formatted timestamp may include a time zone. When a time zone is not explicitly specified, the default time zone, UTC, is used. See more about Timestamp type
has comment: http://stackoverflow.com/comment/88326889
answers question: http://stackoverflow.com/q/50658061
upvote count: 2
has comment: http://stackoverflow.com/comment/88327509
has comment: http://stackoverflow.com/comment/88348862
accepted answer of: http://stackoverflow.com/q/50658061
type: AcceptedAnswer

http://stackoverflow.com/a/50669869
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50669722
has body: You can't get the probability of getting two ones with this code. What your code (mistakenly, due to the while True) does is count how many attempts are necessary in order to get any two equal outcomes from two independent dice. This probability can be determined with simple probability theory. For you to get any two equal outcomes, p = (1/36) * 6 = 1/6. This means that it is expected that, out of every 6 throws of two independent dice, it will once happen that you get the same outcome from each (e.g. two fours or two sixes) If you want to find that with an algorithm, you can run a Monte-Carlo-like simulation to see the how many throws are expected for this to happen in random state of worlds. Using your own algo (with some minor modifications) : import random def roll_dice(n, arange): total_count = 0 for i in range(arange): total_count +=1 d1, d2 = random.randint(1,n), random.randint(1,n) if d1 == d2: break return total_count z=[] s=1000 for i in range(s): z.append(roll_dice(6, 1000)) &gt;&gt;&gt; np.array(z).mean() 5.916666666666667 # s=100000 &gt;&gt;&gt; np.array(z).mean() 5.9943 You'll see that, as expected, the greater the number of simulations, the closer the mean is expected to get to 6. In addition, if you want to find the average for the case your describe (i.e. to find probability of two ones coming out), you can change this line (which accounts for any two equal numbers) if d1 == d2: for the following (which accounts for only the case where output is one): if d1 == d2 and (d1==1): Then, you can run and find that &gt;&gt;&gt; np.array(z).mean() 35.8479 which is close to 36, as expected. Notice that if you plot an histogram of your outcomes, results will not follow a normal distribution: This happens because you are analyzing the probability of X*Y being equal to one, and X*Y is the product of two gaussian random variables. Thus, the distribution of X*Y is not normal, but will follow the product distribution of these two variables (refer here)
accepted answer of: http://stackoverflow.com/q/50669722
type: Answer
has comment: http://stackoverflow.com/comment/88349764
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88350728
has comment: http://stackoverflow.com/comment/88350201
has comment: http://stackoverflow.com/comment/88349631

http://stackoverflow.com/comment/88113694
type: Comment
comment on: http://stackoverflow.com/a/50551327
score: 0
type: AnswerComment
has text: This seems to be a well known article about it: https://towardsdatascience.com/how-to-use-dataset-in-tensorflow-c758ef9e4428

http://stackoverflow.com/comment/102208967
score: 1
type: AnswerComment
has text: In fact, I am attempting there to calculate a "micro average" of 1-gram, 2-gram, and 3-gram language models. Each model is multiplied by its weight, and for each momend I include count of its n-grams in the numerator, and count of the corresponding (n-1)-grams (its prefix) into the denominator. Of course, you could use a simpler model (e.g 3-grams only), but in my experience, this approach works slightly better.
type: Comment
comment on: http://stackoverflow.com/a/50661395

http://stackoverflow.com/q/50675182
upvote count: 0
has comment: http://stackoverflow.com/comment/88360158
has body: I want to call a function inside of an other module but i i always get the same error statement "module 'mat_import' has no attribute 'matread'". After getting the "filename" and "button_pressed" value from the GUI I want to call matread inside of mat_import. The result should be that I have filename1 and button_pressed accessable inside of the main.py. The main.py: EDIT:To get "filename1" and "button_pressed" the function gui inside of GUI.py is called. This works and returns the filename to the main.py. After that i want to call matread inside of mat_import. The function matread should get the filename from the main.py and read the file. The outputs are the two variables "signals" and "signaldata". import mat_import as mi import GUI filename1, button_pressed = GUI.gui() if (button_pressed ==1): signals, signaldata = mi.matread The mat_import.py: import h5py import numpy as np import csv import os import main filename1 = "" global matread def matread(): #get signals and signaldata return signals, signaldata
type: Question
score: -1
has comment: http://stackoverflow.com/comment/88360671
has comment: http://stackoverflow.com/comment/88360072
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50675477
linked to: http://stackoverflow.com/q/8457669
favorite count: 0
tagged with: python-3.x
tagged with: tkinter
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88360230
has title: Calling a function in other module
has comment: http://stackoverflow.com/comment/88360651

http://stackoverflow.com/q/50552150
answer count: 1
has title: Client side unable to connect to socket
has answer: http://stackoverflow.com/a/50629770
favorite count: 0
type: UnansweredQuestion
tagged with: sockets
has comment: http://stackoverflow.com/comment/88119572
tagged with: python
has comment: http://stackoverflow.com/comment/88115300
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88119675
type: Question
has body: Please stay indulgent I am just starting with sockets and IT is not my field. I have a RaspberryPi connected to my desktop with an Ethernet cable. The RPi is used as a web server (apache2 and PHP installed). From the desktop I can access the default webpage. So far so good. I have created a Python script on the RPi that open a socket and send random number through it. import socket import random import time HOST = '' PORT = 8080 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Socket created' try: s.bind((HOST,PORT)) except socket.error: print 'Bind failed' rnd = random.random() print rnd s.listen(1) print 'Socket awaiting messages' (conn, addr) = s.accept() print 'Connected to ' + str(addr) while True: rnd = random.random() print rnd conn.send(str(rnd)) time.sleep(1) conn.close() If I execute this script it hangs until a client open a connection. So, from my desktop I open Firefox and type in the address: "192.168.137.2:8080". Nothing happens in the Firefox windows except that it seems that the browser is waiting that the "page" is done loading. Anyway from the console on my RPi I can see random numbers displayed. So I assume that in some way the connection has been correctly opened. Curiously enough when I change the time.sleep(1) to time.sleep(0.01) I can also see the text displayed in Firefox... But let's say that it's ok. Now, if I create a script in Python and execute it from my desktop I can see that both scripts work. import socket HOST = "192.168.137.2" PORT = 8080 socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.connect((HOST, PORT)) print "Connected" while True: dat = socket.recv(1024) print str(dat) print "Close" socket.close() So far so good... Not for long. Now I want to get the values send in the socket with JS from a webpage served by the RPi. So I created an html file on my RPi Test If I open this page with Firefox from my desktop I obtain this error (translated in English): Firefox cannot establish connection with the s…
has comment: http://stackoverflow.com/comment/88118732
tagged with: raspberry-pi
downvote count: 0
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/comment/88360972
has text: @MSeifert Ok. I reposted here: https://stackoverflow.com/questions/50675705/is-it-expected-for-numbas-efficient-square-euclidean-distance-code-to-be-slower.
score: 1
comment on: http://stackoverflow.com/q/50658884
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52283966
upvote count: 56
downvote count: 1
has body: I ran into a similar problem. It turned out the CSV I had downloaded had no permissions at all. The error message from pandas did not point this out, making it hard to debug. Check that your file have read permissions
accepted answer of: http://stackoverflow.com/q/50552404
answers question: http://stackoverflow.com/q/50552404
score: 55
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/107853672
type: Answer

http://stackoverflow.com/comment/88156106
type: QuestionComment
comment on: http://stackoverflow.com/q/50573241
has text: Did you maybe confuse the `library(RPostgreSQL)` call with `install.packages()`? I can't tell.
score: 0
type: Comment

http://stackoverflow.com/a/50590575
has comment: http://stackoverflow.com/comment/88201146
type: Answer
answers question: http://stackoverflow.com/q/50589989
has comment: http://stackoverflow.com/comment/88191675
score: 2
accepted answer of: http://stackoverflow.com/q/50589989
has comment: http://stackoverflow.com/comment/88194567
downvote count: 0
upvote count: 2
has body: Your URL patterns should be different for every view. otherwise, it will always call the view which is defined above either you call it by customer or information So your URL patterns should be urlpatterns = [ path('customer/', views.customer, name='customer'), path('information/', views.information, name='information'), ] UPDATE You don't have to create separate views for fetching objects from different tables to show in a webpage Create a single view and send as many objects in context dictionary. def table_content(request): ... # fetch objects here from model contacts = Contact.objects.all() tickets = Ticket.objects.all() # set objects to context dictionary context = {'contacts': contacts, 'tickets' : tickets} return render(request, 'uccx/home.html', context) Now in your template, you can easily loop over tickets and contacts {% for ticket in tickets %} &lt;tr&gt; &lt;td&gt; {{ ticket.id }} &lt;/td&gt; ... &lt;/tr&gt; {% endfor %} {% for contact in contacts %} &lt;tr&gt; &lt;td&gt; {{ contact.id }} &lt;/td&gt; ... &lt;/tr&gt; {% endfor %}
has comment: http://stackoverflow.com/comment/88194681
type: AcceptedAnswer

http://stackoverflow.com/a/50678082
has comment: http://stackoverflow.com/comment/88366324
score: 2
answers question: http://stackoverflow.com/q/50677892
has body: Why it should be identified as a normal function or type conversion function? It is just a function. Or as almost everything in python is an object, actually function is also a kind of object which implements __call__. Further, there isn't a type conversion function in fact. tuple acts as an constructor, it takes an iterable object and return a tuple object.
has comment: http://stackoverflow.com/comment/88366228
has comment: http://stackoverflow.com/comment/88366162
downvote count: 0
has comment: http://stackoverflow.com/comment/88366026
has comment: http://stackoverflow.com/comment/88365839
upvote count: 2
type: Answer

http://stackoverflow.com/a/50547693
score: 2
accepted answer of: http://stackoverflow.com/q/50547614
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50547614
type: Answer
upvote count: 2
has body: You can use pandas.cut. A few points to note: We use the fact ordering of dict.keys and dict.values is consistent. We provide bins and labels explicitly; note that labels must have one less item than bins. You may wish to add an extra bin for values above 1100. Here is a minimal example. df = pd.DataFrame({'col': [500, 123, 56, 12, 1000, 2, 456]}) df['mapped'] = pd.cut(df['col'], bins=[1]+list(replace_dict.values()), labels=list(replace_dict.keys())) print(df) col mapped 0 500 P 1 123 H 2 56 E 3 12 B 4 1000 R 5 2 A 6 456 O

http://stackoverflow.com/comment/88283014
has text: You have a bigger problem, you can't implement a lambda layer using numpy or other non-backend functions. Backpropagation through your layer won't work at all, you have to use keras.backend functions.
comment on: http://stackoverflow.com/q/50634986
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50682047
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50681654
has body: Using a plain dict, assuming only that the "title" records come first: &gt;&gt;&gt; lol = [[1.0, 'Software Developer', 1256], ... [1.0, 'Software Developer', 1329], ... [1.0, 'Software Developer', 1469], ... [1.0, 'Software Developer', 2086], ... [0.9230769230769231, 'United States', 1256], ... [0.9230769230769231, 'United States', 1329], ... [0.9230769230769231, 'United States', 1469], ... [0.9230769230769231, 'United States', 2086]] &gt;&gt;&gt; &gt;&gt;&gt; keys = [(gr + '_score', gr, 'ID') for gr in ('title', 'Location')] &gt;&gt;&gt; &gt;&gt;&gt; out = {} &gt;&gt;&gt; for L in lol: ... d = out.setdefault(L[-1], {}) ... d.update(zip(keys[bool(d)], L)) ... &gt;&gt;&gt; out # dict of dicts {1256: {'title_score': 1.0, 'title': 'Software Developer', 'ID': 1256, 'Location_score': 0.9230769230769231, 'Location': 'United States'}, 1329: {'title_score': 1.0, 'title': 'Software Developer', 'ID': 1329, 'Location_score': 0.9230769230769231, 'Location': 'United States'}, 1469: {'title_score': 1.0, 'title': 'Software Developer', 'ID': 1469, 'Location_score': 0.9230769230769231, 'Location': 'United States'}, 2086: {'title_score': 1.0, 'title': 'Software Developer', 'ID': 2086, 'Location_score': 0.9230769230769231, 'Location': 'United States'}} &gt;&gt;&gt; list(out.values()) # list of dicts [{'title_score': 1.0, 'title': 'Software Developer', 'ID': 1256, 'Location_score': 0.9230769230769231, 'Location': 'United States'}, {'title_score': 1.0, 'title': 'Software Developer', 'ID': 1329, 'Location_score': 0.9230769230769231, 'Location': 'United States'}, {'title_score': 1.0, 'title': 'Software Developer', 'ID': 1469, 'Location_score': 0.9230769230769231, 'Location': 'United States'}, {'title_score': 1.0, 'title': 'Software Developer', 'ID': 2086, 'Location_score': 0.9230769230769231, 'Location': 'United States'}] Or---if dict order matters (Python 3.6+ inofficial, Python 3.7+ official): &gt;&gt;&gt; out = {} &gt;&gt;&gt; for l in lol: ... d = out.setdefault(l[-1], {}) ... d.updat…

http://stackoverflow.com/comment/88199255
type: AnswerComment
score: 0
type: Comment
has text: I got a syntex error with "outfile = open(f'outfile{i}.txt', 'w')"
comment on: http://stackoverflow.com/a/50594985

http://stackoverflow.com/comment/88337478
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50660438
type: Comment
has text: Thank you. I ended up asking a follow up question. If you are intrested in helping the url is: Thanks you. Seems to work. https://stackoverflow.com/questions/50660221/string-manipulation-when-given-an-integer-parameter-python?noredirect=1#comment88330575_50660221

http://stackoverflow.com/a/61933454
has body: I also got a similar error File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\authentication.py", line 191, in get_auth_plugin "Authentication plugin '{0}' is not supported".format(plugin_name)) mysql.connector.errors.NotSupportedError: Authentication plugin 'caching_sha2_password' is not supported You have probably installed mysql-connector instead of mysql-connector-python. So you need to install it again for python3: pip3 install mysql-connector-python
downvote count: 0
type: Answer
score: 13
upvote count: 13
answers question: http://stackoverflow.com/q/50557234

http://stackoverflow.com/comment/88112985
type: AnswerComment
comment on: http://stackoverflow.com/a/50550385
score: 0
type: Comment
has text: Sure, although you need a better regex so that you don't match inside words. However, the OP is using Windows, so they may not have `grep`.

http://stackoverflow.com/a/50574746
accepted answer of: http://stackoverflow.com/q/50565322
score: 0
answers question: http://stackoverflow.com/q/50565322
type: Answer
has body: It appears that the difference is in the debug symbols. Perhaps one was built with a higher level of debug symbols than the other, or perhaps the smaller one was built with compressed debug info (a relatively new feature). One way to find out more would be to inspect the compiler and linker flags used during each build, or try to build it yourself.
has comment: http://stackoverflow.com/comment/88163379
type: AcceptedAnswer

wamp
tag name: wamp
tags question: http://stackoverflow.com/q/50552234
type: Tag

http://stackoverflow.com/a/50559589
type: Answer
has body: I'll suggest you try once with xavier's initialization of weights. It's something like W = tf.get_variable("W", shape=[x,y], initializer=tf.contrib.layers.xavier_initializer()) where you know x and y are shape of layers.
has comment: http://stackoverflow.com/comment/88154035
score: 0
answers question: http://stackoverflow.com/q/50558244
has comment: http://stackoverflow.com/comment/88144713
has comment: http://stackoverflow.com/comment/88142178

http://stackoverflow.com/a/50582667
accepted answer of: http://stackoverflow.com/q/50582361
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50582361
type: Answer
score: 1
upvote count: 1
has body: One way is to use Categorical Data. Note this will impact any method which attempts to add an item to the index which does not belong to the index when it was converted to Categorical. df.index = pd.Series(df.index).astype('category') # SUCCESS df.at['C', 1] = 'Bye' # FAIL df.at['D', 1] = 'Hello' You will find: KeyError: 'D' TypeError: cannot insert an item into a CategoricalIndex that is not already an existing category

http://stackoverflow.com/a/50643906
has body: The problem comes from the { and } that you are using. You should double them: payload = "{{\r\n \"name\": \"{0}\",\r\n \"id\":\"{1}\"}}".format(1,2)
answers question: http://stackoverflow.com/q/50643808
type: Answer
upvote count: 1
downvote count: 1
score: 0

http://stackoverflow.com/a/50644762
type: Answer
has body: It seems the problem is only the number of coefficients of the filter: 5 was too low. With b = signal.firwin(101, cutoff=1000, fs=sr, pass_zero=False) it works far better. Note: the audio will be nearly zero during the first 101 samples, so we should probably zero-pad the WAV file at the beginning and end, then apply the filter, then crop the file to remove the zero-padded parts.
answers question: http://stackoverflow.com/q/50644578
has comment: http://stackoverflow.com/comment/88300537
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/88300617
has comment: http://stackoverflow.com/comment/88300175
downvote count: 0
has comment: http://stackoverflow.com/comment/88312687

http://stackoverflow.com/comment/88141239
type: AnswerComment
score: 0
type: Comment
has text: This does not work (testing if 'o' is in 'notin' yields false). Please don't post answers with untested suggestions ...
comment on: http://stackoverflow.com/a/50565505

one-hot-encoding
tags question: http://stackoverflow.com/q/50634310
tags question: http://stackoverflow.com/q/50566293
type: Tag
tag name: one-hot-encoding
tags question: http://stackoverflow.com/q/50579544
tags question: http://stackoverflow.com/q/50626810

http://stackoverflow.com/comment/88285212
comment on: http://stackoverflow.com/q/50635938
type: QuestionComment
type: Comment
has text: Show us exact syntax that you use with `sftp`.
score: 0

http://stackoverflow.com/comment/88165168
type: Comment
score: 0
type: AnswerComment
has text: The output for `df_test= pd.DataFrame({'A':[25,67,24,76,23],'B':[2,54,22,75,19]})` `df_test'A','B'=min_max_scaler.transform(df_test'A','B')` is `A = [1.60,4.40,1.53,5.00,1.46] B = [-0.125,3.125,1.125,4.437,0.937]` How is the data scaling happening here? Because it's not using _**Xnorm = X-Xmin/Xmax-Xmin**_ formula for data scaling.
comment on: http://stackoverflow.com/a/50567308

http://stackoverflow.com/comment/88116262
comment on: http://stackoverflow.com/q/50551997
score: 0
has text: @Kaxil here is the o/p of which python3 /usr/local/bin/python3
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88404939
has text: I have another script to backup old logs in place. This requirement is due to a "quirk" (for lack of better word) to describe the necessity.
type: AnswerComment
comment on: http://stackoverflow.com/a/50697463
score: 0
type: Comment

http://stackoverflow.com/q/50600531
has title: Django filter on date difference between columns
score: 12
tagged with: django
tagged with: python
answer count: 1
linked to: http://stackoverflow.com/q/5245307
has comment: http://stackoverflow.com/comment/88211166
has body: As a Django beginner I struggle with a very basic problem: Filter a table based on the date difference of two columns. I could solve this in raw SQL, but I would really want to use basic Django functions. I have the following model: from django.db import models import datetime class Race(models.Model): __tablename__ = 'race' name = models.CharField(max_length=200) country = models.CharField(max_length=100, null=True) start = models.DateField() end = models.DateField() and I want to extract races that last e.g. more than 5 days. I can somehow get a timediff column: Race.objects.annotate(tdiff=F('end')-F('start')).first() set1 = Race.objects.annotate(tdiff=F('end')-F('start')).all() set1.first().tdiff Now, how do I filter on this column, what I tried is: min_diff = datetime.timedelta(5) set1.filter(tdiff__gte=5).first() set1.all().filter(tdiff__gte=min_diff) set1.filter(tdiff__gte=min_diff).first() but this all gives: TypeError: expected string or bytes-like object Then I considered using extra to get a where clause: set2 = Race.objects.annotate(tdiff=F('end')-F('start')) set2.first().tdiff set2.all().extra(where=['tdiff&gt;=5']) resulting in: ProgrammingError: column "tdiff" does not exist Questions in the same direction include this one and this one but none really give a solution where you filter on a new column (here tdiff). When finalizing this question I in the end did get the result that I wanted by: Race.objects.filter(end__gte=F("start")+5) print(Race.objects.filter(end__gte=F("start")+5).query) but I still very much would like to know how to utilize this temporary column tdiff. Thanks! Update after answer The accepted answer gives exactly what I wanted: from django.db.models import DurationField, F, ExpressionWrapper import datetime set4 = Race.objects.annotate( diff=ExpressionWrapper(F('end') - F('start'), output_field=DurationField())).filter( diff__gte=datetime.timedelta(5)) len(set4) # 364 len(Race.objects.filter(end__gte=F("start")+5)) # 364
linked to: http://stackoverflow.com/q/30222660
has answer: http://stackoverflow.com/a/50601209
upvote count: 12
type: AnsweredQuestion
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/12380448
accepted answer: http://stackoverflow.com/a/50601209
type: Question

http://stackoverflow.com/comment/117097862
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50574566
has text: I've encountered this exact same issue while using `scipy.optimize.shgo` in a 12 dimensional parameter space. I'm wondering if some sort of a solution has been established since. Perhaps I could locally edit scipy's source code accordingly.
score: 0

http://stackoverflow.com/a/50682863
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50682490
has body: I think you can use the following with merge_asof using direction parameter and drop_duplicates: df_before = pd.merge_asof(df_a, df_b, left_on='distance', right_on='mileage', direction='backward')\ .drop_duplicates(['mileage','Driver'], keep='first')'distance','measure' df_after = pd.merge_asof(df_a, df_b, left_on='distance', right_on='mileage', direction='forward')\ .drop_duplicates(['mileage', 'Driver'], keep='last')'distance','measure' df_middle = df_b.rename(columns={'Driver':'measure','mileage':'distance'}) pd.concat([df_before, df_middle, df_after]).sort_values('distance').drop_duplicates() Output: distance measure 0 17442.770 32.7927 0 17442.800 name1 1 17442.951 32.7927 2 17517.492 37.6485 1 17517.500 name2 3 17518.296 37.6485 4 17565.776 38.2871 2 17565.800 name3 5 17565.888 38.2871 6 17596.937 41.2033 3 17597.200 name4 7 17597.297 41.2033 8 17602.164 41.478 4 17602.500 name5 9 17602.839 41.6128 10 17618.164 42.4799 5 17618.400 name6 11 17618.711 42.6816
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50682490
score: 1

http://stackoverflow.com/a/50552904
has comment: http://stackoverflow.com/comment/88313159
accepted answer of: http://stackoverflow.com/q/50552486
has body: Use on_start event to initialize the label's text on program start. In the example below, a Clock.schedule_once event was added to show the initial value and then the change. Note In this example, the root widget is Label widget (root) and the root's dictionary (root.ids) is empty. If there is another widget with id: my_textinput, added as children of the root then root's dictionary will contain one id i.e. my_textinput. A print(self.root.ids) will demonstrate this. self - The keyword self references the “current widget instance” i.e. App. Kivy Language » ids When the kv file is processed, weakrefs to all the widgets tagged with ids are added to the root widget’s ids dictionary. Snippets from kivy.app import App initial_text = "init text" class MainApp(App): def on_start(self): self.root.text = initial_text if __name__ == '__main__': MainApp().run() Example main.py from kivy.app import App from kivy.clock import Clock initial_text = "init text" class MainApp(App): def on_start(self): Clock.schedule_once(self.initialize_widgets, 5) def initialize_widgets(self, dt): self.root.text = initial_text if __name__ == '__main__': MainApp().run() Output
upvote count: 2
answers question: http://stackoverflow.com/q/50552486
type: Answer
score: 2
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/a/59756038
answers question: http://stackoverflow.com/q/50608443
score: 0
has body: In pycharm you can just put -vv in the run configuration Additional Arguments field and this should solve the issue. Or at least, it worked on my machine...
type: Answer

http://stackoverflow.com/comment/88267818
score: 1
comment on: http://stackoverflow.com/q/50628902
type: Comment
type: QuestionComment
has text: Oh wait `_rand_sparse` looks like a function. So, to make it faster, it would make more sense to see its implementation.

http://stackoverflow.com/a/50561282
downvote count: 0
answers question: http://stackoverflow.com/q/50561040
type: Answer
upvote count: 3
has body: You can install pillow instead, which supports both Python 2 and 3 (check out the supported versions here conda install pillow pil is deprecated since 2009 and pillow is an actively developed fork of pil. So I'd suggest creating a new environment with pillow installed instead of pil to test.
score: 3

http://stackoverflow.com/q/50678754
type: UnansweredQuestion
tagged with: package
upvote count: 1
tagged with: python
score: 1
tagged with: setuptools
has answer: http://stackoverflow.com/a/50680113
type: Question
downvote count: 0
has body: I am trying to generate a simple Python library using the following command: &gt; python setup.py bdist_dumb So it will generate a tar.gz file with the contents specified in the setup.py script. Once it is generated, I try to install ot using pip install command, but I am getting an error referring to the missing file setup.py. I have specified to include such file in a MANIFEST.in file. But when I attempt to build the file, it is not included in my package. As a reference I am checking pyspark package, but I can't find the place where the setup.py file is specified to be included. Can anyone give me a hint for including this file in order to install the tar.gz library? Kind regards,
has title: Included setup.py in bdist generated library
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/88240466
score: 2
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50615262
has text: Do you _have to_ use Python?

http://stackoverflow.com/comment/88327988
type: AnswerComment
has text: @Shivan Singh yes for the short term , later i was thinking to use amazon service
type: Comment
comment on: http://stackoverflow.com/a/50658318
score: 0

http://stackoverflow.com/comment/88390389
comment on: http://stackoverflow.com/a/50667396
score: 1
has text: Yes its needed for sorting and indexing
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50669785
has answer: http://stackoverflow.com/a/50669897
tagged with: python
type: AnsweredQuestion
tagged with: list
type: Question
has body: I have task where I need to calculate all possible sums up to given number. For example: mass_list = [4, 1, 8] and max sum value is 10 mass = 10 Output need to be like this &gt;&gt;&gt;[1, 4, 5, 8, 9] 5(1+4) and 9(8 + 1) So far I came up with this quantity, mass = map(int,input().split()) mass_list = [] for x in range(1, 2): mass_list.extend(input().split(' ')) mass_list = list(map(int, mass_list)) count = len(mass_list) Would appreciate any help with solution
has comment: http://stackoverflow.com/comment/88349605
tagged with: combinations
accepted answer: http://stackoverflow.com/a/50669897
tagged with: sum
score: 0
has comment: http://stackoverflow.com/comment/88349559
answer count: 2
has title: posible sums without reps up to given number
linked to: http://stackoverflow.com/q/15701692
possible better answer: http://stackoverflow.com/a/50669900
has comment: http://stackoverflow.com/comment/88349640
has answer: http://stackoverflow.com/a/50669900
duplicate of: http://stackoverflow.com/q/15701692

http://stackoverflow.com/comment/88205810
type: AnswerComment
score: 0
has text: you are right - I thought the system would transform it automatically because of it's simple nature...
comment on: http://stackoverflow.com/a/50597612
type: Comment

http://stackoverflow.com/q/50590188
favorite count: 0
has comment: http://stackoverflow.com/comment/88190600
has comment: http://stackoverflow.com/comment/88190164
type: UnansweredQuestion
has body: def temp(): temparray = ['a','b'] temparray_2 = ['c','d','e'] for i in temparray: print('i:' + str(i)) for i in temparray_2: print('first: ' + str(i)) print('Second: ' + str(i)) print('final: ' + str(i)) Why does the above code the following output? The variable i seems to get overwritten by whatever that is last assigned in the inner loop. Does python not obey the scoping rule like Java or C? i:a first: c first: d first: e Second: e i:b first: c first: d first: e Second: e final: e
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/3611760
type: Question
has answer: http://stackoverflow.com/a/50590226
upvote count: 1
has title: scoping rule for nested-loop in python
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88190412

http://stackoverflow.com/q/50692358
has answer: http://stackoverflow.com/a/70526550
linked to: http://stackoverflow.com/q/48649230
tagged with: selenium-chromedriver
has answer: http://stackoverflow.com/a/79192248
has title: How to work with a specific version of ChromeDriver while Chrome Browser gets updated automatically through Python selenium
has body: I'm new comer of Selenium, and I can use selenium with Chromedriver to do basic auto-test now, the code works fine, but the problem is Chrome browser always update automatically at the backend, and code always fail to run after Chrome update. I know I need to download new chromedriver to solve this issue, but I wonder if there's any way to solve this issue without disabling chromebrowser update? tks. I'm using Windows 10 / Chrome Version 67 / Python 3.6.4 / Selenium 3.12.0
tagged with: selenium
has comment: http://stackoverflow.com/comment/88396793
tagged with: python
tagged with: google-chrome
downvote count: 1
upvote count: 16
has answer: http://stackoverflow.com/a/57602308
tagged with: selenium-webdriver
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/61887855
has comment: http://stackoverflow.com/comment/88394393
has answer: http://stackoverflow.com/a/61928952
has comment: http://stackoverflow.com/comment/88395078
linked to: http://stackoverflow.com/q/580924
type: Question
has answer: http://stackoverflow.com/a/50697221
has answer: http://stackoverflow.com/a/61218681
has comment: http://stackoverflow.com/comment/88397414
linked to: http://stackoverflow.com/q/29858752
has comment: http://stackoverflow.com/comment/108299722
score: 15
possible better answer: http://stackoverflow.com/a/63985206
accepted answer: http://stackoverflow.com/a/50697221
favorite count: 0
has answer: http://stackoverflow.com/a/70550827
has answer: http://stackoverflow.com/a/63985206
answer count: 9

http://stackoverflow.com/q/50674757
has comment: http://stackoverflow.com/comment/88359373
tagged with: performance
has answer: http://stackoverflow.com/a/50675128
has comment: http://stackoverflow.com/comment/88359323
has answer: http://stackoverflow.com/a/50674953
has comment: http://stackoverflow.com/comment/88527004
answer count: 3
has body: I have a list of strings coming from os.listdir() that looks like the following: ['foo', 'bar' 'backup_20180406' ...] out of those entries, I wanna get the ones that match the "backup_YYYYMMDD" pattern. The regex for that, with named groups, would be regex = r"BACKUP_(?P&lt;date&gt;\d+)" I am trying to create a list that contains the date only from the above (aka the .group('date')), but I cannot find a way to do it without parsing the strings twice.. res = [re.search(regex, x).group('date') for x in filter(r.match, os.listdir(folder))] I am sure that I am missing something really obvious and concise here, so is there a better way?
has title: Efficient regex with lists
has comment: http://stackoverflow.com/comment/88359448
favorite count: 0
possible better answer: http://stackoverflow.com/a/50674855
tagged with: python
tagged with: regex
accepted answer: http://stackoverflow.com/a/50674953
has answer: http://stackoverflow.com/a/50674855
type: AnsweredQuestion
upvote count: 2
score: 1
downvote count: 1
type: Question

http://stackoverflow.com/a/50595249
has body: Scala df.groupBy("ip").agg(sum("duration").as("sum_duration")).agg(max("sum_duration")).show() PySpark import pyspark.sql.functions as F df.groupBy("ip").agg(F.sum("duration").alias("sum_duration")).agg(F.max("sum_duration")).show()
score: 0
answers question: http://stackoverflow.com/q/50594636
type: Answer

http://stackoverflow.com/a/50684032
has comment: http://stackoverflow.com/comment/88378247
has comment: http://stackoverflow.com/comment/88378175
has comment: http://stackoverflow.com/comment/88378492
type: Answer
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/88378041
answers question: http://stackoverflow.com/q/50683833
has body: Yes, you can have comments in .NET regex. (examples copied from : https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference#miscellaneous_constructs) You can have inline comments with (?# .... ) : string regex = @"\bA(?#Matches words starting with A)\w+\b" or comment to the end of line # string regex = @"(?x)\bA\w+\b#Matches words starting with A" And you can always span your regex string on several lines, and use classic C# comments : string regex = @"\d{1,3}" + // 1 to 3 digits @"\w+" + // any word characters @"\d{10}"; // 10 digits See also Thomas Ayoub's answer for use of verbatim string @"" on several lines
score: 4

http://stackoverflow.com/comment/88374064
has text: yes always the same with no overlaps, i was thinking about editing table1 to add another column which would tell me what is it's age_range and then use that as key when merging.
comment on: http://stackoverflow.com/q/50681803
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88168750
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50578714
has text: @Goyo need to calculate local curvature i.e at each point.
score: 0

http://stackoverflow.com/comment/119825305
score: 0
comment on: http://stackoverflow.com/q/50689672
type: QuestionComment
type: Comment
has text: is op the + operation or is op a function

http://stackoverflow.com/q/50557727
score: 1
answer count: 2
has comment: http://stackoverflow.com/comment/88126321
possible better answer: http://stackoverflow.com/a/50558152
downvote count: 0
has answer: http://stackoverflow.com/a/50558152
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50557762
has body: I have a file, called input.py, which contains the following: #This is a file of categories Animals: cat, dog, frog, cheetah, tiger Items: desk, chair, bus, cups, pencil Technology: cellphone, TV, laptop, wifi-router #That's the end of the file and I want to filter out all blank lines and lines starting with # to produce output.py: Animals: cat, dog, frog, cheetah, tiger Items: desk, chair, bus, cups, pencil Technology: cellphone, TV, laptop, wifi-router My code is with open('input.py', 'r') as infile, open('output.py', 'w') as outfile: for line in infile: if line[0].strip('') == '#' or line == '\n': pass else: outfile.write(line) but it doesn't strip off the line starting with a tab. I've tried replacing .strip('') with .strip('\t') but I get the same output: Animals: cat, dog, frog, cheetah, tiger Items: desk, chair, bus, cups, pencil Technology: cellphone, TV, laptop, wifi-router #That's the end of the file Why is .strip('') or .strip('\t') not stripping off the tab?
has title: Trying to understand .strip
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88127189
tagged with: file
upvote count: 1
accepted answer: http://stackoverflow.com/a/50557762
type: Question
tagged with: strip

http://stackoverflow.com/comment/88357933
type: Comment
type: QuestionComment
has text: why not simply strip trailing whitespace using `q.strip()`?
comment on: http://stackoverflow.com/q/50674031
score: 0

http://stackoverflow.com/q/50613390
type: AnsweredQuestion
tagged with: outlook
upvote count: 5
has answer: http://stackoverflow.com/a/52997408
score: 5
tagged with: pandas
has title: Save win32com Outlook attachment directly to variable
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52997408
tagged with: python
has body: Fairly new to Python (using 3.6) and am wondering if it is possible to save an Outlook email attachment (csv file) directly to a pandas dataframe. I'm trying to avoid an interim step of saving to file, then using pandas.read_csv to bring the file contents into Python environment. I'm curious if something like the "open attachment" feature in Outlook can be used to open and assign to variable. What I have so far (which works)... import pandas import win32com.client as win32 outlook = win32.Dispatch('outlook.application') mapi=outlook.GetNamespace["MAPI"] datafldr=mapi.Folders['Main'].Folders['Inbox'].Folders['Data'] messages=datafldr.Items num_msgs=messages.count curr_email=messages[num_msgs-1] attachments=curr_email.Attachments curr_att=attachments.Item(1) Is it possible to take the "curr_att" win32 object(?) directly to a pandas dataframe? Or do I have to continue with... curr_att.SaveAsFile('enterpathhere\datafile.csv') mydata=pandas.read_csv('enterpathhere\datafile.csv') Many thanks!
type: Question

http://stackoverflow.com/q/50557099
answer count: 2
downvote count: 2
favorite count: 0
score: 0
has answer: http://stackoverflow.com/a/50558085
tagged with: python
type: UnansweredQuestion
tagged with: pyparsing
type: Question
has answer: http://stackoverflow.com/a/50557275
has body: I'm trying to parse strings like this: aa bb first item ee ff I need separate prefix 'aa bb', keyword:'first item' and suffix 'ee ff' Prefix and suffix can be several words or even doesn't exist. Keyword is list of predefined values. this is what I tried but it didn't work: a = ZeroOrMore(Word(alphas)('prefix')) &amp; oneOf(['first item', 'second item'])('word') &amp; ZeroOrMore(Word(alphas)('suffix'))
upvote count: 2
has title: Find prefix and suffix of keyword using pyparsing

http://stackoverflow.com/q/50617502
has answer: http://stackoverflow.com/a/50618198
has answer: http://stackoverflow.com/a/50633784
downvote count: 1
has answer: http://stackoverflow.com/a/50618112
tagged with: uniform-distribution
type: UnansweredQuestion
tagged with: pymc
has title: Why standard deviation of uniform distribution calculated with pymc.Uniform("stds",0,100) is different each time?
favorite count: 0
has body: Why standard deviation of uniform distribution calculated with pymc.Uniform("stds",0,100) is different each time? I think standard deviation is calculated with this formula '(100-0)/2√3', so I think there is only one value with one uniform distribution. What is pymc.Uniform doing? If you know the information about pymc.Uniform with "std", please teach me. thanks!
type: Question
tagged with: python
score: 0
answer count: 3
upvote count: 1

http://stackoverflow.com/comment/88329775
score: 2
comment on: http://stackoverflow.com/q/50659796
type: Comment
type: QuestionComment
has text: If your input are integers, why are you suing text mining feature selection?

http://stackoverflow.com/comment/88344977
has text: @KlausD. Yeah, that worked. thanks.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50663890
score: 1

http://stackoverflow.com/a/50570810
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: There are two reasons you see so many hellos printed: Python doesn't have a special bytecode for every possible Python statement. Instead statements will use a combination of bytecodes. The Python interpreter imports a series of Python modules just to start running. You can run a regular Python interpreter with the -v switch to see what is imported each time. Each module consists of multiple statements, so there is quite some bytecode to go through before you get to the little script you are running. If I put those 3 lines into test.py and use my unmodified Python 2.7 binary to run that, with the -v switch, I see: $ python2.7 -v test.py # installing zipimport hook import zipimport # builtin # installed zipimport hook # /..../lib/python2.7/site.pyc matches /..../lib/python2.7/site.py import site # precompiled from /..../lib/python2.7/site.pyc # /..../lib/python2.7/os.pyc matches /..../lib/python2.7/os.py import os # precompiled from /..../lib/python2.7/os.pyc import errno # builtin import posix # builtin # /..../lib/python2.7/posixpath.pyc matches /..../lib/python2.7/posixpath.py import posixpath # precompiled from /..../lib/python2.7/posixpath.pyc # /..../lib/python2.7/stat.pyc matches /..../lib/python2.7/stat.py import stat # precompiled from /..../lib/python2.7/stat.pyc # /..../lib/python2.7/genericpath.pyc matches /..../lib/python2.7/genericpath.py import genericpath # precompiled from /..../lib/python2.7/genericpath.pyc # /..../lib/python2.7/warnings.pyc matches /..../lib/python2.7/warnings.py import warnings # precompiled from /..../lib/python2.7/warnings.pyc # /..../lib/python2.7/linecache.pyc matches /..../lib/python2.7/linecache.py import linecache # precompiled from /..../lib/python2.7/linecache.pyc # /..../lib/python2.7/types.pyc matches /..../lib/python2.7/types.py import types # precompiled from /..../lib/python2.7/types.pyc # /..../lib/python2.7/UserDict.pyc matches /..../lib/python2.7/UserDict.py import UserDict # precompiled from /..../lib/python2.7/U…
accepted answer of: http://stackoverflow.com/q/50570632
answers question: http://stackoverflow.com/q/50570632
type: AcceptedAnswer

http://stackoverflow.com/comment/88424027
score: 0
type: AnswerComment
has text: Thank you. I owe you my life
type: Comment
comment on: http://stackoverflow.com/a/50706094

http://stackoverflow.com/comment/90490102
has text: This activates the environment, yes, but the conda.exe will not not be there (unless you already added C:\ProgramData\Anaconda3\Scripts to you global PATH which is not the recommended option when installing Anaconda
type: AnswerComment
comment on: http://stackoverflow.com/a/51736838
score: 0
type: Comment

http://stackoverflow.com/a/50734064
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50693871
answers question: http://stackoverflow.com/q/50693871
type: AcceptedAnswer
downvote count: 0
has body: Thank you all for your help. After lots of searching on Stackoverflow coupled with testing on my local machine I was able to drill it down to this. The object (a['data']) that was being passed in had some values that were not utf-8 decodable. It was in the form of b'xxxsknoen' I ended up deleting the b and the quotes in the front and end and then converting it to an str. var = base64.b64decode(str(a['data'])[2:-1]).decode('utf-8') a.update(json.loads(var))

http://stackoverflow.com/a/50584721
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/88179149
has body: You have defined N_off and N_on inside if statements and only one or the other can be true and execute, Try this: last_state={} last_device={} last_substate={} with open("TESTFILE.csv") as f: reader = csv.reader(f, delimiter=',') for row in reader: device = row[0] state = row[1] model = row[2] substate=row[3] #time = row[4] if device in row: if substate == 'Not joined' and model !='electric_meter': N_off = None N_on = None if state == "Offline": N_off = [device] # print N_off, reader.line_num if state == 'Online': N_on = [device] if N_off == N_on: print device, reader.line_num However I don't see the logic in this: if state == "Offline": N_off = [device] # print N_off, reader.line_num if state == 'Online': N_on = [device] if N_off == N_on: print device, reader.line_num because this: if N_off == N_on: print device, reader.line_num Will never be executed since state cannot be both on and off at the same time.
answers question: http://stackoverflow.com/q/50584191

http://stackoverflow.com/a/50664466
answers question: http://stackoverflow.com/q/50664416
type: Answer
upvote count: 3
score: 3
has body: O(n)? Maybe if you had infinite memory with every possible subarray in the real/imaginary number system stored for efficient accessing, then sure, you can have any complexity algorithm you like. ...But realistically speaking, you're looking at something along the lines of O(n^3), regardless of how efficient you do it. &gt;&gt;&gt; [lst[i:j + 1] for i in range(len(lst)) for j in range(i + 1, len(lst))] [[1, 2], [1, 2, 3], [1, 2, 3, 4], [2, 3], [2, 3, 4], [3, 4]] The one liner hides the two loops and the slicing operation, all of which add layers of complexity. However, it is as efficient and as fast as the underlying algorithm allows it to be.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50664416

http://stackoverflow.com/comment/88139719
type: Comment
has text: The MVCE you posted is not the one that generated the error. Your trace shows that you ran `np.apply_along_axis(d, axis=-1, arr=a)`, not with `axis=0`.
score: 0
comment on: http://stackoverflow.com/q/50563615
type: QuestionComment

http://stackoverflow.com/q/50553698
tagged with: plot
upvote count: 16
has answer: http://stackoverflow.com/a/50553708
tagged with: categories
has answer: http://stackoverflow.com/a/50553706
has title: Pandas plot bar order categories
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50553706
downvote count: 0
has answer: http://stackoverflow.com/a/50554022
has body: I have a dataset with a categorical variable that contains three unique values, "low", "medium" and "high": df.CatVar.value_counts() Out[93]: Medium 35832 Low 25311 High 12527 Name: CatVar, dtype: int64 I am trying to plot the number of unique values as a bar-plot. However, the following code gives me the bars in the order ["Medium", "Low", "High"] df.CatVar.value_counts().plot(kind="bar") How do I change the order of the bars in the plot?
score: 16
favorite count: 0
accepted answer: http://stackoverflow.com/a/50553708
type: Question
tagged with: pandas
tagged with: python
answer count: 3

http://stackoverflow.com/q/50561318
answer count: 1
downvote count: 0
has title: How to bind c++ member function to python just using only c/python api?
has comment: http://stackoverflow.com/comment/88133447
favorite count: 0
has comment: http://stackoverflow.com/comment/88133273
has comment: http://stackoverflow.com/comment/88133384
type: UnansweredQuestion
tagged with: python
tagged with: c++
has comment: http://stackoverflow.com/comment/88133796
has comment: http://stackoverflow.com/comment/88133374
score: 1
has body: i use c/python api to bind my class to python. I make new module and bind just class type successfully. c/python api have PyMethodDef structure to bind function to python class. PyMethodDef pyMethodDef = { "PyFunction", PYFunction, METH_KEYWORDS | METH_VARARGS , "PyFunction" }; PyObject *pFunc = PyCFunction_New(&amp;pyMethodDef, NULL); PyObject *pMethod = PyInstanceMethod_New(pFunc); int result = PyDict_SetItemString(pPyClassDict, pyMethodDef.ml_name, pMethod); But, there is a terrible rule that bind function must have PyObject* return type and it must get 2 PyObject* arguments. PyObject* PYFunction(PyObject* self, PyObject* args) { char *s = "Hello from C!"; return Py_BuildValue("s", s); } So i can not bind my class and member function like this. class Position { int x; int y; public: Position() {x = 0; y = 0} ~Potition() { }+ void SetZero() { x = 0, y = 0 } } It is impossible to change all member function's signature like below. Because actually i have many class to bind. PyObject* method(PyObject*, PyObject*) Well the boost python will be a solution but it is too big to use. I only need python binder and it's too difficult to use. Is there have any way to bind c++ member function(method) to python just only use pure c / python api? (PyMethodDef structure's second member is PyCFunction type...)
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88133417
has answer: http://stackoverflow.com/a/50566007

http://stackoverflow.com/a/50595382
score: 1
type: Answer
has body: Try appending it to the new list i created l, then do ''.join(l) to output it in one line : l = [] ColumnCount_int = 3 while ColumnCount_int &gt; 0 : ColumnCount_text = str('&lt;colspec colnum="'+ str(ColumnCount_int) +'"' ' ' 'colname="'+ str(ColumnCount_int) + '"&gt;') Blank_text = ColumnCount_text ColumnCount_int = ColumnCount_int - 1 l.append(Blank_text) print(''.join(l)) Output: &lt;colspec colnum="3" colname="3"&gt;&lt;colspec colnum="2" colname="2"&gt;&lt;colspec colnum="1" colname="1"&gt; Shorter Way Also try this: l = [] ColumnCount_int = 3 while ColumnCount_int &gt; 0 : l.append(str('&lt;colspec colnum="'+str(ColumnCount_int)+'"'' ''colname="'+str(ColumnCount_int)+'"&gt;')) ColumnCount_int-=1 print(''.join(l)) Output: &lt;colspec colnum="3" colname="3"&gt;&lt;colspec colnum="2" colname="2"&gt;&lt;colspec colnum="1" colname="1"&gt;
upvote count: 1
answers question: http://stackoverflow.com/q/50595357
downvote count: 0

http://stackoverflow.com/q/50631426
has comment: http://stackoverflow.com/comment/88273564
accepted answer: http://stackoverflow.com/a/50631635
tagged with: python
has body: I assumed standard library type hinting support was all based on reading the plain source like inspect does for some things, but I looked at typing.py in the standard library and it seems the compiler does store type hint info on the object itself. So, if I do: def myfunc(a: int, b:int): -&gt; str return "{a} + {b} = {a+b}" and then compile that to a .pyc file, does the type information stick around such that someone who I've given the .pyc file can use things like typing.get_type_hints() to access it? (With the assumption that I have a valid reason to distribute just the .pyc.)
favorite count: 0
tagged with: python-3.x
downvote count: 2
has comment: http://stackoverflow.com/comment/88273282
possible better answer: http://stackoverflow.com/a/50631717
type: Question
has answer: http://stackoverflow.com/a/50631717
has title: Do .pyc files contain type hinting information?
score: 2
type: AnsweredQuestion
tagged with: type-hinting
has answer: http://stackoverflow.com/a/50631635
upvote count: 4
tagged with: pyc
answer count: 2
has comment: http://stackoverflow.com/comment/88273385
has comment: http://stackoverflow.com/comment/88273753

http://stackoverflow.com/comment/88284345
type: Comment
comment on: http://stackoverflow.com/q/50636901
type: QuestionComment
score: 0
has text: show the content of your `urls.py` and `views.py`

http://stackoverflow.com/comment/90943881
type: Comment
comment on: http://stackoverflow.com/a/50590288
score: 0
type: AnswerComment
has text: I ended up ditching Ansible and going with a strictly boto3 solution.

http://stackoverflow.com/comment/88156785
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50551837
type: AnswerComment
has text: Ah, very nice, I am glad

http://stackoverflow.com/a/50622336
score: 5
type: AcceptedAnswer
type: Answer
upvote count: 5
has comment: http://stackoverflow.com/comment/88255522
answers question: http://stackoverflow.com/q/50621829
has comment: http://stackoverflow.com/comment/88254487
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50621829
has body: The default settings are stored in django.conf.global_settings. So in your settings.py file you can write: # settings.py import django.conf.global_settings DATE_INPUT_FORMATS = [ *django.conf.global_settings.DATE_INPUT_FORMATS, 'Your-extra-format' ] Note that aterisk (*) in the list to "unpack" the default list in the new list.

http://stackoverflow.com/a/50648095
upvote count: 3
downvote count: 1
type: Answer
has body: I figured it out. You can just modify the test to expect an error as follows: Compare different numbers Run Keyword And Expect Error * I compare ${num_a} with ${num_b} Alternatively to look for a specific error (rather than wildcard): Compare different numbers Run Keyword And Expect Error ValueError: Numbers are not the same. I compare ${num_a} with ${num_b} Note the double space between the command, error and keyword.
accepted answer of: http://stackoverflow.com/q/50647581
answers question: http://stackoverflow.com/q/50647581
score: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/88124868
type: QuestionComment
has text: Can you explain what you are asking for here: `how I should index the numeric value properly if I wish to use the number for future calculations and comparisons`?
score: 0
comment on: http://stackoverflow.com/q/50556890
type: Comment

http://stackoverflow.com/comment/88273754
has text: Indexing with a slice also preserves a dimension, `x[:, 1:2]`. `x[:,1, None]` also works. `None` or `np.newaxis` is a good idiomatic way of adding a singleton dimension where needed.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50617146
type: Comment

http://stackoverflow.com/a/50577932
has comment: http://stackoverflow.com/comment/88165640
has comment: http://stackoverflow.com/comment/88165064
type: Answer
has comment: http://stackoverflow.com/comment/88165928
has comment: http://stackoverflow.com/comment/88165702
has body: depending on how large the data is and on how your nodejs backend is constructed. You can always send post-requests to your webserver with your data. r = requests.post('http://httpbin.org/post', data = {'key':'value'}) For more information see: http://docs.python-requests.org/en/master/user/quickstart/ Another way would be saveing your data into a database and read it from your webapp.
has comment: http://stackoverflow.com/comment/88166579
has comment: http://stackoverflow.com/comment/88165901
score: 0
accepted answer of: http://stackoverflow.com/q/50577454
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50577454
has comment: http://stackoverflow.com/comment/88165841

http://stackoverflow.com/comment/88272347
score: 0
has text: Yes, I am talking about protobuf python's wire format (I am in protobuf python team). Looks like the problem is more specific with language/cloud-client/v1beta2/snippets.py
type: AnswerComment
comment on: http://stackoverflow.com/a/50614485
type: Comment

http://stackoverflow.com/a/74690180
type: Answer
has body: Behavior on partial periods. date_range returns empty index. period_range returns index with len 1 when specifying start and end that do not cover a whole period. (also, the timezone information is lost for periods of months). date_range: dates = pd.core.indexes.datetimes.date_range("2022-12-01 0:00:00+00:00", "2022-12-05 14:26:00+00:00", inclusive="both", freq="1M") dates DatetimeIndex([], dtype='datetime64[ns, UTC]', freq='M') period_range: periods = pd.core.indexes.period.period_range("2022-12-01 0:00:00+00:00", "2022-12-05 14:26:00+00:00", freq="1M") periods PeriodIndex(['2022-12'], dtype='period[M]')
answers question: http://stackoverflow.com/q/50634824
score: 0

http://stackoverflow.com/comment/90014023
has text: It may be that git-bash is not supported yet based on https://github.com/pypa/pipenv/issues/970
type: AnswerComment
comment on: http://stackoverflow.com/a/51002659
score: 0
type: Comment

http://stackoverflow.com/q/50551399
answer count: 2
possible better answer: http://stackoverflow.com/a/50555461
type: AnsweredQuestion
upvote count: 0
has body: form.py class SignUpForm(forms.Form): name = forms.CharField(max_length=50, required=True) email = forms.EmailField(max_length=100, required=True) password = forms.CharField(max_length=20, required=True) class SignInForm(forms.Form): email = forms.EmailField() password = forms.CharField(max_length=20, min_length=8) view.py def Sign_Up(request.POST): if request.method == 'POST': form = SignUpForm(request) if form.is_valid(): cd = form.cleaned_data name = cd['name'] email = cd['email'] password = cd['password'] us = User..objects.get(email__exact=email, password__exact=password) return HttpResponseRedirect('/') else: form = SignUpForm() return render(request,'User Login Page.html', {'form':form}) def Sign_In(request.POST): if request.method =='POST' : form = SignInForm(request) if form.is_valid(): F = form.cleaned_data Eemail = F['email'] Epassword = F['password'] try: user = User.objects.filter(email=Eemail) except User.DoesNotExist: form = SignInForm() return render(request, "Admin Login Page.html", {'form': form}) if User.password == Epassword: return HttpResponseRedirect("/") form = SignInForm() return render(request,"Admin Login Page.html",{'form':form}) I want to make a sign in &amp; up for my site with Django but it doesn't work! When I click on the submit button my sign up directly goes to the HttpRsponseDirect address even with empty parameters
has answer: http://stackoverflow.com/a/50555461
tagged with: web
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/html
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/50551893
has title: I want to make sign in & up for my site with Django but it doesn't work
score: -1
downvote count: 1
has answer: http://stackoverflow.com/a/50551893

http://stackoverflow.com/comment/88208521
type: QuestionComment
comment on: http://stackoverflow.com/q/50598220
score: 0
has text: by using pipenv command of course !
type: Comment

http://stackoverflow.com/q/50689422
tagged with: http://stackoverflow.com/tag/json
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/88388787
type: Question
has answer: http://stackoverflow.com/a/50689491
score: 0
tagged with: pandas
answer count: 1
has title: parsing json like data without creating a json file python
accepted answer: http://stackoverflow.com/a/50689491
tagged with: python
has body: I am scraping some data and I was looking to automate some things. At the moment my scraper creates JSON files (one for each page I scrape) which I clean and put together into a CSV which I then analyze. I am trying to clean the JSON like data without saving it to a JSON file. At the moment I am writing a JSON file and then using pd.read_json and then cleaning and transforming it. What I was hoping to do was to call the scrapers and have them return the contents of the JSON file rather than writing a JSON file and then loading the JSON file. current code is something like this: scrape... with open('%s-%s-df1.json'%(arg1, arg2), 'w) as fp: json.dump(df1, fp, indent = 4) what I hope to achieve is to directly manipulate df1 without having to do the above. The reason I am having to do the above at the moment is because pd.read_json transforms the JSON file into a pandas data frame. How can I transform JSON like data without exporting to a json file and then importing using pd.read_json?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88388618

http://stackoverflow.com/q/50599515
score: 2
tagged with: feed-forward
has comment: http://stackoverflow.com/comment/88209175
has body: I'm doing a regression problem and I have 18 features. Whenever I try to predict the values, it always gives me negative values. Can anybody help? I define my NN to be this: features = Input(shape=(18,)) LAYER1 X = Dense(1024)(features) X = BatchNormalization()(X) X = Dropout(0.1)(X) X = LeakyReLU(alpha=0.2)(X) LAYER2 X = Dense(1024)(X) X = BatchNormalization()(X) X = Dropout(0.1)(X) X = LeakyReLU(alpha=0.2)(X) LAYER3 X = Dense(1024)(X) X = BatchNormalization()(X) X = Dropout(0.1)(X) X = LeakyReLU(alpha=0.2)(X) LAYER4 X = Dense(512)(X) X = BatchNormalization()(X) X = Dropout(0.1)(X) X = LeakyReLU(alpha=0.2)(X) LAYER5 X = Dense(256)(X) X = BatchNormalization()(X) X = Dropout(0.1)(X) X = LeakyReLU(alpha=0.2)(X) LAYER6 X = Dense(128)(X) X = BatchNormalization()(X) X = Dropout(0.1)(X) X = LeakyReLU(alpha=0.2)(X) output Corr = Dense(1)(X) model = Model(inputs = features, outputs=Corr) model.compile(optimizer = 'Sgd', loss=huber_loss, metrics=['mse', 'mae']) model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=20, batch_size=512, verbose=1) where Huber loss is: def huber_loss(y_true, y_pred): return tf.losses.huber_loss(y_true,y_pred)
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/88212658
has comment: http://stackoverflow.com/comment/88208845
downvote count: 0
tagged with: neural-network
tagged with: keras
has title: I always predict negative values with my model
favorite count: 0
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88212961
has comment: http://stackoverflow.com/comment/88208928

http://stackoverflow.com/a/61968385
answers question: http://stackoverflow.com/q/50643166
type: Answer
has body: Try pip uninstall pyOpenSSL cryptography or sudo pip install pyOpenSSL cryptography
score: 0

http://stackoverflow.com/q/50561040
has comment: http://stackoverflow.com/comment/88132654
answer count: 1
has comment: http://stackoverflow.com/comment/88132567
has title: UnsatisfiableError: The following specifications were found to be in conflict: - pil -> python 2.6* - python 3.6*
favorite count: 0
has comment: http://stackoverflow.com/comment/88132527
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/88132858
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/88132706
tagged with: anaconda
has body: I'm trying to install PIL using anaconda, while I'm inside my conda environment. Inside the conda environment: conda install pil but I get the following error UnsatisfiableError: The following specifications were found to be in conflict: - pil -&gt; python 2.6* - python 3.6* I have python 2.7 and 3.6 both installed inside my conda environment. PIL is not currently installed as I get an importError when I try to import it in python. I have tried the following: conda uninstall pil and conda remove pil For both I get PackageNotFoundError: Package(s) is missing from the environment: pil What do I do?
has comment: http://stackoverflow.com/comment/88132681
has answer: http://stackoverflow.com/a/50561282
type: Question
upvote count: 4
tagged with: python-import

http://stackoverflow.com/comment/88242508
has text: Yes, the biggest consumer would be the "random stuff," and with all those extra processes (pipeline!). The next consumer would be the I/O, and finally I suspect the choice of shell. So: try with some dirt simple randomness (important: how good does that need to be?). And use a different tool. Given what you desire I'd say that a scripting language should do, but of course that C/C++ should be better. Also: can you precompute a quasi-random sequence? Does this need to run repeatedly, often ...?
comment on: http://stackoverflow.com/q/50613848
score: 1
type: QuestionComment
type: Comment

byte
tags question: http://stackoverflow.com/q/50549831
tags question: http://stackoverflow.com/q/50666417
tag name: byte
tags question: http://stackoverflow.com/q/50546268
tags question: http://stackoverflow.com/q/50633765
type: Tag

http://stackoverflow.com/q/50689763
has body: How can I take a string and create a data frame. Let's say the string I have is the following. ss = "This is a string" If I do the following, it produced an error. pd.DataFrame(ss) Traceback (most recent call last): File "&lt;ipython-input-84-4694a8452254&gt;", line 1, in &lt;module&gt; pd.DataFrame(ss) File "/Users/abrahammathew/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py", line 404, in __init__ raise ValueError('DataFrame constructor not properly called!') ValueError: DataFrame constructor not properly called! However, if I try to create a series, it works. pd.Series(ss) Out[85]: 0 This is a string dtype: object
has answer: http://stackoverflow.com/a/50689831
type: Question
has comment: http://stackoverflow.com/comment/88389310
has comment: http://stackoverflow.com/comment/88389289
has answer: http://stackoverflow.com/a/50689834
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has title: Create a DataFrame from a String
has comment: http://stackoverflow.com/comment/88389328
tagged with: python
score: 2
upvote count: 2

http://stackoverflow.com/q/50588477
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
has comment: http://stackoverflow.com/comment/88186774
has body: Here is my problem; I have a main script that imports my own package which contains a function that returns the current directory of my the script which is running. There is no problem when the main script calls this function because he is the one which calls the function and the os.getcwd() works well. However, i've another script which is called by this main script via exec() and when i try to get the directory via the function of my package, it gives me the directory of my main script (because it just adds the code of my other script to my main script). So I finally tried to use subprocess but i've the same problem. (Maybe because it does not import a second time my package, i don't know). I've tried others solutions like the use of filename = inspect.getframeinfo(inspect.currentframe()).filename path = os.path.dirname(os.path.abspath(filename)) but it gives me the package's path and not the script's path Does anyone have a solution to solve my problem ? I've attached a diagram to illustrate my problem. Thanks in advance My Diagram
linked to: http://stackoverflow.com/q/6566642
type: Question
duplicate of: http://stackoverflow.com/q/6566642
downvote count: 0
favorite count: 0
tagged with: python-3.x
has title: How can I get the directory from a script called by another script in python via a function imported

http://stackoverflow.com/q/50691220
accepted answer: http://stackoverflow.com/a/50691459
has body: This question is about SPACE not time complexity. Moreover, it is not about how to solve the question as I was able to do it. I am trying to figure out the space complexity of the algorithm in my solution. I found the question on Leetcode. Assumptions and question description can be found there. I understand the time complexity as explained in this StackOverflow post but the post doesn't talk of space complexity. I have tried explaining it after the end of my code. # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def buildTree(self, preorder, inorder): """ :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode """ preorder.reverse() return self.buildTreeHelper(preorder, inorder) def buildTreeHelper(self, preorder, inorder): if not preorder or not inorder: return None rootValue = preorder.pop() root = TreeNode(rootValue) inorderRootIndex = inorder.index(rootValue) root.left = self.buildTreeHelper(preorder, inorder[:inorderRootIndex]) root.right = self.buildTreeHelper(preorder, inorder[inorderRootIndex+1:]) return root Because I am sending slices of the list in the recursive function, I am using more space. If we don’t consider clearing up the space, then we need O(n^2) space for the list slices. We could suppose that we are clearing up this space as we proceed but for each step we pass 2n length arrays [pre &amp; inorder] for all of n steps. What is the space complexity if we consider that we clear up the space? To add to this, the tree could be a linked list in the worst case and so the space taken up in the call stack because of the recursion would be O(n) as well. Does it make sense to say that the space complexity is then O(n^3) because of each addition to the call stack or have I double counted creating an extra power?
linked to: http://stackoverflow.com/q/20922969
tagged with: binary-tree
tagged with: preorder
has answer: http://stackoverflow.com/a/50691459
tagged with: python
tagged with: big-o
type: AnsweredQuestion
type: Question
tagged with: inorder
score: 0
has title: Space complexity of construction of a binary tree from inorder and preorder traversals
answer count: 1

http://stackoverflow.com/comment/88170239
type: QuestionComment
score: 2
has text: Dictionaries are _not_ ordered
type: Comment
comment on: http://stackoverflow.com/q/50580544

http://stackoverflow.com/comment/88331588
comment on: http://stackoverflow.com/a/50660773
score: 0
type: AnswerComment
has text: This is how "one simply verify that some variable is not False, regardless of whether the variable is an array, list, integer, or whatever".
type: Comment

http://stackoverflow.com/q/50682520
favorite count: 0
has answer: http://stackoverflow.com/a/50707636
has title: Load Json from Complicated Csv/DataFrame, retain dtypes for MongoDB
accepted answer: http://stackoverflow.com/a/50707636
has comment: http://stackoverflow.com/comment/88418271
has comment: http://stackoverflow.com/comment/88423183
tagged with: python
type: AnsweredQuestion
score: 2
downvote count: 0
tagged with: http://stackoverflow.com/tag/json
type: Question
tagged with: mongodb
has comment: http://stackoverflow.com/comment/88381425
upvote count: 2
has body: I am trying to build at json tree for a queryable MongoDB from some disparate csv/excel files. The data is often incomplete and linked by a subject id. Example data below: subid,firstvisit,name,contact,dob,gender,visitdate1,age,visitcategory,samplenumber,label_on_sample,completed_by 1,12/31/11,Bob,,12/31/00,Male,,,,,, 1,,,,,,12/31/15,17,Baseline Visit,,, 1,,,,,,12/31/16,18,Follow Up Visit,,, 1,,,,,,12/31/17,18,Follow Up Visit,,, 1,,,,12/31/00,Male,,17,,XXX123,1,Sally 2,1/1/12,,,1/1/01,Female,,,,,, 2,,,,,,1/1/11,10,Baseline Visit,,, 2,,,,,,1/1/12,11,Follow Up Visit,,, 2,,,,,,1/1/13,12,Follow Up Visit,,, 2,,,,,,1/1/14,13,Follow Up Visit,,, 2,,,,,,1/1/15,14,Follow Up Visit,,, 2,,,,1/1/01,Female,,15,,YYY456,2, 2,,,,1/1/01,Female,,15,,ZZZ789,2,Sally' I'd like the output to look something like this: [ { "subject_id": "1", "name": "Bob", "dob": "12/31/00", "gender": "Male", "visits": { "12/31/15": { "age": "17", "visit_category": "Baseline Visit" }, "12/31/16": { "age": "18", "visit_category": "Follow Up Visit" }, "12/31/17": { "age": "18", "visit_category": "Follow Up Visit" } }, "samples": { "XXX123": { "completed_by": "Sally", "label_on_sample": "1" } } }, { "subject_id": "2", "name": null, "dob": "1/1/01", "gender": "Female", "visits": { "1/1/11": { "age": "10", "visit_category": "Baseline Visit" }, "1/1/12": { "age": "11", "visit_category": "Follow Up Visit" }, "1/1/13": { "age": "12", "visit_category": "Follow Up Visit" }, "1/1/14": { "age": "13", "visit_category": "Follow Up Visit" }, "1/1/15": { "age": "14", "visit_category": "Follow Up Visit" } }, "samples": { "YYY456": { "completed_by": null, "label_on_sample": "2" }, "ZZZ789": { "completed_by": "Sally", "label_on_sample": "2" } } } ] I have a program that puts all of this into the right structure, but unfortunately because it uses csv's DictReader, it seems all variables are entered in as strings, making it difficult to query in meaningful ways. This code is below: def solution(csv_filename): by_subject_id = def…
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/88423107

http://stackoverflow.com/comment/88230647
type: QuestionComment
has text: which operating system ?
score: 0
comment on: http://stackoverflow.com/q/50610425
type: Comment

http://stackoverflow.com/a/50658318
answers question: http://stackoverflow.com/q/50658241
has body: Try removing this line, STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' Source: https://stackoverflow.com/a/32347324/2596187
upvote count: 13
score: 12
type: AcceptedAnswer
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/88327988
has comment: http://stackoverflow.com/comment/88327586
has comment: http://stackoverflow.com/comment/88327282
accepted answer of: http://stackoverflow.com/q/50658241
has comment: http://stackoverflow.com/comment/94680304

http://stackoverflow.com/comment/88185917
has text: yes I am using centos7 VM
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50588127
score: 0

http://stackoverflow.com/a/50572048
type: Answer
answers question: http://stackoverflow.com/q/50572004
upvote count: 5
score: 5
downvote count: 0
has body: In the example you provided, round(395, -2) means round 395 to the nearest hundred. The function round takes the precision you want as second argument. Negative precision means you want to remove significative digits before the decimal point. round(123.456, 3) # 123.456 round(123.456, 2) # 123.45 round(123.456, 1) # 123.4 round(123.456, 0) # 123.0 round(123.456, -1) # 120.0 round(123.456, -2) # 100.0 round(123.456, -3) # 0.0

http://stackoverflow.com/comment/88265644
has text: @khelwood I noticed I have both `2.7` and `3.6` versions how do I make the `3.6` version effective as default in windows?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50627763

http://stackoverflow.com/comment/88407337
has text: @GwJones I wonder, why you get this output. I added a link to Python Tutor, where you can follow the code execution and see, what happens at each step with the variables. As expected, it only prints out the first line within each group.
type: Comment
comment on: http://stackoverflow.com/a/50698233
score: 0
type: AnswerComment

http://stackoverflow.com/q/50547006
has body: I'm trying to set up communication between me and my friend's computer using the socket module. I run the server code on my computer and he runs the client code on his computer. Here is the code: Server: import socket host = "XXX.XXX.XX.XXX" # IP of my computer port = 2000 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind((host, port)) addrs = [] print("Server started") while True: data, addr = s.recvfrom(1024) if not addr in addrs: addrs.append(addr) data = data.decode("utf-8") print("Recieved: " + str(data)) print("Sending: " + data) for add in addrs: s.sendto(data.encode("utf-8"), add) Client: import socket import time host = "XXX.XXX.XXX.XXX" # External IP of my router port = 2001 server = (host, port) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setblocking(False) while True: message = "Test message" time.sleep(1) print("Sending: " + message) s.sendto(message.encode("utf-8"), server) try: data, addr = s.recvfrom(1024) except BlockingIOError: pass else: data = data.decode("utf-8") print("Recieved: " + str(data)) Note: The port in the client vs. server code is different to make sure that my port forwarding is actually doing something. I have set up port forwarding on my router. Everything works fine when I run both scripts on my computer (or even another computer connected to the same WiFi as mine) and I know that the port forwarding is doing its thing. However, when my friend (who is connected to a different WiFi) runs the client code, it doesn't work. No error is thrown, but he sends data which neither my computer nor the router's port forwarding rule recieves. Could this problem originate from my code, or is it more likely to be because of my router not being properly set up?
has title: Python Socket communication across networks not working
tagged with: sockets
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88105446
has answer: http://stackoverflow.com/a/50548184
accepted answer: http://stackoverflow.com/a/50783265
type: Question
has comment: http://stackoverflow.com/comment/88105518
has answer: http://stackoverflow.com/a/50783265
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/50548184

http://stackoverflow.com/comment/88143590
type: Comment
has text: can I use tf.nn.relu function as an activation function and tf.nn.sigmoid_cross_entropy_with_logits for calculating cross entropy
score: 0
comment on: http://stackoverflow.com/q/50565662
type: QuestionComment

http://stackoverflow.com/comment/88355982
comment on: http://stackoverflow.com/a/50672715
has text: Thank you for your give me solution , sir.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88366017
has text: In statistics, [kurtosis](https://en.wikipedia.org/wiki/Kurtosis) measures something kind of like this, if you can normalize your array as a probability distribution in a way that make sense maybe you could use that (although I'm not sure how it would be computed exactly).
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50678185
type: Comment

http://stackoverflow.com/comment/88242490
type: Comment
comment on: http://stackoverflow.com/q/50616240
score: 0
type: QuestionComment
has text: What is the name of your .kv?

http://stackoverflow.com/q/50616574
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50616740
tagged with: django
has title: Django Error that does nothing?
type: Question
score: 0
upvote count: 1
answer count: 1
downvote count: 1
has body: My project in django 2.0, python 3.x and I think its when i go into django admin I get this series of trackbacks and red letters that I assume is some kind of error, i just have no idea whatsoever what it is. ERROR does nothing:ERROR does nothing: Traceback (most recent call last): File "C:\Users\Andre\Anaconda3\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\Andre\Anaconda3\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\Andre\Anaconda3\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\Andre\Anaconda3\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "C:\Users\Andre\Anaconda3\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "C:\Users\Andre\Anaconda3\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "C:\Users\Andre\Anaconda3\lib\socketserver.py", line 775, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] Se ha anulado una conexión establecida por el software en su equipo host [30/May/2018 14:06:28] "GET /static/admin/css/changelists.css HTTP/1.1" 500 59 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 61210) [30/May/2018 14:06:28] "GET /static/admin/js/jquery.init.js HTTP/1.1" 200 363 Traceback (most recent call last): File "C:\Users\Andre\Anaconda3\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\Andre\Anaconda3\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\Andre\Anaconda3\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\Andre\Anaconda3\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "C:\Users\Andre\Anaconda3\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encod…

http://stackoverflow.com/q/50588944
has answer: http://stackoverflow.com/a/50589012
has title: Using a loop to describe multiple conditions
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88194267
has comment: http://stackoverflow.com/comment/88187449
possible better answer: http://stackoverflow.com/a/50589012
has comment: http://stackoverflow.com/comment/88188173
has comment: http://stackoverflow.com/comment/88187348
has comment: http://stackoverflow.com/comment/88187573
type: Question
tagged with: for-loop
has answer: http://stackoverflow.com/a/50589344
accepted answer: http://stackoverflow.com/a/50589053
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/50589053
has body: In the following code, I am trying to extract numbers from a list in which all digits are divisible by 2. The following code works. l = range(100,401) n=[] for i in l: s =str(i) if all([int(s[0])%2==0,int(s[1])%2==0,int(s[2])%2==0]): n.append(s) print(",".join(n)) I was trying to insert a for loop to avoid writing all three conditions explicitly. l = range(100,401) n=[] ss=[] for i in l: s =str(i) ss.append(s) for element in ss: for j in range(3): if int(element[j])%2==0: n.append(element) print(n) I can't get the desired output. Not only that, the elements of output list 'n' at even index are printed twice. I am unable to figure out WHY? Thanks.
favorite count: 0
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/comment/88256194
type: Comment
comment on: http://stackoverflow.com/q/50622088
score: 0
type: QuestionComment
has text: For how large n are you interested in Fib(n)?

http://stackoverflow.com/comment/88228734
type: Comment
comment on: http://stackoverflow.com/a/50609149
has text: @SHatna: there is conceptually no difference between moving an existing item in a loop and creating a new one in a loop. Understand the technique, and then you can apply it to all sorts of problems.
score: 1
type: AnswerComment

http://stackoverflow.com/comment/88213202
has text: are you getting any error, can you send the stack traces
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50602030

http://stackoverflow.com/a/73217682
downvote count: 0
has body: Use faulthandler it will show the stack trace when application crashes through which u can debug the issue import faulthandler if __name__ == &quot;__main__&quot;: faulthandler.enable() #start @ the beginning ... # application logic
type: Answer
upvote count: 10
answers question: http://stackoverflow.com/q/50620954
score: 10

http://stackoverflow.com/q/50607147
accepted answer: http://stackoverflow.com/a/50607387
type: Question
answer count: 2
downvote count: 4
upvote count: 0
has comment: http://stackoverflow.com/comment/88224151
has body: Generate Random numbers with parameters. So like random numbers from 1 to 10 and 15 to 20 The output would be either 1,2,3,4,5,6,7,8,9,15,16,17,18,19 The numbers from 10 to 15 would be excluded
has comment: http://stackoverflow.com/comment/88223948
has title: Random Numbers in Python with Paramaters
favorite count: 0
has answer: http://stackoverflow.com/a/50607387
tagged with: python-3.x
score: -4
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88224019
possible better answer: http://stackoverflow.com/a/50607365
has answer: http://stackoverflow.com/a/50607365

http://stackoverflow.com/q/50559000
has answer: http://stackoverflow.com/a/50569248
accepted answer: http://stackoverflow.com/a/50569248
has title: How do I make 2 images appear side by side in Jupyter notebook (iPython)?
has comment: http://stackoverflow.com/comment/88129274
has comment: http://stackoverflow.com/comment/88129292
has comment: http://stackoverflow.com/comment/88129576
favorite count: 0
has answer: http://stackoverflow.com/a/61592610
has comment: http://stackoverflow.com/comment/88129599
has answer: http://stackoverflow.com/a/67326284
has answer: http://stackoverflow.com/a/67424400
linked to: http://stackoverflow.com/q/33647774
tagged with: python
possible better answer: http://stackoverflow.com/a/61592610
upvote count: 22
has comment: http://stackoverflow.com/comment/88129505
tagged with: jupyter-notebook
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/74609552
has comment: http://stackoverflow.com/comment/88128575
linked to: http://stackoverflow.com/q/38783027
has comment: http://stackoverflow.com/comment/88128619
type: Question
has body: I want to display 2 PNG images in iPython side by side. My code to do this is: from IPython.display import Image, HTML, display img_A = '\path\to\img_A.png' img_B = '\path\to\img_B.png' display(HTML(" ")) But it doesn't output the images, and instead only displays placeholders for the 2 images: I tried the following as well: s = """ """%(img_A, img_B) t=HTML(s) display(t) But the result is the same: The images are in the path for sure, because I verified by displaying them in a pop up: plt.imshow(img_A) plt.imshow(img_B) and they do appear in the pop ups. How do I make the 2 images appear side by side in iPython?
has answer: http://stackoverflow.com/a/71319109
duplicate of: http://stackoverflow.com/q/33647774
has comment: http://stackoverflow.com/comment/126285470
answer count: 6
linked to: http://stackoverflow.com/q/60640375
tagged with: ipython
score: 22
has comment: http://stackoverflow.com/comment/126063363
tagged with: image

http://stackoverflow.com/comment/137799847
has text: It worked! Thank you. Are you sure about `-9`? Didn't find anything about it in the man page and it's working without it too.
comment on: http://stackoverflow.com/a/61570169
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/50656131
accepted answer of: http://stackoverflow.com/q/50655906
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50655906
has body: Approach #1 One vectorized solution based on np.searchsorted and incorporating for closeness for floating-pt numbers, would be - def count_occ(a1,a2,use_closeness=True): # Trace back indices for each elem of a2 in a1 idx = np.searchsorted(a1,a2) # Set out of bounds indices to something within idx[idx==len(a1)] = 0 # Check for the matches if use_closeness==1: mask = np.isclose(a1[idx],a2) else: mask = a1[idx] == a2 # Get counts return np.bincount((idx+1)*mask,minlength=len(a1)+1)[1:] Sample run - In [154]: a1 = np.array([1.0000001,4,5,6]) In [155]: a2 = np.array([2,5,8,5,8,5,0.999999999999]) In [156]: count_occ(a1,a2) Out[156]: array([1, 0, 3, 0]) In [157]: count_occ(a1,a2,use_closeness=False) Out[157]: array([0, 0, 3, 0]) Approach #2 Alternatively, we can also use broadcasting for a short but memory-intensive method, like so - (a1[:,None]==a2).sum(1) # For exact matches np.isclose(a1[:,None],a2).sum(1) # For close matches Approach #3 :Specific case with a1 as lin-spaced data For the Specific case when a1 is a lin-spaced array and again considering the closeness, we can optimize further using rounding of a2 data, like so - def count_occ_rounding(a2, a1_startnum=0,a1_lastnum=2*np.pi, a1_num_sample=101): s = (a1_lastnum-a1_startnum)/(a1_num_sample-1) p = np.round((a2 - a1_startnum)/s).astype(int) return np.bincount(p,minlength=a1_num_sample) Sample run to verify output with generic start, end range array for a1 - In [284]: a1 = np.linspace(-2*np.pi,2*np.pi,201) ...: a2 = np.random.choice(a1, 60) ...: out1 = count_occ_rounding(a2, -2*np.pi, 2*np.pi, 201) ...: out2 = np.isclose(a1[:,None],a2).sum(1) ...: print np.allclose(out1, out2) True

http://stackoverflow.com/comment/88264082
comment on: http://stackoverflow.com/q/50608944
type: Comment
type: QuestionComment
score: 1
has text: @Sp0gg, there was a version conflict when updating pip so it took some time but deleting it and reinstalling it without using apt-get solved the problem. Upgrading python-requests then solved the problem.

http://stackoverflow.com/q/50691394
tagged with: python
favorite count: 0
has title: Trying to create AI - Some IF statement not catching
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88392471
upvote count: 1
has comment: http://stackoverflow.com/comment/88392579
score: 1
type: Question
answer count: 2
has body: So I'm trying to make an AI and for some reason I cant get the IF statements to catch the code. Alice.py import games from function import * startup() main() My problem is in the main() function. def main() life = True while life == True: request = input('-&gt; ') if request.startswith('play'): request.replace('play ', '', 1) if request == 'guess the number': games.guess_the_number(u_name) elif request == 'test': print('Test') if request == 'quit': print('Goodbye') return I can't seem to get the first IF block to opereate the way I want. It just returns no output. I have tried everything and I just can't seem to get it to work. Amy help would be amazing. I'll gladly answer any questions anyone has.
downvote count: 0
has comment: http://stackoverflow.com/comment/88392545
has answer: http://stackoverflow.com/a/50691516
has answer: http://stackoverflow.com/a/50691517

http://stackoverflow.com/comment/88230595
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50610355
score: 0
has text: You could add an arbitrary counter that gets increased every iteration. And you put that `ax.annotate(...)` inside an `if counter % 50 == 0` to annotate every 50th point. The counter could be added manually or by using `enumerate`.

http://stackoverflow.com/a/50547376
score: 0
has comment: http://stackoverflow.com/comment/88107258
has comment: http://stackoverflow.com/comment/88106135
has comment: http://stackoverflow.com/comment/88106397
type: Answer
has comment: http://stackoverflow.com/comment/88112815
has comment: http://stackoverflow.com/comment/88105601
answers question: http://stackoverflow.com/q/50546871
has body: hacky: suppose you call the bot with "play u1" elif query[0] == 'u': try: n = int(query[1]) await bot.say(videos[n][0]) essentially query is string which can be accesd like a list. Have a look here: How to get char from string by index?

http://stackoverflow.com/comment/88199974
has text: @DanielRoseman Thx, you mentioned me, I search the related question and found that almost no one recommend newbie to use `sys.setdefaultencoding` in projects, so I remove it from my settings' file. First I check the Chinese string data type what I ready to store, it's unicode, then I check the model, when I change the instance methods from `__str__` to `__unicode__`, it works! I avoid the UnicodeEncodeError
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50579547

http://stackoverflow.com/q/50610831
has comment: http://stackoverflow.com/comment/88232005
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88231887
has comment: http://stackoverflow.com/comment/88231841
has body: Instead of iterating through each element in a matrix and checking if random() returns lower than the rate of mutation, does it work if you generate a certain amount of random indices that match the rate of mutation or is there some other method?
has answer: http://stackoverflow.com/a/50734768
accepted answer: http://stackoverflow.com/a/50734768
tagged with: statistics
score: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88232186
upvote count: 1
tagged with: python
downvote count: 1
type: AnsweredQuestion
has title: Mutation algorithm efficiency
tagged with: genetic-algorithm

http://stackoverflow.com/a/50570557
accepted answer of: http://stackoverflow.com/q/50570267
answers question: http://stackoverflow.com/q/50570267
type: Answer
score: 1
upvote count: 1
downvote count: 0
has body: You can use map from map-reduce (Please look for map-reduce in python for more details) namelist = [{'name': 'John'},{'name': 'Tin'},{'name': 'Mony'}, {'name':'Hilber'},{'name': 'Marge'}] result = map(lambda item: item.get('name'), namelist) print(list(result)) In short map operation simply lets you map a collection of items into a different collection of items. It takes a function and at least one iterable as an argument. On each iteration, a single item is supplied to the function which must return a value. The value is collected which is of map type which can be converted using list().
type: AcceptedAnswer

http://stackoverflow.com/a/50565261
has body: The problem is in this line print(somemodel_filter.objects.all()). somemodel_filter is not model, it's filterset instance and since it's don't have objects attribute. To get filtered queryset use qs attribute, like this: print(somemodel_filter.qs) You can find example of filter usage here.
score: 4
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50563326
has comment: http://stackoverflow.com/comment/88171592
answers question: http://stackoverflow.com/q/50563326
upvote count: 4
has comment: http://stackoverflow.com/comment/88171418

http://stackoverflow.com/a/50614197
has body: The first issue to clear up is terminology. Technically, what you have is not an array or a matrix. You have a list of lists. To iterate over every other line, you can use list indexing. For a list A, this takes the format A[start:stop:step], where start, stop and step are integers (positive or negative) and stop is not included in the range. If you omit an integer, it is assumed to be 0 for start, None for end, 0 for step. Therefore, to iterate over the first person's words, you can use: for words_a in array[::2]: # do something Or, for the second person's words, use array[1::2]. Note the above method involves building new lists. A more memory-efficient method is to use an iterator, such as itertools.slice: from itertools import islice for words_a in islice(array, 0, None, 2): # do something
answers question: http://stackoverflow.com/q/50614108
type: Answer
score: 0

http://stackoverflow.com/a/50611963
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88271911
has comment: http://stackoverflow.com/comment/88236700
accepted answer of: http://stackoverflow.com/q/50611929
score: 6
answers question: http://stackoverflow.com/q/50611929
type: Answer
upvote count: 6
has body: Need filter as first step by boolean indexing: Sample: df = pd.DataFrame({'Teams': ['Green', 'Blue', 'Red', 'Orange', 'Green', 'Blue', 'Grey', 'Purple'], 'Revenue': [18, 15, 20, 5, 10, 15, 2, 5], 'Location': ['A', 'B', 'V', 'G', 'A', 'D', 'B', 'C']}) print (df) Teams Revenue Location 0 Green 18 A 1 Blue 15 B 2 Red 20 V 3 Orange 5 G 4 Green 10 A 5 Blue 15 D 6 Grey 2 B 7 Purple 5 C First get top values and select column Teams: Rev = df.nlargest(3,'Revenue')['Teams'] print (Rev) 2 Red 0 Green 1 Blue Name: Teams, dtype: object Then need filter first by boolean indexing: print (df[df['Teams'].isin(Rev)]) Teams Revenue Location 0 Green 18 A 1 Blue 15 B 2 Red 20 V 4 Green 10 A 5 Blue 15 D df1 = (df[df['Teams'].isin(Rev)] .groupby('Teams',as_index=False)['Revenue'] .sum() .sort_values('Revenue', ascending=False)) print (df1) Teams Revenue 0 Blue 30 1 Green 28 2 Red 20 If need multiple columns to output is necessary set aggregation function for each of them like: df2 = (df[df['Teams'].isin(Rev)] .groupby('Teams',as_index=False) .agg({'Revenue':'sum', 'Location': ', '.join, 'Another col':'mean'})) print (df2) Teams Revenue Location 0 Blue 30 B, D 1 Green 28 A, A 2 Red 20 V

http://stackoverflow.com/comment/88278838
comment on: http://stackoverflow.com/q/50634310
type: Comment
type: QuestionComment
has text: It's probably not going to be more _efficient_ to put it in a loop, but it's going to be a lot more readable, maintainable, and debuggable.
score: 0

http://stackoverflow.com/q/50605692
has title: Tensorflow prediction using tf.estimator.Estimator too slow
answer count: 0
score: 1
tagged with: machine-learning
upvote count: 1
tagged with: tensorflow
has body: I've installed tensorflow in raspberry pi 3. It is using pretrained model and feed model function into tf.estimator.Estimator. My project is using c++ and currently embeds python code using boost::numpy that converts opencv matrix into numpy type, and pass it over to python function to be predicted and get results. My model function defined like below. only the propagation portion: def cnn_estimator_fn(features, labels, mode): inputs=tf.reshape(features[FEATURE_LABEL],[-1,24,16,1],name="input_node") #24 x 16 x 1, which is gray or binary image and same number of samples conv1=tf.layers.conv2d(inputs=inputs, filters=6, kernel_size=[5,5], padding='same', activation=tf.nn.leaky_relu ) #conv1 output shape: (batch_size,24,16,6) pool1=tf.layers.max_pooling2d(inputs=conv1,pool_size=[2,2],strides=2,padding='valid') #pool1 output shape: (batch_size,12,8,6) conv2=tf.layers.conv2d(inputs=pool1,filters=12,kernel_size=[5,5],padding='same',activation=tf.nn.leaky_relu) #conv2 output shape: (batch_size, 12,8,12) pool2=tf.layers.max_pooling2d(inputs=conv2,pool_size=[2,2],strides=2,padding='valid') #pool2 output shape: (batch_size, 6,4,12) #dense fully connected layer pool2_flat=tf.reshape(pool2,[-1,6*4*12]) #flatten pool2 output to feed in dense layer dense1=tf.layers.dense(inputs=pool2_flat,units=144,activation=tf.nn.leaky_relu) #apply dropout to avoid overfitting dropout=tf.layers.dropout(inputs=dense1,rate=0.3,training=mode==tf.estimator.ModeKeys.TRAIN) logits=tf.layers.dense(dropout,11) #input for softmax layer Well, it's poorly made but i thoutht size of network is adequate for rpi3 spec. But when i ran prediction by feeding this function into tf.estimator.Estimator and call tf.estimator.predict, it takes like 3 ~ 5 seconds to predict 20 images, each shape is [24, 16, 1]. It's too slow!! I tried following assumtion to be the problem, none was right: (1) Converting vector&lt;cv::Mat&gt;&gt; into boost::numpy takes too long: no it wasn't as it took 0.00023 seconds. (2) Maybe 20~30…
has comment: http://stackoverflow.com/comment/88221309
type: Question
downvote count: 0
tagged with: raspberry-pi3
favorite count: 0
tagged with: boost-python
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88221258

http://stackoverflow.com/a/50569856
type: Answer
score: 2
has body: I think you need to pass thesqlite3.PARSE_DECLTYPES option (see this comment): conn = sqlite3.connect('sqlite_file.sqlite', detect_types=sqlite3.PARSE_DECLTYPES) You can also apply the transformation after loading the dataframe: out['v1'] = out['v1'].apply(convert_array)
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/88166510
answers question: http://stackoverflow.com/q/50569070

http://stackoverflow.com/comment/88169292
score: 0
type: AnswerComment
type: Comment
has text: @dunkubok I was only following the blueprint from the question and answer here.
comment on: http://stackoverflow.com/a/50579507

http://stackoverflow.com/comment/88223368
comment on: http://stackoverflow.com/q/50606819
has text: Be careful. Your terminology is incorrect. The `[` and `]` you mention **do not exist**. They represent a `list` object, and are used by Python as a visual aid to indicate a `list`. It *appears* you want to convert the items of a list to a string; use `str.join` for this.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50572655
type: Question
score: -1
possible better answer: http://stackoverflow.com/a/50572780
has title: How to parse contents from a list of dicts in json using python3
answer count: 2
downvote count: 2
upvote count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/50572919
accepted answer: http://stackoverflow.com/a/50572919
has answer: http://stackoverflow.com/a/50572780
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88155083
has comment: http://stackoverflow.com/comment/88154969
tagged with: http://stackoverflow.com/tag/json
has body: My json file : { "data": [ { "features": { "location": "West Springfield, MA", "geo_type": "User location", "screen_name": "JtTatro", "primary_geo": "West Springfield, MA", "id": 2158092352, "tweets": 1, "name": "Jim Tatro" }, "user_id": 2158092352 } , { "features": { "location": "Tijuana, Baja California", "geo_type": "User location", "screen_name": "YuitziContreras", "primary_geo": "Tijuana, Baja California", "id": 996917180980744193, "tweets": 1, "name": "yuitzi contreras" }, "user_id": 996917180980744193 } ] } i am trying to parse the data stored in the features dict. My code so far: import json input_file = open ('file.json') json_array = json.load(input_file) tweet_list = [] features_list = [] user_list =[] for item in json_array: for item2 in json_array[item]: tweet_list.append(item2) for features,user in tweet_list: print(features,user) the code above returns the dict names : features, user_id. how would it be possible to get the contents of each dict field so that i can pass them to my database? For example, get location, geo_type etc.

http://stackoverflow.com/comment/104043426
has text: May be you have installed 64 bit version, Please check the below path if you have 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'. In case tesseract is available, change that line as below pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'
comment on: http://stackoverflow.com/a/51662074
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50682427
has body: I wrote a class in python tkinter that you can use to create buttons that change their images on leave, enter and button-1 event. The script: from tkinter import * class ImageButton: def CreateButton(self, image, root): # --- image setup --- self.ImageName = image self.ButtonRoot = root self.normal = PhotoImage(file="Images/" + self.ImageName + "/normal.png") self.hover = PhotoImage(file="Images/" + self.ImageName + "/hover.png") self.clicked = PhotoImage(file="Images/" + self.ImageName + "/clicked.png") # --- button setup --- self.Button = Button(self.ButtonRoot, image=self.normal) self.Button.bind("&lt;Leave&gt;", self.normal_event) self.Button.bind("&lt;Enter&gt;", self.hover_event) self.Button.bind("&lt;Button-1&gt;", self.click_event) return self.Button def normal_event(self, event): self.Button.config(image=self.normal) def hover_event(self, event): self.Button.config(image=self.hover) def click_event(self, event): self.Button.config(image=self.clicked) Root = Tk() Image = ImageButton() FirstButton = Image.CreateButton("scann_device", Root) FirstButton.grid(row=0, column=0) SecondButton = Image.CreateButton("get_device_info", Root) SecondButton.grid(row=1, column=0) Root.mainloop() So if you create a button with that class, you can do anything you want. It only binds it to the events I mentioned above. If you create 1 button, it works and you see it on your window, but if you create 2 buttons and grid/pack them, it wont work. It looks like this. The second button also gets the hitbox of the first button.
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
has title: Python tkinter class 2 buttons, only 1 visible
type: Question
has answer: http://stackoverflow.com/a/50683310
accepted answer: http://stackoverflow.com/a/50683310
has comment: http://stackoverflow.com/comment/88375759
tagged with: class
score: 0
answer count: 1

http://stackoverflow.com/comment/88225319
type: QuestionComment
has text: No Keras experience so I can't give you any advice there... good luck!
comment on: http://stackoverflow.com/q/50594194
type: Comment
score: 0

http://stackoverflow.com/q/50562160
accepted answer: http://stackoverflow.com/a/50562414
has title: Select fields to return from $lookup
upvote count: 5
downvote count: 0
has body: I have a piece of code to join collection A (sample) to collection B (locators). I've tried the $unwind, $group and $push syntax the only problem is that I can't return the field locator and record. data = db.sample.aggregate([ {'$lookup': { 'from': 'locators', 'localField': "locator", 'foreignField': "_id", 'as': "metalocator"}}]) print(list(data)) Which returns [ { '_id': '599A65E1A80541BA', 'locator': 'ABC', 'record': 'Nicaragua', 'metalocator': [{'_id': 'ABC', 'group': 'Location', 'section': 'Geo', 'cabinet': 'Country', 'record': 'string', 'status': 'integer'}] }, { '_id': '428E970995AE8C76', 'locator': 'CDE', 'record': 'Nigeria', 'metalocator': [{'_id': 'CDE', 'group': 'Location', 'section': 'Geo', 'cabinet': 'Country', 'record': 'string', 'status': 'integer'}] } ] attempt 1 data = db.sample.aggregate([ {"$lookup": {"from": "locators", "localField": "locator", "foreignField": "_id", "as": "metalocator"}}, {"$unwind": '$metalocator'}, {"$group": {"_id": "$_id", "metalocator": {"$push": { "section": "$metalocator.section", "cabinet": "$metalocator.cabinet"}}}} ]) print(list(data)) Which returns: [ { '_id': '1835853D2982AAEF', 'metalocator': [{'section': 'Geo', 'cabinet': 'Country'}] }, { '_id': '428E970995AE8C76', 'metalocator': [{'section': 'Geo', 'cabinet': 'Country'}] } ] Expected result should be: [ { '_id': '1835853D2982AAEF', 'locator': 'ABC', 'record': 'Nicaragua', 'metalocator': [{'section': 'Geo', 'cabinet': 'Country'}] }, { '_id': '428E970995AE8C76', 'locator': 'CDE', 'record': 'Nigeria', 'metalocator': [{'section': 'Geo', 'cabinet': 'Country'}] } ]
answer count: 1
favorite count: 0
tagged with: aggregation-framework
has answer: http://stackoverflow.com/a/50562414
tagged with: python
type: AnsweredQuestion
tagged with: pymongo
type: Question
tagged with: mongodb
score: 5

http://stackoverflow.com/comment/88138015
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50563462
has text: Simply Just implement `try`/`except` construction as [here](https://stackoverflow.com/questions/50529563/how-to-get-attribute-value-selenium-python/50530329#50530329)

http://stackoverflow.com/a/50777406
answers question: http://stackoverflow.com/q/50651811
score: 0
has body: I understand that this is not the way to go but as for my needs and my level of experience it works for me! Yandex allows you to send email from different ip so Yandex is the way to go. What I was doing wrong in the first place was to use the wrong port (587 instead of 465)
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50651811

http://stackoverflow.com/comment/88259365
score: 0
has text: @user8866270 - added solutions for `Datetimeindex`
type: Comment
comment on: http://stackoverflow.com/a/50621816
type: AnswerComment

http://stackoverflow.com/q/50542213
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/50542324
has answer: http://stackoverflow.com/a/50542324
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50542352
tagged with: python
type: AnsweredQuestion
tagged with: list
tagged with: performance
has title: List of Objects: Efficiently getting a list of sum of ith attribute
tagged with: oop
has body: Sorry if the title is confusing, I don't know how to really word this problem well. I'm fairly new to programming outside of class projects/work, and I'm trying to develop good programming habits, and avoid loops where I can (i.e. staying away from inefficient code). A project I'm working on involves getting a list of sum of ith attribute from a list of objects, and I managed to do something with map comprehensions, but I'm wondering if there's a better way to do it. Say I'm working with a class Foo, with n attributes, a1, a2, ... , an, all integers, and a list l containing m of these objects. For example, for n = 3, we could have something like: l = [Foo(a1 = 1, a2 = 2, a3 = 3), Foo(a1 = 1, a2 = 2, a3 = 3), Foo(a1 = 1, a2 = 2, a3 = 3)] I want my result to look like: sums = [3, 6, 9] I did it this way: sums = [sum([x.a1 for x in l]), sum([x.a2 for x in l]), sum([x.a3 for x in l])] Now the issue is, if Foo has a lot of attributes, then typing out each x.ancould be unfeasible. The attributes don't necessarily have an integer attached to them as well, so they could be things like Foo(these, are, some, attributes). So, my question is, what is the "smart" way of solving this problem? Does it involve a use of a loop? Thank you.
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/50542352

http://stackoverflow.com/a/50582337
has comment: http://stackoverflow.com/comment/88180907
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50581645
type: Answer
has comment: http://stackoverflow.com/comment/88181579
accepted answer of: http://stackoverflow.com/q/50581645
has body: There were several problems. You use both pack and grid in __init__. Since you import Calendar.py it's not in your namesapce and you must compensate for that. The name gets to be Calendar.Calendar as both the package and class are named Calendar. Use buttons instead of labels, and associate them with a command to open the calendar. Save a reference to master so you can call it. I also bound SPACE to the printout function. import tkinter as tk import Calendar class Application(tk.Frame): def __init__(self, master = None): super().__init__(master) self.master = master self.grid() self.data = {} self.create_widgets() def create_widgets(self): self.winfo_toplevel().title("Choose date") self.sd_button = tk.Button(self, text="Start date", command=self.popup) self.sd_button.grid() self.ed_button = tk.Button(self, text="End date", command=self.popup) self.ed_button.grid() self.master.bind('&lt;space&gt;', self.print_selected_date) def popup(self): child = tk.Toplevel() cal = Calendar.Calendar(child, self.data) def print_selected_date(self, event): print(self.data) root = tk.Tk() my_gui = Application(root) root.mainloop() The class Control is not part of the calendar but is included as an example of how to use it. This is a common way of building packages. Look for the line if __name__ == '__main__': and there the example will be.

http://stackoverflow.com/q/50639222
score: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Memory Error while running python script on 4GB file
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88288464
has comment: http://stackoverflow.com/comment/88288468
has comment: http://stackoverflow.com/comment/88291205
has body: I am trying to count number of words that has length between 1 and 5, file size is around 4GB end I am getting memory error. import os files = os.listdir('C:/Users/rram/Desktop/') for file_name in files: file_path = "C:/Users/rram/Desktop/"+file_name f = open (file_path, 'r') text = f.readlines() update_text = '' wordcount = {} for line in text: arr = line.split("|") word = arr[13] if 1&lt;=len(word)&lt;6: if word not in wordcount: wordcount[word] = 1 else: wordcount[word] += 1 update_text+= '|'.join(arr) print (wordcount) #print update_text print 'closing', file_path, '\t', 'total files' , '\n\n' f.close() At the end i get a MemoryError on this line text = f.readlines() Can you pelase help to optimize it.
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/88288496
has answer: http://stackoverflow.com/a/50639355
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88288858

http://stackoverflow.com/comment/88284986
type: QuestionComment
has text: Your example is far from [Minimal, Complete, and Verifiable](https://stackoverflow.com/help/mcve)
comment on: http://stackoverflow.com/q/50636902
score: 0
type: Comment

http://stackoverflow.com/q/50584379
tagged with: python
tagged with: command-prompt
has body: I have inherited a python program, which works as follows: Checks for files in a directory If present loads them into somewhere Once it finds no files in the directory it just prints 'No files to load' reccursively We run it in a batch file looks like this python python_file.py The problem is that I have to manually close the command line to end the task. As a quick fix, is there a way to stop the program once No files to load appears in the terminal window?
has comment: http://stackoverflow.com/comment/88206902
type: Question
has comment: http://stackoverflow.com/comment/88178242
score: 0
tagged with: batch-file
has answer: http://stackoverflow.com/a/50584623
tagged with: windows
answer count: 1
tagged with: cmd
has title: End process when 'No files to load' is outputted to terminal
type: UnansweredQuestion

http://stackoverflow.com/a/50571175
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50571153
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/88152075
type: Answer
has comment: http://stackoverflow.com/comment/88152811
upvote count: 4
has comment: http://stackoverflow.com/comment/88152211
has comment: http://stackoverflow.com/comment/88152761
has comment: http://stackoverflow.com/comment/88152177
has body: Neither a match object nor None, the two types of objects that re.match() can return, is ever equal to True: &gt;&gt;&gt; importe re &gt;&gt;&gt; None == True False &gt;&gt;&gt; re.match(r'[a-zA-Z0-9]{6,}', '4fdg5Fj3') &lt;_sre.SRE_Match object; span=(0, 8), match='4fdg5Fj3'&gt; &gt;&gt;&gt; re.match(r'[a-zA-Z0-9]{6,}', '4fdg5Fj3') == True False Don't use == True. If you need to see if the match succeeded, test for is not None: &gt;&gt;&gt; re.match(r'[a-zA-Z0-9]{6,}', '4fdg5Fj3') is not None True &gt;&gt;&gt; re.match(r'No such pattern', 'will not match') is not None False You should almost never use == True or == False. In a boolean context like an if statement, just drop == True; it is the job of the statement to test for the boolean truth. For == False, put not in front instead. Moreover, as seen above, most objects are not equal to True or False; to test for the truth value, just pass in the object itself, or convert the truth value too a boolean using the bool() function.
accepted answer of: http://stackoverflow.com/q/50571153

http://stackoverflow.com/q/50690944
has answer: http://stackoverflow.com/a/51050833
tagged with: azure-cosmosdb
has title: Adding Spatial Index to CosmosDB using PythonAPI
type: Question
has body: It seems that the 'Spatial' index type is missing from the definitions: https://learn.microsoft.com/en-us/python/api/pydocumentdb.documents.indexkind?view=azure-python How does one create a collection with a Spatial index programmatically via the Python API in CosmosDB then? Simply typing the string "Spatial" or adding { "kind": "Spatial", "dataType": "Point" } to the indices in the collection settings also does not seem to work. I'm not able to make spatial queries work on a Graph database populated via the DocumentAPI using Python 3.
tagged with: spatial
accepted answer: http://stackoverflow.com/a/51050833
score: 0
tagged with: geospatial
answer count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/50597013
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/48540170
has body: I am reading headers of csv files from a folder. code: #mypath = folder directory with the csv files for each_file in listdir(mypath): with open(mypath +"//"+each_file) as f: first_line = f.readline().strip().split(",") Error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 3131: invalid start byte Environment: Spyder, Python 3 Not able to understand the encoding error since I have not done any encoding.
tagged with: python
has comment: http://stackoverflow.com/comment/88203148
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50597388
has answer: http://stackoverflow.com/a/50597180
possible better answer: http://stackoverflow.com/a/50597180
type: Question
has title: decoding error while reading csv files from folder
has answer: http://stackoverflow.com/a/50597388
linked to: http://stackoverflow.com/q/37177069
score: 0
answer count: 3
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/51157062

http://stackoverflow.com/comment/88365903
comment on: http://stackoverflow.com/q/50678078
score: 0
type: Comment
type: QuestionComment
has text: if you add a `*` before `args` in `f`, such as `f(*args, z=z)`, it should work?

http://stackoverflow.com/a/50764273
answers question: http://stackoverflow.com/q/50631349
type: Answer
has body: You need some acrobatic. In your viewsets you determines the payload and the http-method. And use different Serializer class handle them.
score: 0

http://stackoverflow.com/a/50634079
has body: Use mask with ^[a-z]+$ as your regular expression: df = pd.DataFrame({'names': ['Chris Z', 'Hulk Hogan', 'notaname', 'whateven']}) df.names.mask(df.names.str.match(r'^[a-z]+$')) 0 Chris Z 1 Hulk Hogan 2 NaN 3 NaN Name: names, dtype: object If there are spaces in some of the lowercase strings, just use ^[a-z\s]+$ instead. ^ # Asserts position at beginning of string [ a-z # Matches any lowercase character 1 or more times ]+ $ # Asserts position at end of string
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50633935
type: Answer
answers question: http://stackoverflow.com/q/50633935
score: 3
upvote count: 3

http://stackoverflow.com/q/50656751
has body: I want to send key down events to game applications using pywinauto. I get the application like this: from pywinauto.application import Application app = Application() app.connect(title='Adobe Flash Player 29') win = app.window_(title_re = "Adobe Flash Player 29") This allows me to send things like mouse clicks to the application: win.Click(coords=(300,330)) This works fine, and I can also send "TypeKeys" events to the application: while True: win.TypeKeys("w") However, instead of holding the key down, it repeatedly sends single letters to the game. I need a way to hold the key down instead (and this must be in context of an application, not just a raw keyboard input). EDIT: I mean I want to send held key presses to applications other than the active window
has comment: http://stackoverflow.com/comment/88339889
tagged with: pywin32
downvote count: 0
score: 1
has title: pywinauto send key down to application
tagged with: pywinauto
favorite count: 0
has comment: http://stackoverflow.com/comment/88332030
type: Question
tagged with: python
upvote count: 1
tagged with: ui-automation
answer count: 1
has comment: http://stackoverflow.com/comment/88331937
has answer: http://stackoverflow.com/a/50656971
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88338946

http://stackoverflow.com/q/50592552
has title: Trim the whitespace of the grayscale image
favorite count: 0
has comment: http://stackoverflow.com/comment/88194713
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/10615901
has comment: http://stackoverflow.com/comment/88197156
upvote count: 1
downvote count: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88194492
has comment: http://stackoverflow.com/comment/88194558
has comment: http://stackoverflow.com/comment/88194594
has answer: http://stackoverflow.com/a/50594019
has answer: http://stackoverflow.com/a/50592805
has body: image like this I get a images set, and the images are like this. How can I remove the beneath white part of the image using python, which doesn't contain any useful content? I read the image to numpy array in python. My code is like this: data_dir = "/Users/leon/Projects/inpainting/data/" images = [] files = glob.glob (data_dir + "*.jpg") for file in files: image = cv2.imread(file, 0) images.append(image)
tagged with: image
score: 0
answer count: 2
tagged with: deep-learning

http://stackoverflow.com/a/50564047
has comment: http://stackoverflow.com/comment/88167482
answers question: http://stackoverflow.com/q/50563867
accepted answer of: http://stackoverflow.com/q/50563867
type: AcceptedAnswer
downvote count: 0
has body: This is not an Excel issue. The reason you are seeing this behaviour is because pandas writes datetime series as datetime objects, which attach a specific representation in Excel. If you want a specific string format, then you need to convert your datetime series to strings before you write to Excel: df['Date'] = df['Date'].dt.strftime('%Y/%m/%d') I recommend you ask your second question separately with a Minimal, Complete and Verifiable Example.
has comment: http://stackoverflow.com/comment/88167491
type: Answer
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/88167989

http://stackoverflow.com/comment/88270556
type: Comment
comment on: http://stackoverflow.com/a/50617146
type: AnswerComment
has text: No it creates a 1d array. That's not the same as a column or row vector. Those are MATLAB terms, where everything is 2d. `x[:, [1]]` produces a (n,1) array.
score: 0

http://stackoverflow.com/q/50615323
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50620075
downvote count: 0
score: 7
tagged with: recurrent-neural-network
type: Question
has title: Keras SimpleRNN confusion
upvote count: 7
answer count: 1
tagged with: keras
favorite count: 0
accepted answer: http://stackoverflow.com/a/50620075
linked to: http://stackoverflow.com/q/50608080
tagged with: python
has body: ...coming from TensorFlow, where pretty much any shape and everything is defined explicitly, I am confused about Keras' API for recurrent models. Getting an Elman network to work in TF was pretty easy, but Keras resists to accept the correct shapes... For example: x = k.layers.Input(shape=(2,)) y = k.layers.Dense(10)(x) m = k.models.Model(x, y) ...works perfectly and according to model.summary() I get an input layer with shape (None, 2), followed by a dense layer with output shape (None, 10). Makes sense since Keras automatically adds the first dimension for batch processing. However, the following code: x = k.layers.Input(shape=(2,)) y = k.layers.SimpleRNN(10)(x) m = k.models.Model(x, y) raises an exception ValueError: Input 0 is incompatible with layer simple_rnn_1: expected ndim=3, found ndim=2. It works only if I add another dimension: x = k.layers.Input(shape=(2,1)) y = k.layers.SimpleRNN(10)(x) m = k.models.Model(x, y) ...but now, of course, my input would not be (None, 2) anymore. model.summary(): _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) (None, 2, 1) 0 _________________________________________________________________ simple_rnn_1 (SimpleRNN) (None, 10) 120 ================================================================= How can I have an input of type batch_size x 2 when I just want to feed vectors with 2 values to the network? Furthermore, how would I chain RNN cells? x = k.layers.Input(shape=(2, 1)) h = k.layers.SimpleRNN(10)(x) y = k.layers.SimpleRNN(10)(h) m = k.models.Model(x, y) ...raises the same exception with incompatible dim sizes. This sample here works: x = k.layers.Input(shape=(2, 1)) h = k.layers.SimpleRNN(10, return_sequences=True)(x) y = k.layers.SimpleRNN(10)(h) m = k.models.Model(x, y) ...but then layer h does not output (None, 10) anymore, but (None, 2, 10) since it returns the whole sequence ins…

http://stackoverflow.com/comment/88195181
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50589747
score: 0
has text: @Rennitbaby It's allocated the same way in either case, but it isn't assigned to a variable so there is no reference once the function returns. In my example it is assigned to a variable so there is a reference keeping it from deallocating. Only when `tid` goes out of scope (if it was a local variable to a function, for example) or the reference is deleted (`del tid` for example) is the memory (potentially) freed. Exactly when the memory is released is implementation-defined, but if you don't have a reference to it as in your original example, you won't be able to retrieve the content.

http://stackoverflow.com/q/50575540
tagged with: numpy
has body: I have an image I've read from file with shape (m,n,3) (i.e. it has 3 channels). I also have a matrix to convert the color space with dimensions (3,3). I've already arrived at a few different ways of applying this matrix to each vector in the image; for example, np.einsum('ij,...j',transform,image) appears to make for the same results as the following (far slower) implementation. def convert(im: np.array, transform: np.array) -&gt; np.array: """ Convert an image array to another colorspace """ dimensions = len(im.shape) axes = im.shape[:dimensions-1] # Create a new array (respecting mutability) new_ = np.empty(im.shape) for coordinate in np.ndindex(axes): pixel = im[coordinate] pixel_prime = transform @ pixel new_[coordinate] = pixel_prime return new_ However, I found that the following is even more efficient while testing on the example image with line_profiler. np.moveaxis(np.tensordot(transform, X, axes=((-1),(-1))), 0, 2) The problem I'm having here is using just a np.tensordot, i.e. removing the need for np.moveaxis. I've spent a few hours attempting to find a solution (I'm guessing it resides in choosing the correct axes), so I thought I'd ask others for help.
score: 2
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/50575720
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88160734
tagged with: python
has comment: http://stackoverflow.com/comment/88160751
upvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/50575720
has comment: http://stackoverflow.com/comment/88160738
has comment: http://stackoverflow.com/comment/88160703
has title: Changing colorspaces with numpy.tensordot

http://stackoverflow.com/comment/88112320
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50550643
has text: are you sure you need to check if x *is* (the same object as) y ? maybe it's `if x == y` ?
score: 0

http://stackoverflow.com/comment/88340524
has text: Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50665240
type: QuestionComment

http://stackoverflow.com/q/50594521
score: 1
type: Question
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50611732
tagged with: python
has title: Where does pyramid store the auth_tkt session cookie at rest
has body: Where does Pyramid store the auth_tkt at rest? I'm trying to quantify how many open sessions my site currently has and I'm hoping I'm just blanking on what table it's being stored at.
has answer: http://stackoverflow.com/a/50594901
tagged with: pyramid
type: UnansweredQuestion
upvote count: 1

http://stackoverflow.com/comment/88273949
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50631760
type: Comment
has text: @yippiez Inefficient as spends too much CPU, too much memory, or too much of your time as a developer? If it is the last one, well, create a function which you will always call ;)

http://stackoverflow.com/comment/88276697
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50633124
score: 0
has text: "_why there is a difference between C++ and python_" Because they are 2 different languages and don't at all have to function exactly the same.

http://stackoverflow.com/comment/88102545
type: QuestionComment
comment on: http://stackoverflow.com/q/50545787
score: 0
type: Comment
has text: It did not work

http://stackoverflow.com/comment/88268626
score: 0
type: Comment
type: QuestionComment
has text: Thank you for your suggestion. I have tried calling `session.add(row)` but the program still throws exception after several hundreds of iterations.
comment on: http://stackoverflow.com/q/50623357

http://stackoverflow.com/comment/88196180
score: 0
has text: with @cdarke: `text = re.sub(reg, '', text, count=0, flags=re.MULTILINE)`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50593119

http://stackoverflow.com/q/50636059
type: UnansweredQuestion
tagged with: multithreading
has title: How to read / process large files in parallel with Python
has body: I have a large file almost 20GB, more than 20 mln lines and each line represents separate serialized JSON. Reading file line by line as a regular loop and performing manipulation on line data takes a lot of time. Is there any state of art approach or best practices for reading large files in parallel with smaller chunks in order to make processing faster? I'm using Python 3.6.X
tagged with: python
linked to: http://stackoverflow.com/q/18114285
has comment: http://stackoverflow.com/comment/88282115
has answer: http://stackoverflow.com/a/50636373
has comment: http://stackoverflow.com/comment/88282866
has answer: http://stackoverflow.com/a/50636561
upvote count: 5
has comment: http://stackoverflow.com/comment/88282589
type: Question
score: 5
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/73128224
has comment: http://stackoverflow.com/comment/129150773
answer count: 3
tagged with: python-3.x

http://stackoverflow.com/comment/88379636
score: 0
has text: yes, or append the child to the original dictionary
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50684578

http://stackoverflow.com/q/50632242
has comment: http://stackoverflow.com/comment/88275012
possible better answer: http://stackoverflow.com/a/50649928
has title: Get element with a randomized class name
tagged with: selenium
has comment: http://stackoverflow.com/comment/88276452
has answer: http://stackoverflow.com/a/50649928
tagged with: web-scraping
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88276398
has comment: http://stackoverflow.com/comment/88278684
has comment: http://stackoverflow.com/comment/88276542
has comment: http://stackoverflow.com/comment/88276711
has answer: http://stackoverflow.com/a/50632361
downvote count: 0
has comment: http://stackoverflow.com/comment/88276822
favorite count: 0
has comment: http://stackoverflow.com/comment/88274939
upvote count: 2
has comment: http://stackoverflow.com/comment/88276476
linked to: http://stackoverflow.com/q/2661818
has comment: http://stackoverflow.com/comment/88275096
tagged with: python
has body: It looks like the &lt;class id&gt; for &lt;img class&gt; on Instagram's web page is changing every day. Right now it is FFVAD and tomorrow it will be something else. For example (I made it shorter, links are long): &lt;img class="FFVAD" alt="Tag your best friend" decoding="auto" style="" sizes="293px" src="https://scontent-lax3-2.cdninstagram.com/vp/0436c00a3ac9428b2b8c977b45abd022/5BAB3EBC/t51.2885-15/s640x640/sh0.08/e35/33110483_592294374461447_8669459880035221504_n.jpg"&gt; By saying that, I need to fix the script and hardcode the Class ID in order to be able scrape the web-page. var = driver.find_elements_by_class_name('FFVAD') Somebody told me that I could use img.get_attribute('class') to find the class ID and store it for later. But I still don't understand how this can be achieved, so selenium or soup could grab the Class ID from the html tag and store or parse it later. All I got now is this. It's little dirty, and not right, but the idea is there. import requests import selenium.webdriver as webdriver url = ('https://www.instagram.com/kitties') driver = webdriver.Firefox() driver.get(url) last_height = driver.execute_script("return document.body.scrollHeight") while True: imgs_dedupe = driver.find_elements_by_class_name('FFVAD') for img in imgs_dedupe: posts = img.get_attribute('class') print posts driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(scroll_delay) new_height = driver.execute_script("return document.body.scrollHeight") if new_height == last_height: break last_height = new_height When I run it, I get this output, and because there are 3 images on the page, I get 3x Class ID python tag_print.py FFVAD FFVAD FFVAD
has comment: http://stackoverflow.com/comment/88276561
has comment: http://stackoverflow.com/comment/88275062
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50632361

http://stackoverflow.com/q/50637089
has answer: http://stackoverflow.com/a/50638540
has comment: http://stackoverflow.com/comment/88997124
has answer: http://stackoverflow.com/a/50659674
type: Question
has body: I want to update aws-sam-cli on my ubuntu 14.04. I have sam 0.2.11 version. I want to update in 0.3.0. When I run pip install --user aws-sam-cli or pip install --user --upgrade aws-sam-cli I got Downloading/unpacking aws-sam-cli Downloading aws-sam-cli-0.3.0.tar.gz (128kB): 128kB downloaded Running setup.py (path:/tmp/pip_build_amber/aws-sam-cli/setup.py) egg_info for package aws-sam-cli /usr/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'python_requires' warnings.warn(msg) error in aws-sam-cli setup command: 'install_requires' must be a string or list of strings containing valid project/version requirement specifiers Complete output from command python setup.py egg_info: /usr/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'python_requires' warnings.warn(msg) error in aws-sam-cli setup command: 'install_requires' must be a string or list of strings containing valid project/version requirement specifiers Cleaning up... Command python setup.py egg_info failed with error code 1 in /tmp/pip_build_amber/aws-sam-cli Storing debug log for failure in /home/amber/.pip/pip.log**
upvote count: 6
tagged with: amazon-web-services
has title: How to Install aws-sam-cli in ubuntu 14?
answer count: 3
has answer: http://stackoverflow.com/a/51549749
favorite count: 0
type: UnansweredQuestion
score: 6
tagged with: pip
tagged with: python
downvote count: 0

http://stackoverflow.com/q/50671746
upvote count: 18
answer count: 2
has comment: http://stackoverflow.com/comment/89322489
possible better answer: http://stackoverflow.com/a/63552421
downvote count: 0
tagged with: jetbrains-ide
has answer: http://stackoverflow.com/a/63552421
favorite count: 0
has comment: http://stackoverflow.com/comment/88385033
has title: PyCharm remote deployment: user name not being saved
tagged with: python
has answer: http://stackoverflow.com/a/51944689
type: AnsweredQuestion
tagged with: pycharm
has body: Working with Professional edition of PyCharm, I'm trying to configure a server for remote deployment of my project over SFTP with OpenSSH + authentication agent as auth type. I have tried to configure PyCharm in Settings &gt; Build, Execution and Deployment &gt; Add server. However, even though I setup and verify successful configuration by Test SFTP connection button, as soon as I click Apply or OK, the User name becomes blank for some reason. Thereafter, when I try to sync with the remote server, the connection fails. I've found a possible workaround by changing Host name to user@host form instead, which works, but then I can't use the same server configuration when I try to setup a remote interpreter under Project &gt; Project Interpreter &gt; Add SSH interpreter. (there it shows my host url as ssh://null@host). I'm guessing the null is there because PyCharm is somehow not saving the username. I've tried to edit the .idea/webServers.xml file, but couldn't find appropriate key-value pair to change there for user name to be preserved.
type: Question
score: 18
accepted answer: http://stackoverflow.com/a/51944689

http://stackoverflow.com/q/50548998
type: Question
downvote count: 0
answer count: 1
tagged with: amazon-web-services
has answer: http://stackoverflow.com/a/50549796
has body: I want to try to clone my git repository which is in a private github . I can see that after adding webhooks and set up cloud formation as described here. It is sending request to my lambda. I am able to clone the repository be below ways but not able to create zip of the repository and upload it to s3 as in Lambda I can not find where is it storing the repository to make it zip and upload it from that path. import boto3 from botocore.vendored import requests import logging import base64 import os import shutil from zipfile import ZipFile from cStringIO import StringIO # Set to False to allow self-signed/invalid ssl certificates verify = False logger = logging.getLogger() logger.setLevel(logging.INFO) s3_client = boto3.client('s3') def lambda_handler(event, context): path = "/gitpull" clone = "git clone https://username:pwd@site.com/scm/awsdemos/testrepo.git" # os.system("sshpass -p your_password ssh user_name@your_localhost") os.chdir(path) os.system(clone) # Cloning # folder = "/gitpull" # logger.info(os.listdir(folder)) # shutil.make_archive('Gitpull', 'zip', '/tmp') s3_archive_file = "Gitpull.zip" # Create zip from /tmp dir without any common prefixes shutil.make_archive('Gitpull', 'zip', os.getcwd()) logger.info("Uploading zip to S3://%s/%s" % ('gitpulls3', s3_archive_file)) s3_client.upload_file(os.getcwd(), 'gitpulls3', s3_archive_file) logger.info('Upload Complete') is there any good way I can do this?
tagged with: aws-lambda
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: git
score: 3
has title: AWS lambda clone git repository and make zip not able to upload in s3
tagged with: amazon-s3
upvote count: 3

http://stackoverflow.com/a/50547351
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50546540
answers question: http://stackoverflow.com/q/50546540
downvote count: 0
score: 1
has body: For each list, find the index of the maximum element Group the lists by that index Pick an arbitrary element from each group and put it into the result at the correct index Use the remaining elements to fill the empty slots in the result import operator import collections example_dict = {'unit1': [1, 4, 3], 'unit2': [2, 2, 2], 'unit3': [1, 1, 1]} # group the lists by the index of their maximum element lists_by_max_index = collections.defaultdict(list) for key, values in example_dict.items(): # find the index of the maximum element max_index, max_value = max(enumerate(values), key=operator.itemgetter(1)) # and store the key in the corresponding group lists_by_max_index[max_index].append(key) # list_by_max_index is now {1: ['unit1'], 0: ['unit2', 'unit3']} # make a list representing the sorted dict and initialize it to None sorted_keys = [None] * len(next(iter(example_dict.values()))) unused_keys = [] # sorted_keys is [None, None, None] # for each group in the dict we created earlier, put a random key into # the list for i, keys in lists_by_max_index.items(): sorted_keys[i] = keys.pop() unused_keys += keys # store the other keys for later # sorted_keys is now ['unit3', 'unit1', None] # iterate over the list and fill any empty slots with arbitrary unused keys for i, key in enumerate(sorted_keys): if key is None: sorted_keys[i] = unused_keys.pop() # sorted_keys is now ['unit3', 'unit1', 'unit2'] # finally, grab the corresponding value for each key and turn the whole thing # into an OrderedDict sorted_dict = [(key, example_dict[key]) for key in sorted_keys] sorted_dict = collections.OrderedDict(sorted_dict) print(sorted_dict) # output: # OrderedDict([('unit3', [1, 1, 1]), # ('unit1', [1, 4, 3]), # ('unit2', [2, 2, 2])]) Useful functions and classes I used: collections.defaultdict for grouping collections.OrderedDict to store the result operator.itemgetter as a key function for sorted iter and next to get an arbitrary element from a dict
has comment: http://stackoverflow.com/comment/88111631

http://stackoverflow.com/comment/99376667
type: QuestionComment
has text: Hi Neil, have you figured the question out? Thanks,
comment on: http://stackoverflow.com/q/50634375
score: 0
type: Comment

http://stackoverflow.com/comment/88219115
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50604740
has text: What code have you tried? What was the problem with it?

http://stackoverflow.com/q/50596286
has title: How to programmably get the metadata of all packages available from AUR in ArchLinux?
has comment: http://stackoverflow.com/comment/88203301
has answer: http://stackoverflow.com/a/50597461
has comment: http://stackoverflow.com/comment/88204141
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88203553
possible better answer: http://stackoverflow.com/a/72752056
has answer: http://stackoverflow.com/a/72752056
favorite count: 0
type: Question
upvote count: 2
has body: How to programmably get the metadata of all packages available from AUR in ArchLinux, including those not installed locally? Preferably in Python. I have tried AurJson, a set of APIs for accessing package metadata, but a minimum length of search keywords has to be provided to query package metadata.
tagged with: archlinux
accepted answer: http://stackoverflow.com/a/50597461
has comment: http://stackoverflow.com/comment/88201792
answer count: 2
tagged with: python
score: 0
downvote count: 2

http://stackoverflow.com/comment/88391057
has text: The parameter 'pbds120_NO_RSA' is db/schema name
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50686841

http://stackoverflow.com/comment/88190164
has text: duplicate of [Scoping in Python 'for' loops](https://stackoverflow.com/questions/3611760/scoping-in-python-for-loops)
comment on: http://stackoverflow.com/q/50590188
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50658035
has comment: http://stackoverflow.com/comment/88326223
type: UnansweredQuestion
has title: Error - UnboundLocalError at /home/ local variable 'team1_score' referenced before assignment
has body: Getting this error on django This is my views.py def post(self, request): form = BetForm(request.POST) if form.is_valid(): form.save() team1_score = form.cleaned_data.get('team1_score') team2_score = form.cleaned_data.get('team2_score') match = form.cleaned_data.get('match') form = BetForm() return redirect ('index') args = {'form': form, 'team1_score': team1_score, 'team2_score': team2_score, 'match': match} return render(request, self.template_name, args) This is my forms.py class BetForm(forms.ModelForm): team1_score = forms.IntegerField(min_value=0, max_value=15) team2_score = forms.IntegerField(min_value=0, max_value=15) class Meta: model = Bet fields = ('team1_score', 'team2_score', 'match') The error is on this line: args = {'form': form, 'team1_score': team1_score, 'team2_score':
score: -1
favorite count: 0
type: Question
downvote count: 2
tagged with: django
upvote count: 1
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/50659917

http://stackoverflow.com/a/50696692
answers question: http://stackoverflow.com/q/50695812
type: Answer
downvote count: 0
score: 1
has body: To handle numbers with float type, use this: Python 3.6.5 (default, Apr 1 2018, 05:46:30) Type 'copyright', 'credits' or 'license' for more information IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: from decimal import Decimal In [2]: s = "1+3+2+1+4+3+5+16+63.5+3" In [3]: nums = [Decimal(i) for i in s.replace(' ', '').split('+')] In [4]: d = 's = ' + '+'.join(str(i) for i in sorted(nums)) In [5]: d Out[5]: 's = 1+1+2+3+3+3+4+5+16+63.5'
upvote count: 1

http://stackoverflow.com/comment/88269503
comment on: http://stackoverflow.com/a/50629701
has text: This is a great idea for the data messages but I also require it to capture the page / part messages (as in example in question) Could I open the same file and write to that for the page/part messages?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/88262721
comment on: http://stackoverflow.com/q/50622856
type: Comment
score: 0
has text: i think i found the reason for this. This cited number is only available to the subscribers only. If you are not a subscriber, you will not see those numbers. I just realized this after I came back home. I can see those numbers using my university Internet access.However, I can still not scrape those data even if i'm using the university internet. Is this dynamic data?
type: QuestionComment

http://stackoverflow.com/comment/88351959
type: Comment
type: QuestionComment
has text: @Lemayzeur, wrong files were uploaded in online server. See now online.
score: 0
comment on: http://stackoverflow.com/q/50671066

http://stackoverflow.com/q/50546566
answer count: 1
accepted answer: http://stackoverflow.com/a/50546749
has body: I'm trying to apply preprocessing imported from a resnet50 module in Keras before propagating the images through the network. Since I got errors when trying to apply it in the generator object, I added it to the network as a lambda layer. But since the model was worse than one that I trained previously when I was applying preprocessing on each image separately, I compared the results of both approaches and they seem very different, although I can't see what's different about the applied operations. import keras from keras.preprocessing import image from keras.applications.resnet50 import preprocess_input model = keras.models.Sequential() model.add(keras.layers.Lambda(preprocess_input, name='preprocessing', input_shape=(224, 224, 3))) file = '/path/to/an/image.jpeg' x = np.array(image.img_to_array(image.load_img(file, target_size=(224, 224)))) preprocessed_x = preprocess_input(x) predicted_x = model.predict(x.reshape(1,224,224,3)).reshape(224,224,3) Results (left: preprocessing function used directly; right: preprocessing as a lambda layer.
score: 2
downvote count: 0
tagged with: keras
type: AnsweredQuestion
favorite count: 0
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/50546749
has title: Image preprocessing as a Keras lambda layer vs preprocessing on its own
tagged with: resnet
tagged with: python

http://stackoverflow.com/comment/88360852
score: 0
type: Comment
type: QuestionComment
has text: The problem is detecting that the connection is lost. raise socket.error("no data") is never reached. decoder_fp.readline() seems to block indefinitely when the connection drops.
comment on: http://stackoverflow.com/q/50675434

http://stackoverflow.com/q/50667714
type: Question
downvote count: 0
tagged with: pandas
score: 3
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I am analyzing the time series of an action (historical from 2000 to 2018). I want to be able to better analyze my time series (e.g. on a monthly, quarterly basis) by placing all the datetime data in a DatetimeIndex. How can I do it? Is it possible? df.columns Out[181]: Index(['Date', 'Price', 'Open', 'High', 'Low'], dtype='object') df.index Out[179]: RangeIndex(start=0, stop=4309, step=1) df.info [4309 rows x 5 columns]&gt; type(df) Out[178]: pandas.core.frame.DataFrame
has answer: http://stackoverflow.com/a/50667737
has title: From RangeIndex to DatetimeIndex
upvote count: 3

http://stackoverflow.com/comment/88276827
score: 0
comment on: http://stackoverflow.com/a/50633250
type: Comment
type: AnswerComment
has text: I'm not sure what you mean, but either way just throw it in an infinite loop and sleep it for 3600 seconds after you send the weather data.

http://stackoverflow.com/a/51144665
has body: I find an answer and it really works for me. See the accepted answer and change it to extension-pkg-whitelist=lxml pylint 1.4 reports E1101(no-member) on all C extensions
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50569453
upvote count: 3
has comment: http://stackoverflow.com/comment/105116861
downvote count: 1

http://stackoverflow.com/comment/88353926
has text: `url = "https://dogechain.info/api/v1/address/balance/{}".format(a)`
score: 1
comment on: http://stackoverflow.com/q/50672113
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88291318
score: 0
type: Comment
has text: I think you should post your template, otherwise i have no clue :(
type: AnswerComment
comment on: http://stackoverflow.com/a/50630140

http://stackoverflow.com/a/50564360
upvote count: 2
has comment: http://stackoverflow.com/comment/88139146
has body: I think need convert to float, because missing NaNs or Nones values have type float because in pandas is impossible convert NaNs to int per design: m = df['maturity_date'].str[:4].astype(float) &gt; 2261 Another solution is remove rows with NaNs or Nones first: df = df.dropna(subset=['maturity_date']) For check problematic rows use: df = df[df['maturity_date'].isnull()]
answers question: http://stackoverflow.com/q/50564331
has comment: http://stackoverflow.com/comment/88139130
accepted answer of: http://stackoverflow.com/q/50564331
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/q/50544788
has body: I'm writing a code that can read a data inside 2 dimensional array and then store the sum of each line in another 1 dimensional array. This is the code I'm using: n = 256 b = [[0]*n for p in range (n)] line = [] for k in range(1,4,256): for j in range(1,256,1): line[k] = line[k] + b[j][k] print line But I always get this error: list index out of range
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50544989
tagged with: arrays
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/88100635
score: 0
has answer: http://stackoverflow.com/a/50544989
answer count: 1
tagged with: sum
has comment: http://stackoverflow.com/comment/88100553
has title: Line's sum of 2 dimensional array python

http://stackoverflow.com/q/50648853
linked to: http://stackoverflow.com/q/1305532
has comment: http://stackoverflow.com/comment/88309392
type: AnsweredQuestion
has title: Difference between dict attributes and dict
tagged with: attributes
has comment: http://stackoverflow.com/comment/88309583
type: Question
has comment: http://stackoverflow.com/comment/88309538
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/88308609
has comment: http://stackoverflow.com/comment/88309051
score: 0
has body: This is from the fastai library. So this function call: md = ColumnarModelData(PATH, ColumnarDataset.from_data_frame(trn_df, cat_flds=cat_vars, y=trn_y), ColumnarDataset.from_data_frame(val_df, cat_flds=cat_vars, y=val_y), bs=128, test_ds=test_ds) vars(md) Gives this result: {'path': 'data/rossmann/', 'test_dl': &lt;fastai.dataloader.DataLoader at 0x112c93d68&gt;, 'trn_dl': &lt;fastai.dataloader.DataLoader at 0x112c93e80&gt;, 'val_dl': &lt;fastai.dataloader.DataLoader at 0x112c93a20&gt;} But I can build the same result by doing: md = {'path':PATH, 'test_dl':DataLoader(test_ds, batch_size=128, shuffle=False, num_workers=1), 'trn_dl':DataLoader(trn_df, batch_size=128, shuffle=False, num_workers=1), 'val_dl':DataLoader(val_df, batch_size=128*2, shuffle=False, num_workers=1)} md Which gives: {'path': 'data/rossmann/', 'test_dl': &lt;fastai.dataloader.DataLoader at 0x1c20e9cc88&gt;, 'trn_dl': &lt;fastai.dataloader.DataLoader at 0x1c20d5f8d0&gt;, 'val_dl': &lt;fastai.dataloader.DataLoader at 0x1c20d5f320&gt;} However they behave very differently when trying to use them in other functions. As in: m = StructuredLearner(md, StructuredModel(to_gpu(model)), opt_fn=optim.Adam) This runs fine when I use the initial method of md = ColumnarModelData() but does not work when I build it on my own, gives this error: AttributeError: 'dict' object has no attribute 'path' What exactly is going wrong here?
has answer: http://stackoverflow.com/a/50649645
answer count: 1
has comment: http://stackoverflow.com/comment/88309140
has comment: http://stackoverflow.com/comment/88309445
has comment: http://stackoverflow.com/comment/88308551
accepted answer: http://stackoverflow.com/a/50649645
has comment: http://stackoverflow.com/comment/88309669

opencv
type: Tag
tags question: http://stackoverflow.com/q/50545787
tags question: http://stackoverflow.com/q/50552007
tags question: http://stackoverflow.com/q/50565610
tags question: http://stackoverflow.com/q/50665030
tags question: http://stackoverflow.com/q/50684393
tags question: http://stackoverflow.com/q/50599702
tags question: http://stackoverflow.com/q/50630045
tags question: http://stackoverflow.com/q/50667644
tags question: http://stackoverflow.com/q/50678519
tags question: http://stackoverflow.com/q/50605924
tags question: http://stackoverflow.com/q/50551439
tags question: http://stackoverflow.com/q/50673055
tags question: http://stackoverflow.com/q/50576487
tags question: http://stackoverflow.com/q/50630825
tags question: http://stackoverflow.com/q/50588175
tags question: http://stackoverflow.com/q/50552327
tags question: http://stackoverflow.com/q/50668212
tags question: http://stackoverflow.com/q/50674051
tags question: http://stackoverflow.com/q/50669984
tags question: http://stackoverflow.com/q/50585533
tags question: http://stackoverflow.com/q/50670326
tags question: http://stackoverflow.com/q/50671524
tags question: http://stackoverflow.com/q/50595573
tags question: http://stackoverflow.com/q/50559105
tags question: http://stackoverflow.com/q/50694192
tags question: http://stackoverflow.com/q/50672666
tags question: http://stackoverflow.com/q/50562755
tag name: opencv
tags question: http://stackoverflow.com/q/50567727
tags question: http://stackoverflow.com/q/50623735
tags question: http://stackoverflow.com/q/50547916
tags question: http://stackoverflow.com/q/50678194
tags question: http://stackoverflow.com/q/50660532
tags question: http://stackoverflow.com/q/50649776
tags question: http://stackoverflow.com/q/50601275
tags question: http://stackoverflow.com/q/50670024
tags question: http://stackoverflow.com/q/50579050
tags question: http://stackoverflow.com/q/50680293
tags question: http://stackoverflow.com/q/50558627
tags question: http://stackoverflow.com/q/50632275
tags question: http://stackoverflow.com/q/50659212
tags question: http://stackoverflow.com/q/50627548
tags question: http://stackoverflow.com/q/50644073
tags question: http://stackoverflow.com/q/50672758
tags question: http://stackoverflow.com/q/50586226
tags question: http://stackoverflow.com/q/50595727
tags question: http://stackoverflow.com/q/50659698
tags question: http://stackoverflow.com/q/50630103
tags question: http://stackoverflow.com/q/50568668
tags question: http://stackoverflow.com/q/50664425
tags question: http://stackoverflow.com/q/50581260
tags question: http://stackoverflow.com/q/50545343
tags question: http://stackoverflow.com/q/50553262
tags question: http://stackoverflow.com/q/50660947
tags question: http://stackoverflow.com/q/50560896
tags question: http://stackoverflow.com/q/50656167
tags question: http://stackoverflow.com/q/50641240
tags question: http://stackoverflow.com/q/50697077
tags question: http://stackoverflow.com/q/50610223
tags question: http://stackoverflow.com/q/50639655
tags question: http://stackoverflow.com/q/50630769
tags question: http://stackoverflow.com/q/50631195
tags question: http://stackoverflow.com/q/50603978
tags question: http://stackoverflow.com/q/50548556
tags question: http://stackoverflow.com/q/50591068
tags question: http://stackoverflow.com/q/50642057
tags question: http://stackoverflow.com/q/50653773
tags question: http://stackoverflow.com/q/50675459
tags question: http://stackoverflow.com/q/50692502
tags question: http://stackoverflow.com/q/50683157
tags question: http://stackoverflow.com/q/50564242
tags question: http://stackoverflow.com/q/50665262
tags question: http://stackoverflow.com/q/50684329
tags question: http://stackoverflow.com/q/50572891
tags question: http://stackoverflow.com/q/50616986
tags question: http://stackoverflow.com/q/50664746
tags question: http://stackoverflow.com/q/50617991
tags question: http://stackoverflow.com/q/50551410
tags question: http://stackoverflow.com/q/50550654

http://stackoverflow.com/q/50687651
type: UnansweredQuestion
tagged with: machine-learning
has body: I have 12 classes(images) and uneven distributed data in each of these classes. They are as follows(all images): X1 = 16 X2 = 203 X3 = 192 X4 = 220 X5 = 172 X6 = 143 X7 = 22 X8 = 89 X9 = 31 X10 = 89 X11 = 10 X12 = 204 I am trying to train a CNN using the given datset. I want to know whether should I apply data augmentation to only the classes having less data or to all of the classes? Has anyone trained a similar model as mine? Also, what architecture of CNN should I use? I have used this(by applying data augmentation to all classes), but I stopped since the accuracy was around 14%(I stopped in between the first epoch) model = Sequential() model.add(Conv2D(32, (3, 3), input_shape=input_shape)) # input_shape = (150,150) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(32, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(64, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(64)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(12)) model.add(Activation('sigmoid')) Any help would be appreciated. If anyone has any tips, I would like to hear some. It's giving me a hard time lately.
score: 3
tagged with: conv-neural-network
has answer: http://stackoverflow.com/a/50694965
linked to: http://stackoverflow.com/q/45666675
type: Question
answer count: 1
tagged with: neural-network
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/88387466
upvote count: 3
tagged with: python
has title: How to use data augmentation on uneven multiclass dataset?
downvote count: 0

http://stackoverflow.com/q/50576470
has title: Select rows which have only zeros in columns
has body: I want to select the rows in a dataframe which have zero in every column in a list of columns. e.g. this df:. In: df = pd.DataFrame([[1,2,3,6], [2,4,6,8], [0,0,3,4],[1,0,3,4],[0,0,0,0]],columns =['a','b','c','d']) df Out: a b c d 0 1 2 3 6 1 2 4 6 8 2 0 0 3 4 3 1 0 3 4 4 0 0 0 0 Then: In: mylist = ['a','b'] selection = df.loc[df['mylist']==0] selection I would like to see: Out: a b c d 2 0 0 3 4 4 0 0 0 0 Should be simple but I'm having a slow day!
score: 4
has comment: http://stackoverflow.com/comment/88162193
upvote count: 4
answer count: 2
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/50576528
favorite count: 0
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50576753
has comment: http://stackoverflow.com/comment/88162157
has answer: http://stackoverflow.com/a/50576753
accepted answer: http://stackoverflow.com/a/50576528
tagged with: dataframe
type: Question
has comment: http://stackoverflow.com/comment/88162120

http://stackoverflow.com/q/50634982
tagged with: image
score: 0
has body: I'm trying to add an image to the top frame so the image appears above the Label Frame, but for some reason, I can't get it to appear. The code will run but I never get the image to display once the GUI starts up. Please help. import tkinter as tk import tkinter as ttk from PIL import ImageTk,Image class Calc(tk.Tk): def __init__(self,*args,**kwargs): tk.Tk.__init__(self,*args,**kwargs) tk.Tk.iconbitmap(self,default='smile.ico') tk.Tk.wm_title(self,"Name") frame = tk.Frame(self,width = 50,height = 50,pady =3) frame.grid(row=0,column=0) label_frame = ttk.LabelFrame(self,text = "Calculator",width = 50,height = 100) label_frame.grid(row=3, column=0, columnspan=2, rowspan=10, \ sticky='NS', padx=5, pady=5) # Image Logo img = ImageTk.PhotoImage(Image.open('Hercu.jpg')) panel = tk.Label(frame,image = img, width = 50, height = 50) panel.grid(row=0,column=0) text1 = ttk.Entry(label_frame) text1.grid(row=1,column=1) label1 = ttk.Label(label_frame,text = 'Number of Windows') label1.grid(row=1,column=2,sticky='w') text2 = ttk.Entry(label_frame) text2.grid(row=2,column=1) label2 = ttk.Label(label_frame,text = 'Number of Doors') label2.grid(row=2,column=2,sticky='w') text3 = ttk.Entry(label_frame) text3.grid(row=3,column=1) label3 = ttk.Label(label_frame,text = 'Number of Shear Walls') label3.grid(row=3,column=2,sticky='w') text4 = ttk.Entry(label_frame) text4.grid(row=4,column=1) label4 = ttk.Label(label_frame,text = 'Plate Height') label4.grid(row=4,column=2,sticky='w') text5 = ttk.Entry(label_frame) text5.grid(row=5,column=1) label5 = ttk.Label(label_frame,text = 'Laminated') label5.grid(row=5,column=2,sticky='w') text6 = ttk.Entry(label_frame) text6.grid(row=6,column=1) label6 = ttk.Label(label_frame,text = 'Painted') label6.grid(row=6,column=2,sticky='w') text7 = ttk.Entry(label_frame) text7.grid(row=7,column=1) label7 = ttk.Label(label_frame,text = 'Number of Billets') label7.grid(row=7,column=2,sticky='w') text8 = ttk.Entry(label_frame) text8.grid(row=8,column=1) label8 =…
tagged with: frame
has comment: http://stackoverflow.com/comment/88280319
tagged with: python
has title: How to add an image to a Frame with a grid?
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
tagged with: grid
has comment: http://stackoverflow.com/comment/88280191
type: Question

http://stackoverflow.com/comment/88188026
type: AnswerComment
has text: @Tapasya.A, Ok. I this moment I am busy but later I will add an explaining.
score: 0
comment on: http://stackoverflow.com/a/50589053
type: Comment

http://stackoverflow.com/q/50652687
tagged with: tweepy
score: 4
has body: I have a python program that searches twitter for a word and counts all mentions of that word. However, I've run into an odd problem and I can't find an answer elsewhere. I'm getting a "AttributeError: 'MyStreamListener' object has no attribute 'api'" error. This is the first time I've seen this error. Any suggestions on how to fix? Code: from tweepy import OAuthHandler import tweepy from tweepy import StreamListener from tweepy import Stream import time consumer_key = 'super secret consumer key' consumer_secret = 'Please help Ive been stuck with this error for days' access_token = 'Im so desperate' access_secret = 'I suck at coding please help' auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) api = tweepy.API(auth) print('') class MyStreamListener(tweepy.StreamListener): def __init__(self): #initializes the counter self.counter = 0 def on_status(self, status): #prints status text. Also counts the mentions. self.counter = self.counter + 1 print(status.text) def on_error(self, status_code): if status_code == 420: print('420 error') #Ends stream in case of rate limiting return False myStreamListener = MyStreamListener() myStream = tweepy.Stream(auth = api.auth, listener = myStreamListener) #Word myStream.filter(track=['Warriors'])
type: Question
has title: "AttributeError: 'MyStreamListener' object has no attribute 'api'" tweepy error
upvote count: 4
has answer: http://stackoverflow.com/a/51302550
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50560495
has comment: http://stackoverflow.com/comment/88131795
tagged with: python
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/88131446
score: 1
type: Question
has body: Mt. Everest is the highest peak in the world. It's height is 8848 m. How do I split this into two sentences? and not split it on the dot besides 'Mt'? Rule is whenever Mt is followed by a dot, it needs to skip that. Something like this: Mt. Everest is the highest peak in the world. It's height is 8848 m. Code so far data = "Mt. Everest is the highest peak in the world. It's height is 8848 m." sentences=data.split(".") print (sentences)
has title: Splitting with exception in python
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/50560574
accepted answer: http://stackoverflow.com/a/50560574
favorite count: 0

http://stackoverflow.com/comment/88389488
type: Comment
has text: Ok I fixed this by making sure the module name in my bindings macro, matches the module name in the CMakeLists.txt file.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50688379

http://stackoverflow.com/q/50673113
has comment: http://stackoverflow.com/comment/88355943
has comment: http://stackoverflow.com/comment/88356167
score: 0
has title: How to test all the links in footer of any given webpage
upvote count: 1
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88355968
favorite count: 0
has answer: http://stackoverflow.com/a/50673188
tagged with: python
type: UnansweredQuestion
has body: I want to test all the link in a footer section of any given webpage. Ex: &lt;footer id="globalfooter"&gt; &lt;a href="www.abc.com/xyz"&gt; &lt;div&gt; &lt;a href="www.google.com/abc"&gt; &lt;/div&gt; &lt;div&gt; &lt;a href="www.linkedin.com/abc"&gt; &lt;/div&gt; &lt;a href="www.facebook.com/abc"&gt; &lt;/footer&gt; the program should return all the 4 links in the footer section. I appreciate all the given help in advance. This is the code I have tried: from selenium import webdriver import requests chrome_path = "/Users/tanmaykale/Downloads/chromedriver" driver = webdriver.Chrome(chrome_path) # -----------Getting footer content of apple.com------------ driver.get("http://www.apple.com") footer = driver.find_element_by_tag_name('footer') print footer elems = footer.find_element_by_tag_name('div') linkscount = len(elems) print "Total No of link in footer of www.apple.com are : ",linkscount The code returns the following: linkscount = len(elems) TypeError: object of type 'WebElement' has no len()
tagged with: selenium
has comment: http://stackoverflow.com/comment/88355933
type: Question

http://stackoverflow.com/q/50602508
has body: I have a list which has a lot of URLs , thousands of urls. Here is the example UrlList = ["www.test.com", "www.123.com", "www.youtube.com", "youtube.com", 123.com, test.com, c.microsoft.com, office.microsoft.com] There are urls which doesn't have .com or www. or http:// or https:// and there are which does. I'm trying to ignore all that and just searching for test or youtube or microsoft etc in the URL List, once it is found print the whole URL. How can i do this? Edit : Sorry i forgot to post the attempt Attempt 1#: Code for Attempt 1#: fileURLs = urlReader() print("Here is the URLs in the File which needs to be search in the List.") print(fileURLs) for x in data: for y in x['urls']: url = str(y) if url in fileURLs: print(x['id'] , url) Output for Attempt 1#: Here is the URLs in the File which needs to be search in the List ['youtube.com', 'test.com', '123.com'] (u'CUSTOM_03', 'test.com') (u'CUSTOM_05', 'youtube.com') (u'CUSTOM_07', 'test.com') (u'CUSTOM_07', 'youtube.com') (u'CUSTOM_08', 'youtube.com') (u'CUSTOM_15', 'test.com') (u'CUSTOM_16', 'test.com') (u'CUSTOM_17', 'test.com') (u'CUSTOM_18', 'test.com') (u'CUSTOM_19', 'test.com') (u'CUSTOM_20', 'youtube.com') (u'CUSTOM_23', 'test.com') (u'CUSTOM_24', 'youtube.com') Code for Attempt 2#: for x in data : for s in x['urls']: url = str(s) matching = [y for y in fileURLs if url in y] if (matching): print(x['id'], x['configuredName'], matching) Output for Attempt 2#: Here is the URLs in the File which needs to be search in the List. ['www.youtube.com', 'www.test.com', 'www.123.com'] (u'CUSTOM_03', ['www.test.com']) (u'CUSTOM_03', ['www.test.com']) (u'CUSTOM_05', ['www.youtube.com']) (u'CUSTOM_07', ['www.test.com']) (u'CUSTOM_07', ['www.youtube.com']) (u'CUSTOM_08', ['www.youtube.com']) (u'CUSTOM_10', ['www.youtube.com']) (u'CUSTOM_15', ['www.test.com']) (u'CUSTOM_16', ['www.test.com']) (u'CUSTOM_17', ['www.test.com']) (u'CUSTOM_18', ['www.test.com']) (u'CUSTOM_19', ['www.test.com']) (u'CUSTOM_20', ['www.youtube.com'…
has answer: http://stackoverflow.com/a/50602543
answer count: 2
has title: Python - Searching a String in a list
has comment: http://stackoverflow.com/comment/88214151
score: -5
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/88215851
tagged with: python
downvote count: 6
type: UnansweredQuestion
upvote count: 1
type: Question
tagged with: list
has answer: http://stackoverflow.com/a/50603435
has comment: http://stackoverflow.com/comment/88242972

http://stackoverflow.com/q/50660606
has comment: http://stackoverflow.com/comment/88331422
tagged with: python
has comment: http://stackoverflow.com/comment/88331401
type: AnsweredQuestion
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/65353604
has body: I'm having trouble with this problem that simply return True of False if a number n, is a palindrome. Note: wherever I have a ____ indicates where there is a blank that needs to be filled in. There are 2 blank spaces. def is_palindrome(n): x, y = n, 0 f = lambda: ____ while x &gt; 0: x, y = ____ , f() return y == n I've spent about an hour on this. I've found out that putting x//10 in the second blank space will allow the function to iterate over the number of digits in n. It then comes down to the function f. Ideally, every time it is called, it should add the last digit in n to a new number, y. Thus, if n = 235, the while loop will iterate 3 times, and each time f() is called, it should add 5, 3, and 2, to the value y.
score: 7
has answer: http://stackoverflow.com/a/50660737
has answer: http://stackoverflow.com/a/65353604
has title: Check if a number is a palindrome without changing it into string
answer count: 3
has answer: http://stackoverflow.com/a/74981962
tagged with: palindrome
tagged with: iteration
favorite count: 0
upvote count: 8
accepted answer: http://stackoverflow.com/a/50660737

http://stackoverflow.com/comment/88150640
comment on: http://stackoverflow.com/q/50555232
has text: Thank you for your concern, @jpmc26. I spared god the trouble of having mercy on people other than myself in this case. As I said already, I'm experimenting with the language to understand it better.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50557145
score: 0
has title: "Python3 not found" error when deploying docker image to heroku
has body: So I'm trying to deploy my django powered web app to heroku using my docker file, But I keep getting a "python3 not found" error. Note that I've deployed this same application using zeit's now. My dockerfile looks like so: FROM mhart/alpine-node RUN echo "ipv6" &gt;&gt; /etc/modules RUN echo "http://nl.alpinelinux.org/alpine/v3.7/community" &gt;&gt; /etc/apk/repositories RUN apk add --no-cache python3 yarn &amp;&amp; python3 -m ensurepip RUN mkdir /code WORKDIR /code COPY . /code RUN pip3 install -r requirements.txt RUN yarn RUN yarn build:dev EXPOSE $PORT CMD [python3 manage.py runserver 0.0.0.0:$PORT ] I've also attached a screenshot of my application's logs on heroku. I tried adding the full path to the python3 package like so /usr/bin/python3 but it still failed. Any help would be appreciated
has comment: http://stackoverflow.com/comment/88132777
tagged with: python
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: django
tagged with: heroku
has comment: http://stackoverflow.com/comment/88125144
type: Question
has comment: http://stackoverflow.com/comment/88137346
tagged with: docker

http://stackoverflow.com/a/50666529
accepted answer of: http://stackoverflow.com/q/50666335
has body: Correct use of subclassing needs to obey the following substitution principle: If there are some objects x_1 of type T_1 and x_2 of type T_2 such that issubclass(T_2, T_1) == True, then any property that applies to x_1 must also apply for x_2. In other words, you expect subclassing to implement new behaviours, not to change existing behaviours. In you example, the change of coordinate system itself is a change of behaviour and thus HexCell should not inherit from Cell. What you can do is create a base class BaseCell that encapsulates the common behaviour between Cell and HexCell and inherit from it. class BaseCell: def __init__(self): self.links = set() self.neighbors = [] def add_neighbor(self, other): self.neighbors.append(other) def link(self, other, bidirectional=True): self.links.add(other) if bidirectional: other.link(self, bidirectional=False) class Cell(BaseCell): def __init__(self, row_loc, col_loc): self.row = row_loc self.col = col_loc super().__init__() def __repr__(self): return f'Cell @({self.row},{self.col})' class HexCell(Cell): def __init__(self, r_out, th_around): self.hex_r = r_out self.hex_th = th_around super().__init__() def __repr__(self): return f"HexCell @[{self.hex_r}, {self.hex_th}]" def bind(self, other, to_dir): ...
score: 3
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50666335
upvote count: 3

http://stackoverflow.com/comment/88442094
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50677690
has text: q1) I recommend you use the built-in postgis functions to create points, such as: `SELECT ST_SetSRID(ST_MakePoint(-4.4427,36.7233),4326);` (the same point in Malaga), so that you can be sure that the result is exactly what other functions would expect. q2) If the function is returning `true` it means that all points are inside the given polygon. Can you share the _fixed_ polygon for me to take a look?
type: Comment

http://stackoverflow.com/a/74777645
downvote count: 0
has body: The only way works for me is to set xunits to the desired order import pandas as pd import matplotlib.pyplot as plt from matplotlib.category import UnitData TestData = pd.DataFrame({'value':[1,2,5,3,5,6,8,9,8,1,2,8,9], 'Month':['Jan','Mar','Jan','Feb','May','Apr','Jan','Mar','Jan','Feb','May','Apr','May']}) fig, (ax1, ax2) = plt.subplots(1,2, figsize=(8, 4)) # Applying custom categorical order MonthLabels = ['Jan','Feb','Mar','Apr','May'] bar1 = ax1.bar('Month','value', data=TestData) # set xunits with UnitData bar2 = ax2.bar('Month','value', data=TestData, xunits=UnitData(MonthLabels))
answers question: http://stackoverflow.com/q/50543055
upvote count: 3
type: Answer
score: 3

http://stackoverflow.com/q/50602710
has comment: http://stackoverflow.com/comment/88218960
type: AnsweredQuestion
has body: Need to convert the time 00:00:00 of each day to epoch time, below is the code I have: import datetime today = datetime.datetime.now() today_morning = today.strftime('%y%m%d') + "000000" epoch = int(today_morning.strftime('%s')) print(epoch) I get the following error: AttributeError: 'str' object has no attribute 'strftime' If anyone has any advice, please share it. I have looked around at other answers, but they seem to be for Python 2.X and for the current time, not a predetermined time. I am looking for Python 3.X answers.
accepted answer: http://stackoverflow.com/a/50603747
score: 1
type: Question
upvote count: 4
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50603747
tagged with: epoch
tagged with: datetime
tagged with: python
linked to: http://stackoverflow.com/q/11743019
has title: Convert a set datetime to epoch time
tagged with: python-3.x
downvote count: 3
has comment: http://stackoverflow.com/comment/88214648

http://stackoverflow.com/comment/88199432
type: Comment
comment on: http://stackoverflow.com/a/50594985
score: 0
type: AnswerComment
has text: I learnt something new everyday on this platform thanks to you guys! Really appreciate it.

http://stackoverflow.com/q/50672300
has body: How can I save screenshot for each slide in pptx when use python-pptx package. I have read python-pptx.readthedocs.io and find some tips maybe help, but still could not make it work.
answer count: 1
favorite count: 0
has title: How to take save screenshot for each slide in pptx
upvote count: 2
has comment: http://stackoverflow.com/comment/94161662
type: UnansweredQuestion
tagged with: python-pptx
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/89304685
type: Question
has comment: http://stackoverflow.com/comment/94161758
linked to: http://stackoverflow.com/q/27150518
linked to: http://stackoverflow.com/q/48455680
has answer: http://stackoverflow.com/a/53773058
has comment: http://stackoverflow.com/comment/94161918
downvote count: 0

http://stackoverflow.com/comment/88344022
score: 0
type: Comment
type: QuestionComment
has text: Ok, well this is the first I have heard of flask 'debug mode' but when everything is looking good will probably take those two lines out again before deploying on a server.
comment on: http://stackoverflow.com/q/50666852

http://stackoverflow.com/comment/88257712
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50623915
has text: @nandal Thank you, I've just updated my post with examples.

http://stackoverflow.com/comment/88389408
score: 1
comment on: http://stackoverflow.com/a/50688981
type: AnswerComment
type: Comment
has text: Excellent answer. I can't believe this isn't a mega-dupe.

turtle-graphics
tags question: http://stackoverflow.com/q/50608037
tag name: turtle-graphics
tags question: http://stackoverflow.com/q/50542019
type: Tag
tags question: http://stackoverflow.com/q/50591845
tags question: http://stackoverflow.com/q/50655768
tags question: http://stackoverflow.com/q/50654793
tags question: http://stackoverflow.com/q/50633101
tags question: http://stackoverflow.com/q/50654490
tags question: http://stackoverflow.com/q/50546402
tags question: http://stackoverflow.com/q/50664086
tags question: http://stackoverflow.com/q/50663775
tags question: http://stackoverflow.com/q/50671528
tags question: http://stackoverflow.com/q/50548821
tags question: http://stackoverflow.com/q/50586171

http://stackoverflow.com/comment/88226871
type: Comment
type: QuestionComment
has text: You may need to adjust for the last row inequality
comment on: http://stackoverflow.com/q/50608418
score: 0

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

http://stackoverflow.com/a/50637638
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/88352184
accepted answer of: http://stackoverflow.com/q/50636902
has body: Just replace \s by \b: import re lines = [ "R_d_10763 VDDI_1007 Group_BGA_BGA_VDD_INT_AD26 3.711438e+000", "R_d_10771 VDDI_1007 VDDI_1012 1.337785e+001", "R_d_8607 Group_BGA_BGA_VSS_AH6 Group_BGA_BGA_VSS_AJ43 3.777161e+000", "R_d_6585 Group_BGA_BGA_AVDD085_MIPI_DPHY_Y36 Group_BGA_BGA_AVDD085_MIPI_DPHY_W35_SINK_ 3.860682e-003", "R_d_69804 Xm4s4s2_M_DPDATA0_580 Group_BGA_BGA_XMIPI_DSI_D0_P_V38_SINK_ 2.668494e-001", "R_d_69668 XCP_ANT_SW1_383 Group_BGA_BGA_XCP_ANT_SW1_N5_SINK_ 5.037550e-001", "R_d_13 AVDD085_MIPI_DPHY_540 Group_BGA_BGA_AVDD085_MIPI_DPHY_Y36 2.854267e-002", ] for line in lines: conn1, conn2, res = line.split()[1:] match1 = re.search(r"(A?[A-Z][0-9]{1,2})(?:_SINK|\b)", conn1) match2 = re.search(r"(A?[A-Z][0-9]{1,2})(?:_SINK|\b)", conn2) try: conn1 = match1.group(1) except AttributeError: pass try: conn2 = match2.group(1) except AttributeError: pass print(f"Connection 1: {conn1} Connection 2: {conn2} Resistance: {res}") Output: Connection 1: VDDI_1007 Connection 2: AD26 Resistance: 3.711438e+000 Connection 1: VDDI_1007 Connection 2: VDDI_1012 Resistance: 1.337785e+001 Connection 1: AH6 Connection 2: AJ43 Resistance: 3.777161e+000 Connection 1: Y36 Connection 2: W35 Resistance: 3.860682e-003 Connection 1: Xm4s4s2_M_DPDATA0_580 Connection 2: V38 Resistance: 2.668494e-001 Connection 1: XCP_ANT_SW1_383 Connection 2: N5 Resistance: 5.037550e-001 Connection 1: AVDD085_MIPI_DPHY_540 Connection 2: Y36 Resistance: 2.854267e-002
answers question: http://stackoverflow.com/q/50636902
score: 0

http://stackoverflow.com/a/50603862
downvote count: 0
answers question: http://stackoverflow.com/q/50599003
type: Answer
has body: Maybe you are looking for django-push-notifications
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88220092

http://stackoverflow.com/comment/88357976
type: Comment
type: QuestionComment
has text: Invalid _HTML_, only one ` ` starting tag while 3 ` ` ending tags
score: 0
comment on: http://stackoverflow.com/q/50674141

http://stackoverflow.com/q/50549536
answer count: 1
score: 1
favorite count: 0
has body: I have a problem with my code. So I'm trying to make a TicTacToe game but I want the computer to choose a box to put his marker. I already did the code where the user can put his marker but I cant fix the problem where it doesn't choose a box for the computers marker. You can see my code here. Y1, Y2, Y3.... etc are all functions for when you click the button it changes it. C1, C2, C3.... etc are all codes for the computer to put his marker. import tkinter as tk from tkinter import messagebox import random one_flag= True two_flag= True three_flag= True four_flag= True five_flag= True six_flag= True seven_flag= True eight_flag= True nine_flag= True pk = tk.Tk() frame = tk.Frame(pk) frame.grid() def X(): print("test") def Y1(): global one_flag if one_flag: print("Your Marker Is Now On This Square") one.config(text="X",fg='red') one_flag = False def Y2(): global two_flag if two_flag: print("Your Marker Is Now On This Square") two.config(text="X",fg='red') two_flag = False def Y3(): global three_flag if three_flag: print("Your Marker Is Now On This Square") three.config(text="X",fg='red') three_flag = False def Y4(): global four_flag if four_flag: print("Your Marker Is Now On This Square") four.config(text="X",fg='red') four_flag = False def Y5(): global five_flag if five_flag: print("Your Marker Is Now On This Square") five.config(text="X",fg='red') five_flag = False def Y6(): global six_flag if six_flag: print("Your Marker Is Now On This Square") six.config(text="X",fg='red') six_flag = False def Y7(): global seven_flag if seven_flag: print("Your Marker Is Now On This Square") seven.config(text="X",fg='red') seven_flag = False def Y8(): global eight_flag if eight_flag: print("Your Marker Is Now On This Square") eight.config(text="X",fg='red') eight_flag = False def Y9(): global nine_flag if nine_flag: print("Your Marker Is Now On This Square") nine.config(text="X",fg='red') nine_flag = False def C1(): global one_flag if one_flag: print("The Computer's Marker Is Now On…
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51857956
tagged with: python
tagged with: tkinter
has comment: http://stackoverflow.com/comment/88110334
upvote count: 2
tagged with: loops
has comment: http://stackoverflow.com/comment/88116682
downvote count: 1
has comment: http://stackoverflow.com/comment/88110086
has comment: http://stackoverflow.com/comment/88112300
type: Question
has title: Tkinter Can't Call Function ( TicTacToe in tkinter)
tagged with: function
has comment: http://stackoverflow.com/comment/88164179

http://stackoverflow.com/a/50578329
answers question: http://stackoverflow.com/q/50577790
score: 1
upvote count: 1
has body: In the general case, there is no way to tell whether a character in a path is correct or not without externally checking the actual paths on your computer (and "special character" is not really well-defined; how do you know that the path wasn't \0x41 which got converted to A anyway?) As a weak heuristic, you could look for path names within a particular editing distance, for example. import os from difflib import SequenceMatcher as similarity # or whatever path_components = os.path.split(variable) path = '' for p in path_components: npath = os.path.join(path, p) if not os.path.exists(npath): similar = reversed(sorted([(similarity(None, x, p).ratio(), x) in os.listdir(npath)])) # recurse on most similar, second most similar, etc? or something path = npath
downvote count: 0
type: Answer

http://stackoverflow.com/a/50657399
has body: You could group by both s and tokenID and aggregate like so: def aggregate(df): token = " ".join(df.token) pred = df.iloc[0].pred.split("-", 1)[1] return pd.Series({"token": token, "pred": pred}) df.groupby(["s", "tokenID"]).apply(aggregate) # Output token pred s tokenID 17 3 hakawati theatre Loc 7 jerusalem Loc 56 5 university of texas Org 6 here Org 5402 1 dwight d. eisenhower Peop
answers question: http://stackoverflow.com/q/50657239
score: 0
type: Answer

http://stackoverflow.com/a/65532991
answers question: http://stackoverflow.com/q/50652587
has body: I solved this problem by just changing the PASSWORD field in the settings.py (DATABASES dict) to password.
score: 0
type: Answer

http://stackoverflow.com/comment/88190102
comment on: http://stackoverflow.com/q/50587012
type: Comment
type: QuestionComment
score: 1
has text: I am sorry, but to me this sounds like a question of solving equation `5*x == 25` and wanting to get a different solution every time you solve it. I hope someone else has a working solution for you.

http://stackoverflow.com/comment/88348080
type: Comment
type: QuestionComment
has text: Thank you @Y. Luo. In trying to simplify my file string, I only partially cloned the Gorner GitHub file into my host file and missed the utils_datagen file. Now python can find it. How do I reward you?
comment on: http://stackoverflow.com/q/50612686
score: 0

http://stackoverflow.com/q/50616856
tagged with: database
has body: In my Laravel project, I have added python pandas code for data separation and insertion into a database. if I declare database username password and database name in python then I am able to insert the CSV file created directly into database but when now I cannot declare username and password in python always because the username and password will be changing so I want to add the username and password to a config file and import it into python. so I can write the config file with Laravel code whenever I want. I tried some ways but it didn't work. My code so far is. config.py import pymysql db = pymysql.connect( host = "localhost" , user = "root" , passwd = "root") file.py import config as db cursor = db.cursor() csv_data = csv.reader(open('v.csv')) next(csv_data) for row in csv_data: cursor.execute('INSERT INTO dbname.tablename(fields1, field2, ...) VALUES(%s, %s, %s, %s, %s, %s)',row) db.commit() cursor.close() If I put the entire code in a file.py, I am able to insert the data but I want to import it into file.py. Any help would be greatly appreciated.
tagged with: pandas
downvote count: 0
tagged with: insert
score: 1
has comment: http://stackoverflow.com/comment/88248432
favorite count: 0
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: laravel
has title: How to import python dbconfig file in laravel 5.6
type: Question

http://stackoverflow.com/q/50634193
tagged with: python-3.x
score: 3
has title: Boto3 upload ServerSideEncryption
has body: I am getting an accessed denied error due to SSE How do I modify my current code to include SSE in the form of ServerSideEncryption='AES256' def download(self): s3 = boto3.client('s3') try: with open(self.flow_cells +'.zip', 'wb') as data: s3.download_fileobj(self.source_s3_bucket, self.source_key, data) return True except botocore.exceptions.ClientError as error: print(error.response['Error']['Code']) def upload(self): s3 = boto3.client('s3') try: with open(self.flow_cells +'.zip', 'rb') as data: s3.upload_fileobj(data, self.output_s3_bucket, self.flow_cells +'.zip') return True except botocore.exceptions.ClientError as error: print(error.response['Error']['Code'])
tagged with: python
upvote count: 3
accepted answer: http://stackoverflow.com/a/50634222
type: AnsweredQuestion
tagged with: amazon-s3
tagged with: boto3
type: Question
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50634222
tagged with: amazon-web-services
favorite count: 0

http://stackoverflow.com/comment/88385845
type: Comment
comment on: http://stackoverflow.com/a/50673866
type: AnswerComment
has text: Nice! Thanks for the link also.
score: 0

http://stackoverflow.com/comment/88253210
type: Comment
has text: The exception should also tell you the line where that's happening. Try adding a `print` before that line to see the values of everything you're using. Right now, all we can tell is what the error message is saying - somewhere in that loop there's a value that's expected to be a number, but it's actually this random string that can't be converted to a float. Maybe `in_numbers` has a value that's not a number? try `print(in_numbers)` before the loop to verify that.
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50621614

http://stackoverflow.com/comment/88381425
score: 0
has text: if I understand the problem, e.g. `"subject_id": "1"`, you would like better `"subject_id": 1` where 1 is an integer instead of a string? if yes you can probably do in your code `'subject_id': int(k)` and same idea for other values
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50682520

http://stackoverflow.com/comment/88149944
has text: If you have both Python 2.7 and 3.5.2 installed, the `python` command starts Python 2, while `python3` starts Python 3, perhaps this is your issue?
comment on: http://stackoverflow.com/q/50569960
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/93247471
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50624012
has text: Dude, that's EXACTLY what is going on here. Did you came up with a solution?

http://stackoverflow.com/q/50545787
type: Question
has answer: http://stackoverflow.com/a/50546555
answer count: 1
score: 0
tagged with: typeerror
tagged with: python
tagged with: object-detection
tagged with: python-3.x
has title: Python&OpenCv TypeError on Object Detection
type: UnansweredQuestion
has body: I want to detect my ears on python&amp;OpenCv but it occured this error : Traceback (most recent call last): File "C:/Users/asus/PycharmProjects/ImageProcessing/app.py", line 17, in &lt;module&gt; cv2.rectangle(frame, obj, (15 ,15 ), (0, 0, 255),-5) TypeError: function takes exactly 2 arguments (1 given) Code is here : import numpy as np import cv2 camera = cv2.VideoCapture(0) ear = cv2.imread("ear.png", 0) w, h = ear.shape[::-1] while (True): _, frame = camera.read(0) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) match = cv2.matchTemplate(frame, ear, cv2.TM_CCORR_NORMED) match = np.where(match &gt;= 0.8) for obj in zip(match[::-1]): print(obj) cv2.rectangle(frame, obj, (15,15), (0, 0, 255),-5) cv2.imshow("FindMyEars", frame) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break camera.release() cv2.destroyAllWindows() What should i am to correct the code?
tagged with: opencv
has comment: http://stackoverflow.com/comment/88102545

http://stackoverflow.com/comment/88325998
type: QuestionComment
has text: @ResetACK It actually didnt work as presented and i did not know if it was possible at all. So i thought it may work if you supply it some other way. For example supplying a tuple to a function like datetime((1,1,1)) would not work unless you unpack it like datetime(*(1,1,1))
score: 1
comment on: http://stackoverflow.com/q/50653182
type: Comment

web-services
type: Tag
tags question: http://stackoverflow.com/q/50658118
tags question: http://stackoverflow.com/q/50662832
tag name: web-services
tags question: http://stackoverflow.com/q/50607838

http://stackoverflow.com/comment/88402407
has text: `total` is confusing. It does not appear in the assignment text and you are not ever updating it. What is it supposed to be? The sum of the numbers entered? The previous number?
type: Comment
comment on: http://stackoverflow.com/q/50696624
type: QuestionComment
score: 2

http://stackoverflow.com/comment/88370936
has text: TLS in base64 over JSON through HTTP over SSL over TCP, when one needs just plain SSL over TCP... I'm not sure I want to live in a world where this seems a sensible solution to implement...
type: AnswerComment
comment on: http://stackoverflow.com/a/50679227
type: Comment
score: 0

http://stackoverflow.com/a/50622002
score: 2
has comment: http://stackoverflow.com/comment/88253946
has comment: http://stackoverflow.com/comment/88253904
answers question: http://stackoverflow.com/q/50621832
has comment: http://stackoverflow.com/comment/88260563
downvote count: 0
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/88260668
has comment: http://stackoverflow.com/comment/88254053
has body: In order to access private user data you need the permission of the user. You cant upload to my drive account without my permission. USERNAME:PASSWORD Is called basic authentication and uses login and password google shut down for this in 2015. In order to access private user data now you will need to use Oauth2. I suggest starting with the Python quickstart """ Shows basic usage of the Drive v3 API. Creates a Drive v3 API service and prints the names and ids of the last 10 files the user has access to. """ from __future__ import print_function from apiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools # Setup the Drive v3 API SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly' store = file.Storage('credentials.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service = build('drive', 'v3', http=creds.authorize(Http())) # Call the Drive v3 API results = service.files().list( pageSize=10, fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) if not items: print('No files found.') else: print('Files:') for item in items: print('{0} ({1})'.format(item['name'], item['id']))

http://stackoverflow.com/a/50556391
downvote count: 0
has body: this is implementation of details provided by Garvita Tiwari. I am using python 2.7.12 with opencv 3.4.1 import cv2 import numpy as np src_img = cv2.imread('src.jpg') test_img = cv2.imread('test.jpg') src_gray= cv2.cvtColor(src_img,cv2.COLOR_BGR2GRAY) test_gray= cv2.cvtColor(test_img,cv2.COLOR_BGR2GRAY) sift = cv2.xfeatures2d.SIFT_create() src_kp,src_desc = sift.detectAndCompute(src_gray,None) test_kp,test_desc = sift.detectAndCompute(test_gray,None) bf = cv2.BFMatcher() matches = bf.knnMatch(src_desc,test_desc, k=2) good = [] for m,n in matches: if m.distance &lt; 0.75*n.distance: good.append([m]) print 'so the correspondences are' for i in range(len(good)): print int(src_kp[good[i][0].queryIdx].pt[0]),int(src_kp[good[i][0].queryIdx].pt[1]) ,'-&gt;',int(test_kp[good[i][0].trainIdx].pt[0]) ,int(test_kp[good[i][0].trainIdx].pt[1])
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50550211

http://stackoverflow.com/q/50675518
has body: I am a noob in AngularJS and Flask and I'm getting this issue. When I don't use AngularJS my auth_url is correct. But when I start using AngularJS, it's converting the &amp; in my auth_url to &amp;amp;amp; here is my code. var customInterpolationApp = angular.module('customInterpolationApp', []); customInterpolationApp.config(function($interpolateProvider) { $interpolateProvider.startSymbol('[{['); $interpolateProvider.endSymbol(']}]'); }); customInterpolationApp.controller('DemoController', function($scope) { $scope.label = "https://accounts.google.com/o/oauth2/auth?response_type=code&amp;client_id=214209400059-20bdd3dhe7hnj4b1vjf76btp7eklo7ia.apps.googleusercontent.com&amp;redirect_uri=https%3A%2F%2Flocalhost%3A5000%2FgCallback&amp;scope=profile+email&amp;state=SC1KqZJfjJ12zTrEn2Rm66GGIXGLBj&amp;access_type=offline"; $scope.auth_url = "'{{auth_url}}'" }); When I see in the console, the value of $scope.auth_url has &amp;amp;amp; in place of &amp;. as its a link the code is breaking. I have tried $scope.auth_url = "{{auth_url}}" $scope.auth_url = {{auth_url}} but both are not working and they are still converting the &amp; to &amp;amp;amp;
has comment: http://stackoverflow.com/comment/88365131
linked to: http://stackoverflow.com/q/3206344
has title: angularjs converting & to &amp; in a variable coming from flask server
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/88363800
downvote count: 1
tagged with: flask
favorite count: 0
tagged with: angularjs
duplicate of: http://stackoverflow.com/q/35555383
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/88362051
tagged with: python
duplicate of: http://stackoverflow.com/q/3206344
answer count: 0
type: Question

http://stackoverflow.com/a/50548063
has body: Python's multiprocessing always waits for the child to complete. But subprocess.Popen() does not. However, subprocess.Popen() launches any new program, not necessarily a Python one, and does not directly call a Python function. You could do something like Popen(['python', __file__, '--child']) and implement your script so that when sys.argv contains --child (hint: use argparse), it will just call lul(). However, there is no need to do any of this--your end goal here seems to be that lul() runs in a Python interpreter, and no extra Python interpreter remains. So don't start a second interpreter in the first place--simply call lul() and be done with it.
accepted answer of: http://stackoverflow.com/q/50547948
answers question: http://stackoverflow.com/q/50547948
type: AcceptedAnswer
score: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/88111270
downvote count: 1

http://stackoverflow.com/comment/88336696
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50655765
has text: Great answer. The suggestion works perfect, includes more cases than I considered (e.g. it perfectly detects 5% in "Did you say 5%?"), and the tool you link to is super useful! Thanks.
type: AnswerComment

http://stackoverflow.com/a/50617821
has comment: http://stackoverflow.com/comment/88248187
has comment: http://stackoverflow.com/comment/88248801
score: 2
has comment: http://stackoverflow.com/comment/88248858
has comment: http://stackoverflow.com/comment/88250007
has comment: http://stackoverflow.com/comment/88248033
has comment: http://stackoverflow.com/comment/88250392
has comment: http://stackoverflow.com/comment/88247558
accepted answer of: http://stackoverflow.com/q/50617233
has comment: http://stackoverflow.com/comment/88248139
has body: You can first convert dates to dtetimes and get days by dt.day: df['DATE_LOCATION'] = pd.to_datetime(df['DATE_LOCATION'], dayfirst=True) days = df['DATE_LOCATION'].dt.day Then binning by cut: rng = pd.cut(days, bins=[0,3,7,15,31], labels=['1-3', '4-7','8-15', '&gt;=16']) print (rng) 0 1-3 1 1-3 2 4-7 3 8-15 4 8-15 5 1-3 6 1-3 7 4-7 8 8-15 9 8-15 10 8-15 Name: DATE_LOCATION, dtype: category Categories (4, object): [1-3 &lt; 4-7 &lt; 8-15 &lt; &gt;=16] And aggregate sum by product and binned Series: df = df.groupby(["PRODUCT_ID",rng])['Sold'].sum() print (df) PRODUCT_ID DATE_LOCATION 0E4234 1-3 9 4-7 3 8-15 3 0G2342 1-3 3 4-7 1 8-15 7 Name: Sold, dtype: int64 If need also count per years: df = df.groupby([df['DATE_LOCATION'].dt.year.rename('YEAR'), "PRODUCT_ID",rng])['Sold'].sum() print (df) YEAR PRODUCT_ID DATE_LOCATION 2016 0E4234 1-3 9 4-7 3 8-15 3 0G2342 1-3 3 4-7 1 8-15 7 Name: Sold, dtype: int64
has comment: http://stackoverflow.com/comment/88250498
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88250139
upvote count: 2
answers question: http://stackoverflow.com/q/50617233
type: Answer
has comment: http://stackoverflow.com/comment/88247362

http://stackoverflow.com/a/50707636
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50682520
accepted answer of: http://stackoverflow.com/q/50682520
has comment: http://stackoverflow.com/comment/88452914
upvote count: 1
score: 1
has body: here is not the best solution, but using pandas might be helpfull for keeping type of values, I did not look at the efficiency of the code, justthe part on reading the csv file but you can do: import pandas as pd def solution(csv_filename): by_subject_id = defaultdict(lambda: { . . }) df = pd.read_csv(csv_filename).fillna('') for row in df .iterrows(): non_empty = {k: v for k, v in row[1].iteritems() if v != ''} subject_id = non_empty['subid'] # must have to group by . . . I try to keep the fews lines changeed, everything else is the same. Ultimately, if you can directly have as parameter your cleaned DF instead of reading the csv file it would be better. Otherwise, you can add dtype= in read_csv() such as: df = pd.read_csv(csv_filename,dtype={'subid':int, 'age':int}).fillna('') add any type you want to have. I hope it helps you
has comment: http://stackoverflow.com/comment/88453218

http://stackoverflow.com/comment/88400768
type: QuestionComment
has text: because `first` get first non nan values per grouops
comment on: http://stackoverflow.com/q/50693031
type: Comment
score: 1

http://stackoverflow.com/q/50613664
has comment: http://stackoverflow.com/comment/88237907
score: 0
duplicate of: http://stackoverflow.com/q/19951816
linked to: http://stackoverflow.com/q/2612802
has body: I was just trying to write a code in Python for Euler Problem 15 (https://projecteuler.net/problem=15), concerning Lattice Paths. I wanted to write something which would return (1,2,1), (1, 3, 3, 1), (1, 4, 6, 4, 1) etc. I wrote the following: lijst = [1,1] temp = [1,1] for a in range(2,21): temp.append(1) for b in range(1,a): temp[b] = lijst[b-1] + lijst[b] lijst = temp print a, lijst To my surprise, this didn't work. At the start of the second 'for'-loop, somehow the append doesn't only work on 'temp', but also on 'lijst'. I got the code working by changing: lijst = temp into: lijst = [a for a in temp] What's the problem hear? Am I missing something out on the behaviour of lists? Thanks!
type: UnansweredQuestion
tagged with: python
tagged with: list
answer count: 0
has comment: http://stackoverflow.com/comment/88237826
duplicate of: http://stackoverflow.com/q/2612802
type: Question
has comment: http://stackoverflow.com/comment/88237324
has title: Assigning two lists as each others equals
has comment: http://stackoverflow.com/comment/88237234

http://stackoverflow.com/comment/88159069
type: QuestionComment
comment on: http://stackoverflow.com/q/50567832
has text: Thenk you for your comment. The code run in python successfully, but it doesn't run in exe file. And no error message is shown. "Run it from the CMD" means that I run the exe file from the CMD?
score: 0
type: Comment

http://stackoverflow.com/q/50616556
favorite count: 0
has body: I use this code to test scientific notation: a = 5.26E-324 print(a) a = 5.26E-325 print(a) The code result: 5e-324 0.0 Questions: Why 5.26E-325 cannot show 5e-325? Does this mean that less than E-324 is shown to be 0.0? Is there a way to show 5e-325?
has answer: http://stackoverflow.com/a/50616674
type: Question
accepted answer: http://stackoverflow.com/a/50616733
upvote count: 1
has comment: http://stackoverflow.com/comment/88243039
has answer: http://stackoverflow.com/a/50616733
score: 0
answer count: 3
linked to: http://stackoverflow.com/q/1835787
downvote count: 1
possible better answer: http://stackoverflow.com/a/50616749
has title: Python uses the scientific notation to show that 5.26E-325 is 0,but 5.26E-324 is 5e-324,why?
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50616749
tagged with: scientific-notation
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88243113

http://stackoverflow.com/comment/88101164
has text: Hi @jpp, thanks for pointing out, it was my mistake, I want to know the unique number of days it has been sold. I have edited my question
comment on: http://stackoverflow.com/a/50542101
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50611788
score: 4
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88233713
has body: I believe need lambda function with unique and sum: df = pd.DataFrame({'numerator':[3,1,1,9,2,2], 'category2':list('aaabbb')}) #print (df) df['denominator']=df.groupby(['category2'])['numerator'].transform(lambda x: x.unique().sum()) Alternative solution with sets and sums: df['denominator']=df.groupby(['category2'])['numerator'].transform(lambda x: sum(set(x))) print (df) category2 numerator denominator 0 a 3 4 1 a 1 4 2 a 1 4 3 b 9 11 4 b 2 11 5 b 2 11
type: Answer
accepted answer of: http://stackoverflow.com/q/50611772
upvote count: 4
answers question: http://stackoverflow.com/q/50611772
downvote count: 0

http://stackoverflow.com/comment/88191902
score: 0
has text: If I comment out the 2nd call(), this appears on the terminal: "Script started, file is sessyon.log"
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50591198

http://stackoverflow.com/a/50652609
downvote count: 0
has comment: http://stackoverflow.com/comment/88315987
accepted answer of: http://stackoverflow.com/q/50652561
score: 9
has comment: http://stackoverflow.com/comment/88315941
answers question: http://stackoverflow.com/q/50652561
has comment: http://stackoverflow.com/comment/88315961
has body: Annotations have no meaning to Python's compiler and interpreter.1 As long as what you type is a syntactically valid expression, Python will evaluate it, store its value as part of the function's annotations, and leave it there for you to do whatever you want with (which is usually nothing). In fact, you can see this being stored without a problem: &gt;&gt;&gt; print(my_function_3.__annotations__) {'param': 1} The main point of annotations is for using a static type checker, as explained in PEP 484 (and the accompanying PEP 483 and PEP 482 for background). Static type checking is optional in Python, and generally done with a dedicated tool like mypy, or with tools integrated into IDEs like PyCharm. If you run such a checker against your code, it will complain. For example: $ mypy testscript.py testscript.py:1: error: invalid type comment or annotation This error means that it can't figure out what type 1 is supposed to be.2 One last thing: what kind of variable I would have to pass to functions 2 and 3 to satisfy parameter type I erroneously requested There's no type that would satisfy that. Python's runtime type rules are more flexible than its (optional) static type rules, but they're not that flexible.3 1. However, they do have a meaning to at least one thing in the stdlib, the dataclass decorator. 2. Mypy continues on from here, but with no more errors, even if you abuse the parameter in the body or call the function improperly. As far as I can tell, it skips checking the body, and treats the function as if it took any parameters and returned an Any. Which is pretty reasonable—that way you just get this one error instead of hundreds of useless ones that probably wouldn't mean anything. 3. You can't even test for it—isinstance(obj, 1) will raise an exception because 1 is not an instance of type. But if you could, it could only return true if obj was created by calling 1 (or a subclass of 1, of which there are none) as a metaclass, which is impossible, or if obj._…
type: AcceptedAnswer
upvote count: 9
type: Answer
has comment: http://stackoverflow.com/comment/88315932

http://stackoverflow.com/comment/88226884
type: Comment
comment on: http://stackoverflow.com/q/50608418
score: 0
has text: Your output and desired output are the same?
type: QuestionComment

http://stackoverflow.com/a/50659978
has comment: http://stackoverflow.com/comment/88330551
downvote count: 0
has comment: http://stackoverflow.com/comment/88330411
has comment: http://stackoverflow.com/comment/88330487
has comment: http://stackoverflow.com/comment/88330109
has body: You'll need groupby + unique, followed by agg. df.groupby('id').fruit.unique().agg(', '.join).reset_index() id fruit 0 101 apple, watermelon, orange 1 102 apple, orange 2 103 grapes 3 104 lemon 4 105 lemon, apple Note that data within groups are not reordered, even if the groups are. If you don't want to sort the groups either, use sort=False. df.groupby('id', sort=False).fruit.unique().agg(', '.join).reset_index() id fruit 0 101 apple, watermelon, orange 1 102 apple, orange 2 104 lemon 3 105 lemon, apple 4 103 grapes
has comment: http://stackoverflow.com/comment/88330167
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50659967
has comment: http://stackoverflow.com/comment/88330520
type: Answer
accepted answer of: http://stackoverflow.com/q/50659967
has comment: http://stackoverflow.com/comment/88330027
score: 2

node.js
tags question: http://stackoverflow.com/q/50589034
tags question: http://stackoverflow.com/q/50611746
tags question: http://stackoverflow.com/q/50546268
tags question: http://stackoverflow.com/q/50669874
tags question: http://stackoverflow.com/q/50551364
tags question: http://stackoverflow.com/q/50598070
tags question: http://stackoverflow.com/q/50693158
tags question: http://stackoverflow.com/q/50643873
tags question: http://stackoverflow.com/q/50577454
type: Tag
tag name: node.js
tags question: http://stackoverflow.com/q/50560161
tags question: http://stackoverflow.com/q/50651772
tags question: http://stackoverflow.com/q/50623788
tags question: http://stackoverflow.com/q/50618593

http://stackoverflow.com/comment/88210863
comment on: http://stackoverflow.com/q/50600841
score: 0
type: Comment
type: QuestionComment
has text: `' '.join(''.join(x) for x in lst)`?

http://stackoverflow.com/q/50665505
score: 0
has comment: http://stackoverflow.com/comment/90021695
has comment: http://stackoverflow.com/comment/88340981
has comment: http://stackoverflow.com/comment/88341412
type: UnansweredQuestion
has title: How to fix Notepad++ NppExec Error
tagged with: python
answer count: 0
type: Question
tagged with: notepad++
tagged with: nppexec
has body: I'm trying to fix a error in Notepad++, I'm using NppExec plugin in Notepad++ and trying to execute my code. Whenever I click Plugins, NppExec, Execute, a window popups. Then I type this: print("Hello World") and press 'OK', a error line like this appears: print("Hello World!") about to start a child process: "print("Hello World!")" `CreateProcess() failed with error code 2:` The system cannot find the file specified. How should I fix this? Am I using it in the wrong way? Or is there any way to fix this? [Sorry if I hadn't explained well]

http://stackoverflow.com/q/50665379
type: Question
duplicate of: http://stackoverflow.com/q/44074695
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88340725
score: 1
has answer: http://stackoverflow.com/a/50665387
has comment: http://stackoverflow.com/comment/88340724
accepted answer: http://stackoverflow.com/a/50665387
answer count: 1
downvote count: 0
favorite count: 0
has title: Why to use .remove(elem) when there is .discard(elem) in python?
tagged with: python
has body: .discard(x): This operation removes element from the set. If element does not exist, it does not raise a KeyError. .remove(x): This operation removes element from the set. If element does not exist, it raises a KeyError. So my question is, where is the reason to use remove(x) function since it can cause problem to our program by erasing an error. I feel like it is useless function since discard(x) does the exact same thing without causing any unpredictable behavior to our program.
upvote count: 1

http://stackoverflow.com/comment/88201826
type: AnswerComment
has text: Thanks! I was trying to avoid applying lambda functions but I guess we dont have a better way..
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50596351

http://stackoverflow.com/q/50582179
has answer: http://stackoverflow.com/a/50582978
tagged with: mapping
type: UnansweredQuestion
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88174254
has comment: http://stackoverflow.com/comment/88174308
linked to: http://stackoverflow.com/q/17071871
linked to: http://stackoverflow.com/q/49754202
type: Question
tagged with: numpy
has title: Filter dates according to the month and paste them in a new column with month as column name
answer count: 1
has comment: http://stackoverflow.com/comment/88174283
has comment: http://stackoverflow.com/comment/88174683
tagged with: pandas
tagged with: datetime
has body: I have about 30+ columns with dates all ranging in current year for databases. I need to filter dates and arrange them in new columns, as in all dates falling in May in a new column called May while all dates in June in another column June. (I have a schedule for databases which all the release date in the current year in different columns. I need to create a column month-wise and add dates in these columns) I did write a code but I could only filter dates of one of the many columns and also the date format is distorted sf.loc[(sf['Unnamed: 16']&gt;= start) &amp; (sf['Unnamed: 16']&lt;=end), 'CurrentMonth'] = sf['Unnamed: 16'] Input file Output file

http://stackoverflow.com/q/50589400
tagged with: keras
favorite count: 0
tagged with: python
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/50589562
type: Question
has body: I know those activations differ in their definition, however, when reading ReLU's documentation, it takes a parameter alpha as an input with 0 as default, and says relu relu(x, alpha=0.0, max_value=None) Rectified Linear Unit. Arguments x: Input tensor. alpha: Slope of the negative part. Defaults to zero. max_value: Maximum value for the output. Returns The (leaky) rectified linear unit activation: x if x > 0, alpha * x if x &lt; 0. If max_value is defined, the result is truncated to this value. And there is also a LeakyReLU with a similar documentation, but as part of other module (advanced activation) Is there a difference between them? and how shoud I import relu to instantiate it with alpha? from keras.layers.advanced_activations import LeakyReLU .. .. model.add(Dense(512, 512, activation='linear')) model.add(LeakyReLU(alpha=.001)) # using Relu insted of LeakyRelu Note that when using LeakyReLU I'm getting the following error: AttributeError: 'LeakyReLU' object has no attribute '__name__' but when I use ReLU instead, It works: model.add(Activation('relu')) # This works correctly but can't set alpha To sum up: What are de diferencies and how can I import ReLU to pass aplha to it?
has comment: http://stackoverflow.com/comment/88188449
has comment: http://stackoverflow.com/comment/88189237
has title: implementation difference between ReLU and LeakyRelu
score: 3
accepted answer: http://stackoverflow.com/a/50589562
answer count: 1
downvote count: 0

http://stackoverflow.com/a/50696442
has comment: http://stackoverflow.com/comment/88404934
has comment: http://stackoverflow.com/comment/88411696
has comment: http://stackoverflow.com/comment/88404196
has comment: http://stackoverflow.com/comment/88402785
type: Answer
has comment: http://stackoverflow.com/comment/88404082
has comment: http://stackoverflow.com/comment/88403959
has comment: http://stackoverflow.com/comment/88404594
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88405318
has comment: http://stackoverflow.com/comment/88403909
has body: First remove replacing duplicated ID in both DataFrames: #df1['ID'] = df1['ID'].mask(df['ID'].duplicated(), '') #df2['ID'] = df2['ID'].mask(df['ID'].duplicated(), '') print (df1) ID Range(US) Count(US) Mean(US) 0 690 1-3 266 4.0 1 690 4-7 277 NaN 2 354 1-3 233 2.0 3 354 4-7 85 NaN 4 947 1-3 156 4.0 print (df2) ID Range(UK) Count(UK) Mean(UK) 0 690 1-3 186 4.0 1 690 4-7 25 NaN 2 354 1-3 44 1.0 3 947 1-3 213 3.0 4 947 4-7 33 NaN And then merge by both columns with outer join: df = df1.merge(df2, left_on=['ID', 'Range(US)'], right_on=['ID', 'Range(UK)'], how='outer') print (df) ID Range(US) Count(US) Mean(US) Range(UK) Count(UK) Mean(UK) 0 690 1-3 266.0 4.0 1-3 186.0 4.0 1 690 4-7 277.0 NaN 4-7 25.0 NaN 2 354 1-3 233.0 2.0 1-3 44.0 1.0 3 354 4-7 85.0 NaN NaN NaN NaN 4 947 1-3 156.0 4.0 1-3 213.0 3.0 5 947 NaN NaN NaN 4-7 33.0 NaN
answers question: http://stackoverflow.com/q/50696386
has comment: http://stackoverflow.com/comment/88434121
has comment: http://stackoverflow.com/comment/88403932
has comment: http://stackoverflow.com/comment/88406407
has comment: http://stackoverflow.com/comment/88404938
has comment: http://stackoverflow.com/comment/88405099
has comment: http://stackoverflow.com/comment/88405585
has comment: http://stackoverflow.com/comment/88404133
has comment: http://stackoverflow.com/comment/88405193
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88411462
accepted answer of: http://stackoverflow.com/q/50696386

http://stackoverflow.com/q/50637603
has comment: http://stackoverflow.com/comment/88286401
has comment: http://stackoverflow.com/comment/88286684
has body: So I have a set of 50 dates I have specified 7 here for example df["CreatedDate"] = pd.DataFrame('09-08-16 0:00','22-08-16 0:00','23-08-16 0:00',28-08-16 0:00,'29-08-16 0:00','30-08-16 0:00','31-08-16 0:00') df["CreatedDate"] = pd.to_datetime(df4.CreatedDate) df4["DAY"] = df4.CreatedDate.dt.day How to find the continuous days which form a streak range [1-3],[4-7],[8-15],[>=16] Streak Count 1-3 3 #(9),(22,23) are in range [1-3] 4-7 1 #(28,29,30,31) are in range [4-7] 8-15 0 &gt;=16 0 let's just say the product (pen) has been launched 2 yrs back we are taking the dataset for last 10 months from today and from what I want to find is that if people are buying that pen continuously for 1 or 2 or 3 days and if yes place the count [1-3] and if they are buying it continuously for 4 or 5 or 6 or 7 days we place the count in [4- 7] and so on for other ranges I dont know which condition to specify to match the criteria
has comment: http://stackoverflow.com/comment/88287535
has comment: http://stackoverflow.com/comment/88287517
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88286088
tagged with: pivot-table
possible better answer: http://stackoverflow.com/a/50640163
tagged with: python
linked to: http://stackoverflow.com/q/50621605
has answer: http://stackoverflow.com/a/50640163
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50640550
has title: Finding the streak of days in python
has comment: http://stackoverflow.com/comment/88286208
type: Question
tagged with: group-by
has comment: http://stackoverflow.com/comment/88287664
accepted answer: http://stackoverflow.com/a/50640550
score: 0
answer count: 2
tagged with: pandas
linked to: http://stackoverflow.com/q/50617233

http://stackoverflow.com/a/50545735
has comment: http://stackoverflow.com/comment/88102754
has comment: http://stackoverflow.com/comment/88102660
has comment: http://stackoverflow.com/comment/88102852
has comment: http://stackoverflow.com/comment/88115912
upvote count: 2
has comment: http://stackoverflow.com/comment/88103189
score: 2
has comment: http://stackoverflow.com/comment/88102635
has comment: http://stackoverflow.com/comment/88103013
has comment: http://stackoverflow.com/comment/88102929
has body: Here is an approach using a KDTree for efficient nearest color lookup. Note that while KDTrees may be pretty advanced, using them is actually quite simple. import numpy as np from matplotlib import colors from scipy.spatial import cKDTree as KDTree from scipy.misc import face REDUCED_COLOR_SPACE = True # borrow a list of named colors from matplotlib if REDUCED_COLOR_SPACE: use_colors = {k: colors.cnames[k] for k in ['red', 'green', 'blue', 'black', 'yellow', 'purple']} else: use_colors = colors.cnames # translate hexstring to RGB tuple named_colors = {k: tuple(map(int, (v[1:3], v[3:5], v[5:7]), 3*(16,))) for k, v in use_colors.items()} ncol = len(named_colors) if REDUCED_COLOR_SPACE: ncol -= 1 no_match = named_colors.pop('purple') else: no_match = named_colors['purple'] # make an array containing the RGB values color_tuples = list(named_colors.values()) color_tuples.append(no_match) color_tuples = np.array(color_tuples) color_names = list(named_colors) color_names.append('no match') # get example picture img = face() # build tree tree = KDTree(color_tuples[:-1]) # tolerance for color match `inf` means use best match no matter how # bad it may be tolerance = np.inf # find closest color in tree for each pixel in picture dist, idx = tree.query(img, distance_upper_bound=tolerance) # count and reattach names counts = dict(zip(color_names, np.bincount(idx.ravel(), None, ncol+1))) print(counts) import pylab pylab.imshow(img) pylab.savefig('orig.png') pylab.clf() pylab.imshow(color_tuples[idx]) pylab.savefig('minimal.png' if REDUCED_COLOR_SPACE else 'reduced.png') Output with full matplotlib named color space: {'aliceblue': 315, 'antiquewhite': 0, 'aqua': 0, 'aquamarine': 0, 'azure': 0, 'beige': 27, 'bisque': 0, 'black': 88584, 'blanchedalmond': 0, 'blue': 0, 'blueviolet': 0, 'brown': 0, 'burlywood': 76, 'cadetblue': 0, 'chartreuse': 0, 'chocolate': 0, 'coral': 0, 'cornflowerblue': 0, 'cornsilk': 0, 'crimson': 0, 'cyan': 0, 'darkblue': 0, 'darkcyan': 0, 'darkgoldenrod': 0, …
has comment: http://stackoverflow.com/comment/88102846
has comment: http://stackoverflow.com/comment/88102967
has comment: http://stackoverflow.com/comment/88102589
has comment: http://stackoverflow.com/comment/88103880
has comment: http://stackoverflow.com/comment/88103247
downvote count: 0
has comment: http://stackoverflow.com/comment/88114567
has comment: http://stackoverflow.com/comment/88103360
has comment: http://stackoverflow.com/comment/88103110
answers question: http://stackoverflow.com/q/50545192
has comment: http://stackoverflow.com/comment/88103312
type: Answer
has comment: http://stackoverflow.com/comment/88104075
has comment: http://stackoverflow.com/comment/88102733

http://stackoverflow.com/q/50696659
upvote count: 0
has answer: http://stackoverflow.com/a/50696703
favorite count: 0
answer count: 3
tagged with: pandas
has title: Convert DateTime in to number
tagged with: python
has answer: http://stackoverflow.com/a/50697478
type: UnansweredQuestion
score: -4
has body: If I have a column in my df that has datetime, such as '21:56:02', how is the best way to convert that in to an indentical numeric format, so '215602'? Thank you,
has answer: http://stackoverflow.com/a/50696708
type: Question
downvote count: 4

http://stackoverflow.com/comment/88226134
comment on: http://stackoverflow.com/q/50603077
has text: I see you have `output_file` and `show`. Those are typically used with *standalone* Bokeh documents that are static HTML and JS and *do not work with real Python `on_change` callbacks*. Are you running this like a normal python script or are you running it with e.g. `bokeh serve --show app.py` ?
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/88328125
type: Comment
type: QuestionComment
has text: @raghav710 : i found an updated version of my code that I posted as an answer, so now it works fine. :)
score: 1
comment on: http://stackoverflow.com/q/50657788

http://stackoverflow.com/a/50686050
has body: This finds the maximum value and then finds its first occurence in the given list def max_index(my_list) max_value = max(my_list) max_index = my_list.index(max_value) return max_index Here's the expected behaviour. &gt; list = [1, 2, 3, 4] &gt; max_index(list) &gt; 3
has comment: http://stackoverflow.com/comment/88384696
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88385865
accepted answer of: http://stackoverflow.com/q/50685860
type: Answer
has comment: http://stackoverflow.com/comment/88382009
answers question: http://stackoverflow.com/q/50685860

http://stackoverflow.com/comment/88287637
has text: Hi, question is if this error is really related to the pydocumentdb lib or you just hit the document DB size limit of 2MB per document?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50607467

http://stackoverflow.com/comment/106529623
type: Comment
type: QuestionComment
has text: Try [**this link**](https://github.com/jmschrei/pomegranate/issues/485) at Github
comment on: http://stackoverflow.com/q/50660261
score: 0

http://stackoverflow.com/a/50558891
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/88128525
answers question: http://stackoverflow.com/q/50558424
has body: Your question is very similar to invoking a python script from another one which has already two answers in Run a python script from another python script, passing in args and What is the best way to call a Python script from another Python script? Your fragment is OK, but there may be some differences from the symlink. E.g. If File_B uses the classic idiom if __name__ == '__main__':, then the 'if' would not be True with the import and you should invoke the code in that section directly. To invoke File_B you can use ececfile("/path_to/File_B") to maintain the same arguments or os.system("/path_to/File_B %s" % ' '.join(arglist)) if you need to change the arguments. If you prefer to avoid the OS and keep it in Python, check if you have to call a function or add some code after the import (e.g. if File_B has a if __name__ == '__main__':). And in https://stackoverflow.com/a/3781960/3547046 there are some suggestions to preserve the arguments.

fixtures
tags question: http://stackoverflow.com/q/50609171
type: Tag
tags question: http://stackoverflow.com/q/50593556
tag name: fixtures

http://stackoverflow.com/comment/88372007
comment on: http://stackoverflow.com/q/50681101
type: Comment
type: QuestionComment
has text: So could you please describe what you're looking for as an output and what you are currently getting?
score: 0

http://stackoverflow.com/q/50654965
tagged with: django
downvote count: 1
has title: How should I move my completed Django Project in a Virtual Environment?
type: Question
has answer: http://stackoverflow.com/a/50655762
has body: I started learning django a few days back and started a project, by luck the project made is good and I'm thinking to deploy it. However I didn't initiate it in virtual environment. have made a virtual environment now and want to move project to that. I want to know how can I do that ? I have created requirements.txt whoever it has included all the irrelevant library names. How can I get rid of them and have only that are required for the project.
accepted answer: http://stackoverflow.com/a/50655762
score: 1
has comment: http://stackoverflow.com/comment/88320825
has comment: http://stackoverflow.com/comment/88320970
answer count: 1
tagged with: virtualenv
favorite count: 0
has comment: http://stackoverflow.com/comment/88320183
tagged with: python
type: AnsweredQuestion
upvote count: 2

http://stackoverflow.com/comment/88245657
score: 0
type: Comment
type: QuestionComment
has text: The algorithm for finding the insertion point is also unclear (and your code is inconsistent with what you've written). For example, you calculate `d1` and `d2` without taking the absolute value (`abs`), but your comment when you list the steps says, "ignore the sign." If two items from the second list are slated for insertion between the same two items in the first list, which goes first?
comment on: http://stackoverflow.com/q/50617334

http://stackoverflow.com/q/50616048
has comment: http://stackoverflow.com/comment/88242204
linked to: http://stackoverflow.com/q/9614258
has comment: http://stackoverflow.com/comment/88242198
score: 0
has comment: http://stackoverflow.com/comment/88247710
tagged with: python-3.x
has title: Google Maps API (Places search) returning results from multiple geographic coordinates
type: UnansweredQuestion
tagged with: python
tagged with: google-places-api
has body: I'm using Google Maps APi places search in python import urllib import urllib.request import json googleGeocodeUrl = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=' keyword = "hospitales" geolocation = "&amp;location=-12.135,-77.023&amp;radius=5000" APIKEY = '&amp;key='+'AIzaSyg5v17Ik' url = googleGeocodeUrl + keyword + geolocation + APIKEY print(url) url = googleGeocodeUrl + keyword + geolocation + APIKEY json_response = urllib.request.urlopen(url) search = json_response.read().decode('utf-8') searchjson = json.loads(search) export = open('hopital.csv','w') for place in searchjson['results']: print(place['name']) print(place['geometry']['location']) export.write(place['name']+','+str(place['geometry']['location']['lng'])\ +','+str(place['geometry']['location']['lat'])+'\n') export.close() I want my code to make some kind of loop where it's gonna return results for more than one geographic coordinate at the time. How can I achieve that? Any code sample that could help me?
answer count: 0
tagged with: google-api
has comment: http://stackoverflow.com/comment/88247684
type: Question
linked to: http://stackoverflow.com/q/6965847

http://stackoverflow.com/q/50664128
has comment: http://stackoverflow.com/comment/88338396
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/50664166
possible better answer: http://stackoverflow.com/a/50664147
favorite count: 0
has title: Python Pandas Groupby Count Error
has answer: http://stackoverflow.com/a/50664147
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50664166
has body: i have a list with columns "school" and "scores1" and "scores2", i'm trying to groupby in order to get unique school record and do a count for scores1 greater than or equal to 70 and count for scores2 greater than or equal to 70. can anyone help me? this is the error i'm getting: my sample list:
type: Question

http://stackoverflow.com/comment/88389963
type: QuestionComment
has text: Also: df.query(“A >= 0”)
score: 0
comment on: http://stackoverflow.com/q/50689823
type: Comment

http://stackoverflow.com/comment/88341844
comment on: http://stackoverflow.com/a/50665612
score: 0
type: AnswerComment
type: Comment
has text: For some reason this regex is striping the day from some of the dates: January 1st , 2017, becomes January , 2017

http://stackoverflow.com/comment/88322314
type: Comment
has text: Perfect explanation. Thanks a lot it worked like a charm :)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50649942

http://stackoverflow.com/a/50660682
answers question: http://stackoverflow.com/q/50660571
upvote count: 0
score: -1
type: Answer
has comment: http://stackoverflow.com/comment/88336694
has body: Following my comment, I wrote a simple test generator to test your solution. Here is the code: def cyclic_sorted_lst(A): low, high = 0, len(A) - 1 while low &lt;= high: mid = (low + high) // 2 if A[mid] &lt; A[high]: high = mid elif A[mid] == A[high]: return mid else: low = mid + 1 import random i = 0 while True: i += 1 print(i) arr = list(set([random.randint(1, int(1000)) for _ in range(10)])) arr.sort() length = random.randint(1, len(arr)) cyclic_arr = arr[length:] + arr[:length] print(cyclic_arr) if cyclic_sorted_lst(cyclic_arr) != cyclic_arr.index(min(cyclic_arr)): print(cyclic_arr, cyclic_sorted_lst(cyclic_arr), cyclic_arr.index(min(cyclic_arr))) break Your code ran successfully for over 200K iterations so I am pretty confident it is correct.
downvote count: 1

http://stackoverflow.com/a/50555053
score: 0
type: Answer
has body: I think the answer to your question is: "Practice creates masters". Write code, review your code, refactor your code. With time you will gain more and more experience and write better code. As resource I recommend reading "Clean Code" by Robert C. Martin, "Pragmatic Programmer" by Andy Hund and Dave Thomas, "Practical object-oriented desing" by Sandi Metz. I think you will get a better developer, if you read them.
answers question: http://stackoverflow.com/q/50554935

http://stackoverflow.com/comment/88201069
type: Comment
has text: The issue is that it's fetching the same url while selenium is loading the page.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50595758

http://stackoverflow.com/q/50678599
tagged with: pandas
has body: So I have two data frames In the first data frame, it shows 4 Cars sold on different dates of the range and the number of cars sold In the 2nd data frame, some cars have repair's so they are called df1: Cars Range(Days) Sold 0 A 1-3 5 1 4-7 23 2 8-15 2 3 B 4-7 4 4 8-15 1 5 C 1-3 5 6 D 1-3 2 7 E 1-3 9 and df2: Car Repair_Calls 0 A 2 1 C 45 2 D 32 4 E 1 I tried df1['Repair_Calls']=df2['Repair_Calls'] What i got Car Range(Days) Sold Repair_Calls 0 A 1-3 5 2 1 4-7 23 45 2 8-15 2 32 3 B 4-7 4 1 4 8-15 1 5 C 1-3 5 6 D 1-3 2 7 E 1-3 9 Output Expected Car Range(Days) Sold Repair_Calls 0 A 1-3 5 2 1 4-7 23 2 8-15 2 3 B 4-7 4 0 4 8-15 1 5 C 1-3 5 45 6 D 1-3 2 32 7 E 1-3 9 1
favorite count: 0
tagged with: python-3.x
upvote count: 1
tagged with: python
tagged with: merge
has answer: http://stackoverflow.com/a/50678642
type: AnsweredQuestion
score: 1
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/50679950
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50679950
downvote count: 0
has title: How to merge two irregular data frames in python
accepted answer: http://stackoverflow.com/a/50678642

http://stackoverflow.com/q/50698649
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50722571
favorite count: 0
tagged with: python-asyncio
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/88436615
has title: How can I refactor to accept multiple clients?
has comment: http://stackoverflow.com/comment/88435743
upvote count: 1
has comment: http://stackoverflow.com/comment/88410348
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50722571
has comment: http://stackoverflow.com/comment/88409853
has body: I don't understand why server.py Version 1 allows a client to be keyboard-interrupted and restarted, while server.py Version 2 doesn't: server.py Version1: import asyncio async def handle_client(reader, writer): while True: request = (await reader.read(128)).decode() writer.write('Received ok.'.encode()) await writer.drain() async def main(): loop.create_task(asyncio.start_server(handle_client, 'localhost', 15555)) loop = asyncio.new_event_loop() loop.create_task(main()) loop.run_forever() server.py Version 2: import asyncio async def handle_client(reader, writer): while True: request = (await reader.read(128)).decode() if request == "hello": writer.write('Received ok.'.encode()) await writer.drain() async def main(): loop.create_task(asyncio.start_server(handle_client, 'localhost', 15555)) loop = asyncio.new_event_loop() loop.create_task(main()) loop.run_forever() client.py: import asyncio async def make_connections(): reader, writer = await asyncio.open_connection('localhost', 15555, loop=loop) loop.create_task(connect(reader, writer)) async def connect(reader, writer): writer.write("hello".encode()) await writer.drain() result = await reader.read(128) print(result.decode()) loop = asyncio.new_event_loop() loop.create_task(make_connections()) loop.run_forever() Version 2 works fine for a single client, but if I send a keyboard interrupt to the client I can no longer connect after I restart the client. It's annoying to ssh in and kill/restart the server every time I alter code in the client. I don't see why the second version doesn't accept the client the second time it attempts to connect.
score: 1

http://stackoverflow.com/q/50690751
has answer: http://stackoverflow.com/a/50691528
has comment: http://stackoverflow.com/comment/88391451
has body: Sorry if the title is not so specific. I am looking to restructure variables and if-statements in a program to make the code more efficient. The current code is pretty large and I am sure it can be shortened by at least 70%. I just started learning Python two weeks ago, I may be missing basic functions that are pretty obvious. Here is the code: def function(): variable = int(input('Input: ') if variable == 10: variable = 1 elif variable == 9: variable = 0.9 If I want to repeat this with different values and variables it gets pretty long, and this is what I want to fix. A friend told me to use dictionaries to store the values but I am not sure how to use if-statements with dictionary values. How should I structure my code to make it shorter?
answer count: 3
has comment: http://stackoverflow.com/comment/88392971
type: UnansweredQuestion
downvote count: 2
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/50690802
tagged with: if-statement
has comment: http://stackoverflow.com/comment/88391316
has answer: http://stackoverflow.com/a/50690784
type: Question
upvote count: 0
score: -2
has title: How can I structure variables more efficiently in Python?
tagged with: arrays
tagged with: variables
favorite count: 0

seq2seq
tag name: seq2seq
type: Tag
tags question: http://stackoverflow.com/q/50662896

http://stackoverflow.com/q/50694378
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50698482
type: Question
score: -2
has comment: http://stackoverflow.com/comment/88398315
linked to: http://stackoverflow.com/q/37085665
tagged with: conda
has body: I use Anaconda to open a Jupyter Notebook: When I open the Jupyter Notebook in the default environment, 'root', everything is all right: But there are some mistakes when I open the Jupyter Notebook in the other environment. Is there some necessary information I should complement？ Thanks a lot.
upvote count: 0
has title: No Conda environment when I open JupyterNotebook
answer count: 1
accepted answer: http://stackoverflow.com/a/50698482
favorite count: 0
downvote count: 2
tagged with: python
tagged with: jupyter-notebook
tagged with: environment

http://stackoverflow.com/comment/88378083
score: 0
type: Comment
type: QuestionComment
has text: It should! My mistake, sorry :) Every value from the original input should be included
comment on: http://stackoverflow.com/q/50684079

word2vec
tags question: http://stackoverflow.com/q/50643196
tags question: http://stackoverflow.com/q/50651861
tags question: http://stackoverflow.com/q/50685212
tags question: http://stackoverflow.com/q/50573054
type: Tag
tags question: http://stackoverflow.com/q/50618993
tag name: word2vec

http://stackoverflow.com/q/50642057
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50642556
tagged with: image-processing
downvote count: 1
tagged with: tensorflow
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/50673976
score: 0
has body: I am working on a robotic project that involves the detection of a human body for which I am using tensor flow and predefined data sets to create a training model. As I am new to machine learning, I am unable to properly get the output from my classifier. I require only the Person detection and want to avoid the detection of balls, laptops or other objects. Right now my webcam detects all the objects like ball, bat, laptops, tv etc. The output I require is only persons with a score of 80% and above. The code I used for using the created model is import numpy as np import os import six.moves.urllib as urllib import sys import tarfile import tensorflow as tf import zipfile from collections import defaultdict from io import StringIO from matplotlib import pyplot as plt from PIL import Image from utils import label_map_util from utils import visualization_utils as vis_util MODEL_NAME = 'ssd_mobilenet_v1_coco_11_06_2017' MODEL_FILE = MODEL_NAME + '.tar.gz' DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/' PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb' PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt') NUM_CLASSES = 90 if not os.path.exists(MODEL_NAME + '/frozen_inference_graph.pb'): print ('Downloading the model') opener = urllib.request.URLopener() opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE) tar_file = tarfile.open(MODEL_FILE) for file in tar_file.getmembers(): file_name = os.path.basename(file.name) if 'frozen_inference_graph.pb' in file_name: tar_file.extract(file, os.getcwd()) print ('Download complete') else: print ('Model already exists') detection_graph = tf.Graph() with detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='') label_map = label_map_util.load_labelmap(PATH_TO_LABELS) categories = label_map_util.convert_label_map_to_categori…
upvote count: 1
has answer: http://stackoverflow.com/a/50673976
has answer: http://stackoverflow.com/a/50642556
favorite count: 0
tagged with: python
has title: Human body detection using opencv, tensorflow and python
tagged with: opencv

http://stackoverflow.com/a/50575207
has body: Here is a sample program that can append the values to a list array = np.array([188.58, 35.56, 1.66, 21.91]) date = datetime.datetime(2018, 5, 25) data_frame = pd.DataFrame({'A': 188.58, 'B': 35.56, 'C': 1.66, 'D': 21.91}, index=pd.DatetimeIndex([date])) list_ = [] for num in range(0, 4): list_.append(float(data_frame.iloc[0, num])) print(list_) Here is our output: [188.58, 35.56, 1.66, 21.91] We can just run a for loop and then append based on iloc position. We could also do a list comprehension, but I felt as if it'd be more useful to simply show the entire loop in this example.
score: 0
answers question: http://stackoverflow.com/q/50575021
type: Answer

http://stackoverflow.com/q/50622568
has comment: http://stackoverflow.com/comment/88264442
has comment: http://stackoverflow.com/comment/88288111
tagged with: types
has body: Is there a sure-fire way to check that the class of an object is a sub-class of the desired super? For Example, in a migration script that I'm writing, I have to convert objects of a given type to dictionaries in a given manner to ensure two-way compatability of the data. This is best summed up like so: Serializable User Status Issue Test Set Step Cycle However, when I'm recursively checking objects after depickling, I receive a Test object that yields the following results: Testing data object type: type(data) {type}&lt; class'__main.Test' > Testing Class type: type(Test()) {type}&lt; class'__main.Test' > Testing object type against class type: type(Test()) == type(data) {bool}False Testing if object isinstance() of Class: isinstance(data, Test) {bool}False Testing if Class isinstance() of Super Class: isinstance(Test(), Serializable) {bool}True Testing isinstance() of Super Class:: isinstance(data, Serializable) {bool}False Interestingly, it doesn't appear to have any such problem prior to pickling as it handles the creation of dictionary and integrity hash just fine. This only crops up with depickled objects in both Pickle and Dill. For Context, here's the code in it's native environment - the DataCache object that is pickled: class DataCache(object): _hash="" _data = None @staticmethod def genHash(data): dataDict = DataCache.dictify(data) datahash = json.dumps(dataDict, sort_keys=True) return hashlib.sha256(datahash).digest() @staticmethod def dictify(data): if isinstance(data,list): datahash = [] for item in data: datahash.append(DataCache.dictify(item)) elif isinstance(data,(dict, collections.OrderedDict)): datahash = collections.OrderedDict() for key,value in datahash.iteritems(): datahash[key]= DataCache.dictify(value) elif isinstance(data, Serializable): datahash = data.toDict() else: datahash = data return datahash def __init__(self, restoreDict = {}): if restoreDict: self.__dict__.update(restoreDict) def __getinitargs__(self): return (self.__dict__) def s…
tagged with: python-2.x
has comment: http://stackoverflow.com/comment/88255987
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/88288628
type: UnansweredQuestion
tagged with: pickle
tagged with: python
has comment: http://stackoverflow.com/comment/88264521
has comment: http://stackoverflow.com/comment/88265061
has comment: http://stackoverflow.com/comment/88266697
has comment: http://stackoverflow.com/comment/88267738
has comment: http://stackoverflow.com/comment/88256120
has title: Class inheritance type checking after pickling in Python
has comment: http://stackoverflow.com/comment/88267835
score: 2
tagged with: dill
type: Question
has comment: http://stackoverflow.com/comment/88268207
downvote count: 0
has comment: http://stackoverflow.com/comment/88265704
has comment: http://stackoverflow.com/comment/88262810
favorite count: 0
has comment: http://stackoverflow.com/comment/88264741

http://stackoverflow.com/a/50610992
upvote count: 5
score: 5
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88232316
has body: There are several questions here. The main points worth mentioning: Use can use a list to hold your arguments and use *args to unpack when you supply them to add_entry. To check / avoid duplicates, you can use set to track items already added. For writing to JSON, now you have a list, you can simply iterate your list and write in one function at the end. Putting these aspects together: import json res = [] seen = set() def add_entry(res, name, element, type): # check if in seen set if (name, element, type) in seen: return res # add to seen set seen.add(tuple([name, element, type])) # append to results list res.append({'name': name, 'element': element, 'type': type}) return res args = ['xyz', '4444', 'test2'] res = add_entry(res, *args) # add entry - SUCCESS res = add_entry(res, *args) # try to add again - FAIL args2 = ['wxy', '3241', 'test3'] res = add_entry(res, *args2) # add another - SUCCESS Result: print(res) [{'name': 'xyz', 'element': '4444', 'type': 'test2'}, {'name': 'wxy', 'element': '3241', 'type': 'test3'}] Writing to JSON via a function: def write_to_json(lst, fn): with open(fn, 'a', encoding='utf-8') as file: for item in lst: x = json.dumps(item, indent=4) file.write(x + '\n') #export to JSON write_to_json(res, 'elements.json')
has comment: http://stackoverflow.com/comment/88237573
type: Answer
accepted answer of: http://stackoverflow.com/q/50610730
has comment: http://stackoverflow.com/comment/88236050
answers question: http://stackoverflow.com/q/50610730

http://stackoverflow.com/a/50649505
downvote count: 1
type: Answer
upvote count: 0
has comment: http://stackoverflow.com/comment/88377620
has comment: http://stackoverflow.com/comment/88579941
has body: Using regular expressions the below sample code will parse the text to a CSV string with the tokens: description, result, normal_value, unit. Note the list test_results is usually read from a file using: with open('name_test_file') as test_file: test_results = test_file.read().splitlines() import re tests = 'Haemoglobin 13.5 14-16 g/dl\nRandom Blood Sugar 186 60 - 160 mg/dl\n'\ 'Random Urine Sugar Nil\n¢ Blood Urea 43 14-40 mg/dl\n'\ '4 — Serum Creatinine 2.13 0.4-1.5 mg/dl\n'\ 'Serum Uric Acid 4.9 3.4-7.0 mg/dl\nSerum Sodium 142 135 - 150 meq/L\n'\ '/ Serum Potassium 2.6 3.5-5.0 meq/L\n'\ 'Total Cholesterol] 146 110 - 160 mg/dl\n'\ 'Triglycerides 162 60 - 180 mg/d]\n' test_results = tests.splitlines() for test_result in test_results: print('input :', test_result) m = re.search(r'.*?(?=[a-zA-Z][a-zA-Z])(?P&lt;description&gt;.*?)(?=[ ][0-9])' r'[ ](?P&lt;result&gt;[0-9.]*?)(?=[ ][0-9])' r'[ ](?P&lt;normal_value&gt;[ 0-9.\-]*?)(?=[ ][a-zA-Z])' r'[ ](?P&lt;unit&gt;.[ a-zA-Z/]*)', test_result) if m is not None: normal_value = m.group('normal_value') unit = m.group('unit') else: m = re.search(r'.*?(?=[a-zA-Z][a-zA-Z])(?P&lt;description&gt;.*?)(?=[ ]Nil)' r'[ ](?P&lt;result&gt;Nil).*', test_result) normal_value = '' unit = '' if m is not None: description = m.group('description') result = m.group('result') else: description = test_result result = '' write_string = description + ',' + result + ',' + normal_value + ',' + unit print(write_string)
score: -1
answers question: http://stackoverflow.com/q/50647561

http://stackoverflow.com/comment/88772527
type: AnswerComment
comment on: http://stackoverflow.com/a/50779840
score: 0
type: Comment
has text: I will try both the solutions and update the question. Thanks for helping me out.

http://stackoverflow.com/q/50593461
downvote count: 1
has body: I have a pandas.DataFrame that of events, that looks like this: event_name event_person_firstname event_person_lastname price year event_a foo bar 100 2017 event_a foo bar 42 2016 event_a foo bar 90 2016 event_a not same 80 2015 event_b random name 200 2018 event_b random name 42 2010 I want to merge the rows based on event_name and event_person_firstname + event_person_lastname so, that there is a new column named after for each year with the corresponding price (If there is no Price in the data, it should be NaN or empty - I don't care). It's hard to explain so here is the expected result after the transformation of the the DataFrame above: event_name event_person_firstname event_person_lastname 2018 2017 2016 2015 2014 2010 event_a foo bar NaN 100 42 NaN 90 NaN event_a not same NaN NaN NaN 80 NaN NaN event_b random name 200 NaN NaN NaN NaN 42 I tried grouping those duplicate elements first, but am stuck on how to proceed after that step. I hope you can help. Thanks in Advance!
type: AnsweredQuestion
score: 1
has title: Generate new feature based on duplicate
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/50593619
tagged with: pandas
favorite count: 0
upvote count: 2
accepted answer: http://stackoverflow.com/a/50593619
tagged with: python

http://stackoverflow.com/comment/88098365
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50543559
has text: You are already doing it here `bon = 0` just do that before the if with some default value.
score: 0

http://stackoverflow.com/comment/88193670
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50592137
score: 0
has text: @ThatUmbrellaGuy Good point... now where is someone with a dupehammer...

http://stackoverflow.com/a/50681323
answers question: http://stackoverflow.com/q/50679895
score: 4
upvote count: 4
downvote count: 0
has body: You can use sympy or bigfloat: &gt;&gt;&gt; x = -1.20831312e+05 &gt;&gt;&gt; &gt;&gt;&gt; import sympy as sp &gt;&gt;&gt; sp.exp(x) 4.24577787737720e-52477 &gt;&gt;&gt; &gt;&gt;&gt; import bigfloat &gt;&gt;&gt; bigfloat.exp(x) BigFloat.exact('4.2457778773771979e-52477', precision=53)
type: Answer

http://stackoverflow.com/comment/88278766
comment on: http://stackoverflow.com/a/50634075
type: Comment
type: AnswerComment
has text: Do you want to change `df1` or `df_dict`? It's two different objects. That's why I suggested _not_ to use a dictionary.
score: 0

http://stackoverflow.com/a/50574474
type: Answer
has body: No, but you can use the through attribute to explicitly define the intermediate model: Django will automatically generate a table to manage many-to-many relationships. However, if you want to manually specify the intermediary table, you can use the through option to specify the Django model that represents the intermediate table that you want to use. class ModelB(models.Model): name = models.CharField(max_length=100) model_a = models.ManyToManyField(ModelA, through='MyIntermediate') class MyIntermediate(models.Model): model_a = models.ForeignKey(ModelA, on_delete=models.CASCADE) model_b = models.ForeignKey(ModelB, on_delete=models.CASCADE) then you can refer to the intermediate model as follows: class ModelC(models.Model): name = models.CharField(max_length=100) intermediate_ab = models.ForeignKey(MyIntermediate, on_delete=models.CASCADE) Note that after this change you wont't be able to use the Django admin widget. From the documentation: When you specify an intermediary model using the through argument to a ManyToManyField, the admin will not display a widget by default. This is because each instance of that intermediary model requires more information than could be displayed in a single widget, and the layout required for multiple widgets will vary depending on the intermediate model.
answers question: http://stackoverflow.com/q/50574024
score: 0

http://stackoverflow.com/q/50573104
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/50573401
type: AnsweredQuestion
upvote count: 3
has body: Suppose I have a numpy array that maps between IDs of two item types: [[1, 12], [1, 13], [1, 14], [2, 13], [2, 14], [3, 11]] I would like to rearrange this array such that each row in the new array represents all items that matched the same ID in the original array. Here, each column would represent one of the mappings in the original array, up to a specified shape restriction on the number of columns in the new array. If we wanted to obtain this result from the above array, ensuring we only had 2 columns, we would obtain: [[12, 13], #Represents 1 - 14 was not kept as only 2 columns are allowed [13, 14], #Represents 2 [11, 0]] #Represents 3 - 0 was used as padding since 3 did not have 2 mappings The naïve approach here would be to use a for-loop that populates the new array as it encounters rows in the original array. Is there a more efficient means of accomplishing this with numpy's functionality?
accepted answer: http://stackoverflow.com/a/50574461
possible better answer: http://stackoverflow.com/a/50573401
tagged with: scipy
type: Question
tagged with: numpy
score: 3
tagged with: arrays
has answer: http://stackoverflow.com/a/50573430
downvote count: 0
has comment: http://stackoverflow.com/comment/88155858
has title: Convert numpy rows into columns based on ID
has answer: http://stackoverflow.com/a/50573225
favorite count: 0
has answer: http://stackoverflow.com/a/50574461
linked to: http://stackoverflow.com/q/38013778

http://stackoverflow.com/comment/88349096
has text: So can I just sum the cost to the previous cost function I had? Doesn't it have to be done with TF operations for it to be possible to compute the gradients?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50669262
type: Comment

http://stackoverflow.com/a/50633250
type: Answer
answers question: http://stackoverflow.com/q/50633232
has body: If you're using python just put it in a while loop and have it send the message and sleep for an hour. for sleep you can import time Something like: while true: client.send(result) sleep(3600) Important: Your bot will be 100% inactive while you sleep it, so if you use it for more than just weather this might not be the solution you're looking for.
has comment: http://stackoverflow.com/comment/88276806
score: 0
has comment: http://stackoverflow.com/comment/88276827

http://stackoverflow.com/q/50665715
has comment: http://stackoverflow.com/comment/88345845
has body: I have a table samplecol that contains (a sample): vessel_hash | status | station | speed | latitude | longitude | course | heading | timestamp | the_geom --------------+--------+---------+-------+-------------+-------------+--------+---------+--------------------------+---------------------------------------------------- 103079215239 | 99 | 841 | 5 | -5.41844510 | 36.12160900 | 314 | 511 | 2016-06-12T06:31:04.000Z | 0101000020E61000001BF33AE2900F424090AF4EDF7CAC15C0 103079215239 | 99 | 3008 | 0 | -5.41778710 | 36.12144900 | 117 | 511 | 2016-06-12T06:43:27.000Z | 0101000020E6100000E2900DA48B0F424042C3AC61D0AB15C0 103079215239 | 99 | 841 | 17 | -5.42236900 | 36.12356900 | 259 | 511 | 2016-06-12T06:50:27.000Z | 0101000020E610000054E6E61BD10F42407C60C77F81B015C0 103079215239 | 99 | 841 | 17 | -5.41781710 | 36.12147900 | 230 | 511 | 2016-06-12T06:27:03.000Z | 0101000020E61000004D13B69F8C0F424097D6F03ED8AB15C0 103079215239 | 99 | 841 | 61 | -5.42201900 | 36.13256100 | 157 | 511 | 2016-06-12T06:08:04.000Z | 0101000020E6100000CFDC43C2F71042409929ADBF25B015C0 103079215239 | 99 | 841 | 9 | -5.41834020 | 36.12225000 | 359 | 511 | 2016-06-12T06:33:03.000Z | 0101000020E6100000CFF753E3A50F42408D68965F61AC15C0 I try to fetch all points inside polygon with: poisInpolygon = """SELECT col.vessel_hash,col.longitude,col.latitude, ST_Contains(ST_GeomFromEWKT('SRID=4326; POLYGON((-15.0292969 47.6357836,-15.2050781 47.5172007,-16.2597656 29.3821751, 35.0683594 26.1159859, 38.0566406 47.6357836,-15.0292969 47.6357836))'), ST_GeomFromEWKT(col.the_geom)) FROM samplecol As col;""" The output is: (103079215291L, Decimal('40.87123100'), Decimal('29.24107000'), False) (103079215291L, Decimal('40.86702000'), Decimal('29.23967000'), False) (103079215291L, Decimal('40.87208200'), Decimal('29.22113000'), False) (103079215291L, Decimal('40.86973200'), Decimal('29.23963000'), False) (103079215291L, Decimal('40.87770800'), Decimal('29.20229900'), False) I don't figure out what is False in the results.…
tagged with: postgis
has comment: http://stackoverflow.com/comment/88345627
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88345688
has title: Points inside polygon in PostGIS
favorite count: 0
has comment: http://stackoverflow.com/comment/88345128
tagged with: postgresql
has answer: http://stackoverflow.com/a/50677690
tagged with: python
tagged with: psycopg2
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/88345811
has comment: http://stackoverflow.com/comment/88345748
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50677690

http://stackoverflow.com/comment/88302641
type: QuestionComment
comment on: http://stackoverflow.com/q/50645700
has text: so for 10, both the second and last conditions are true?
score: 0
type: Comment

http://stackoverflow.com/q/50588175
tagged with: opencv
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50598399
has title: Detecting binary blobs in OpenCV
has body: I have some colored rectangles in my image that I successfully recognize by HSV thresholding. The result looks like this: Now I want to detect the big blob as one point. I tried it with cv2.SimpleBlobDetector() and custom parameters: import cv2 import numpy as np mask = cv2.imread('mask.png') original = cv2.imread('original.png') params = cv2.SimpleBlobDetector_Params() # thresholds params.minThreshold = 10 params.maxThreshold = 200 #params.thresholdStep = 20 # filter by area params.filterByArea = True params.minArea = 1 params.maxArea = 10000 # filter by circularity params.filterByCircularity = False # filter by convexity params.filterByConvexity = False # filter by inertia params.filterByInertia = False detector = cv2.SimpleBlobDetector(params) keypoints = detector.detect(mask) img_keypoints = cv2.drawKeypoints(original, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) cv2.imwrite('keypoints.png', img_keypoints) This is how the result AND the original picture looks like: I would expect a red point sitting in the center of the green point. How can I fix this? Help is very appreciated. EDIT: I forgot to mention: Is it really necessary to generate multiple binary images in cv2.SimpleBlobDetector() since I already have a binary image as input? Is it OK to change the values to the following: params.minThreshold = 127 params.maxThreshold = 127 to reduce unnecessary CPU usage by generating binary images? EDIT2 : Please note that I'm using OpenCV 2, not 3 Thank you.
type: Question
has answer: http://stackoverflow.com/a/50598399
downvote count: 0
answer count: 1
favorite count: 0
upvote count: 2
tagged with: python

http://stackoverflow.com/q/50564209
has comment: http://stackoverflow.com/comment/88140261
accepted answer: http://stackoverflow.com/a/50564248
has comment: http://stackoverflow.com/comment/88138893
has answer: http://stackoverflow.com/a/50564263
type: Question
has comment: http://stackoverflow.com/comment/88139701
has comment: http://stackoverflow.com/comment/88138589
has answer: http://stackoverflow.com/a/50564248
favorite count: 0
has answer: http://stackoverflow.com/a/50564236
score: 0
has comment: http://stackoverflow.com/comment/88138571
has body: I have a the following string in Python: x = "['good', 'bad', 'something', 'another']" And I want to convert it into a list y, such that y[0] would give me good, and y[1] would give me bad. I tried many ways such as creating a for loop and trying x[0] or x[0][0], but all I reached was the first char, not the whole word. I also tried: y = list(x) But no help. Is there a way to do it on Python?
has comment: http://stackoverflow.com/comment/88139905
linked to: http://stackoverflow.com/q/1832940
has title: Convert Python string in a form of a list to a list
has comment: http://stackoverflow.com/comment/88138666
upvote count: 1
has comment: http://stackoverflow.com/comment/88138551
downvote count: 1
has comment: http://stackoverflow.com/comment/88138948
has comment: http://stackoverflow.com/comment/88139136
answer count: 4
has comment: http://stackoverflow.com/comment/88139917
has comment: http://stackoverflow.com/comment/88139813
tagged with: python
has answer: http://stackoverflow.com/a/50564498
possible better answer: http://stackoverflow.com/a/50564236
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/q/50551097
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88114765
tagged with: mod-wsgi
has comment: http://stackoverflow.com/comment/88113509
has title: "You have not defined a default connection" with Elastic Benstalk WSGI Deployment of Flask application with mongoengine
has body: I am stuck with first time deployment of flask application on Elastic Beanstalk. It fails establishing connection to mongodb with a error "mongoengine.connection.MongoEngineConnectionError: You have not defined a default connection". Details Application uses flask, Connexion for API config, mongoengine as mongodb glue. connexion==1.1.15 Flask==1.0.1 mongoengine==0.15.0 pymongo==3.6.1 PyJWT==1.6.1 Example shown here was deployed on Python 3.4 (but app runs on Python 3.6 as well locally as well on the Elastic Beanstalk with same set of problems) Same application works fine in local environment or on EC2 (Amazon Linux AMI) when run as a python application (with Apache ProxyPass config). Here are the relevant code: __init__.py import logging.config import connexion import mongoengine as me from api_server import encoder app = connexion.App(__name__, specification_dir='./config/') app.app.json_encoder = encoder.JSONEncoder app.add_api('api_config.yaml', arguments={'title': 'My App'}) logging.config.fileConfig("./config/logging.conf") # set the WSGI application callable to allow using uWSGI: # uwsgi --http :8080 -w app def main(): db = me.connect(alias="default", host="mongodb+srv://*[DB URL]* if __name__ == '__main__': main() application.py import logging import sys logging.basicConfig(stream=sys.stderr) sys.path.insert(0, '/opt/python/current/app/') from api_server import app as application Directory Structure Base Dir(Elastic Benstalk Root dir) -- application.py -- api_server -----__init__.py -----config --------app_config.ymal wsgi.conf apache mod_wsgi config created by ElasticBeanstalk utility on server: LoadModule wsgi_module modules/mod_wsgi.so WSGIPythonHome /opt/python/run/baselinenv WSGISocketPrefix run/wsgi WSGIRestrictEmbedded On &lt;VirtualHost *:80&gt; Alias /static/ /opt/python/current/app/static/ &lt;Directory /opt/python/current/app/static/&gt; Order allow,deny Allow from all &lt;/Directory&gt; WSGIScriptAlias / /opt/python/current/app/application.py &lt;…
type: Question
linked to: http://stackoverflow.com/q/21818610
has answer: http://stackoverflow.com/a/50614076
tagged with: flask
tagged with: mongoengine
score: 0
answer count: 1
tagged with: amazon-elastic-beanstalk
accepted answer: http://stackoverflow.com/a/50614076
tagged with: python
linked to: http://stackoverflow.com/q/419163

http://stackoverflow.com/a/50551250
has comment: http://stackoverflow.com/comment/94138667
accepted answer of: http://stackoverflow.com/q/50551096
score: 2
answers question: http://stackoverflow.com/q/50551096
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88113395
type: Answer
has comment: http://stackoverflow.com/comment/88114869
has body: Right, looking at the comment with the ongoing issue, the current workaround looks like just saving and loading weights: model.save_weights(filename) # you have to rebuild model again model.load_weights(filename) This case the saved file would not contain the architecture and you have to rebuild it every time. This isn't costly so it shouldn't be a problem. EDIT: perhaps this only affects Lambda layers, it might be a simple custom layer avoids this issue: class MyLayer(Layer): def call(self, x): return x / 255.0 - 0.5
upvote count: 2
has comment: http://stackoverflow.com/comment/88113368

http://stackoverflow.com/comment/88398405
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50694089
has text: Thanks for your input, i will try this out. Dmesg shows no information about a segfault or something else. I forgot to mention, that the stdout prints "PID killed" in the last line.

http://stackoverflow.com/a/50688229
has body: You could use tf.split, but that would mean, the param num_or_size_splits should be a multiple of length of the input if its a scalar, or the sum of the dimensions along the split dimensions should match with the length of the input (same for tf.segment_mean as well). A better approach is to use tf.extract_image_patches where those restrictions dont apply: # generate batch of inputs def get_batch(tensor, batch, k): return tf.extract_image_patches(tensor, ksizes=[1, batch, k, 1], strides=[1, batch, k, 1], rates=[1, 1, 1, 1], padding='VALID') embed_dim = 5 batch = 3 x = np.arange(200).reshape(-1, embed_dim) embeddings = tf.constant(x) train_dataset = tf.constant([0,1,2,5,6,7]) embeds = tf.nn.embedding_lookup(embeddings, train_dataset) split = tf.reshape(get_batch(embeds[None,..., None], batch, embed_dim), [-1, batch, embed_dim]) avg = tf.reduce_mean(split, 1) with tf.Session() as sess: print(sess.run(embeds)) #[[ 0 1 2 3 4] # [ 5 6 7 8 9] # [10 11 12 13 14] # [25 26 27 28 29] # [30 31 32 33 34] # [35 36 37 38 39]] print(sess.run(split)) #[[[ 0 1 2 3 4] # [ 5 6 7 8 9] # [10 11 12 13 14]] # [[25 26 27 28 29] # [30 31 32 33 34] # [35 36 37 38 39]]] print(sess.run(avg)) #[[ 5 6 7 8 9] # [30 31 32 33 34]] For 3D segments the code changes to: dim1 = 2 x = np.arange(200).reshape(-1, dim1, embed_dim) split = tf.reshape(get_batch(embeds[None,...], batch, dim1), [-1, batch, dim1, embed_dim])
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50686873
answers question: http://stackoverflow.com/q/50686873
type: AcceptedAnswer

http://stackoverflow.com/q/50606302
has title: Need to find a maximum in a list of lists
type: Question
possible better answer: http://stackoverflow.com/a/50606380
has answer: http://stackoverflow.com/a/50607794
has answer: http://stackoverflow.com/a/50606522
accepted answer: http://stackoverflow.com/a/50606524
has comment: http://stackoverflow.com/comment/88222383
has comment: http://stackoverflow.com/comment/88222355
has comment: http://stackoverflow.com/comment/88222327
has body: I found this question in 'How to Think like a computer scientist: Learning with Python 3, 3rd edition' by Peter Wentworth. I have added their solution below as well. My simple recursive function produces wrong output def maximum_in_list(L): '''Finds the maximum value from L which is a List_of_List''' item=0 for i in L: if type(i)==list: item=maximum_in_list(i) elif i&gt;item: item=i return item print(maximum_in_list([9,18,99,7,4,21,[3,5,[27,57,92],7,76],32,4])) print(maximum_in_list([2, 9, [1, 13], 8, 6])) print(maximum_in_list([2, [[100, 7], 90], [1, 13], 8, 6])) #Here the problem occurs print(maximum_in_list([[[13, 7], 90], 2, [1, 100], 8, 6])) The Books Code produces the correct one, but why the need of a flag? def r_max(nxs): largest=None first_time=True for e in nxs: if type(e)=type([]): val=r_max(e) else: val=e if first_time or val&gt;largest: largest=val first_time=False return largest I am unable to understand the requirement of a flag here, though it produces the correct result.
downvote count: 0
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50606524
has comment: http://stackoverflow.com/comment/88222422
answer count: 4
score: 2
type: AnsweredQuestion
tagged with: list
upvote count: 2
has answer: http://stackoverflow.com/a/50606380

http://stackoverflow.com/q/50664541
tagged with: pip
type: Question
has comment: http://stackoverflow.com/comment/88349163
has title: Install netifaces to local directory
score: 0
tagged with: amazon-web-services
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88342322
answer count: 0
has body: I am trying to get the python module netifaces installed locally into a project dir in order to use it with an AWS lambda function. I did it the following way: cd projectdir pip install netifaces -t . In the project I used: from netifaces import interfaces, AF_INET, ifaddresses And on lambda aws I get the error that it can not find the module netifaces. How would I resolve this?

http://stackoverflow.com/q/50654064
has body: def _store_file(self, logVal): if not os.path.exists('logs'): print("[INFO] creating directory") a = os.makedirs("logs") print("INFO create Dir result: " + str(a)) f = None try: print("{INFO} Trying to open the file for writing logs") f = open(self.conf['filename'], 'w') print("{INFO} realpath of file is: " + os.path.realpath(f.name)) print("{INFO} abs path of file is: " + os.path.abspath(f.name)) res = f.write(str(logVal)) print("INFO file write: " + str(res)) except IOError as er: print("[INFO]" + str(er)) finally: f.close() print("[INFO] WRITTING TO FILE") print("sdfjsbdfkjbsdfkjbskjdfbskjfbskjbfkjsdbsdfksds",file=open('logs/temp.txt', 'w')) I have written a middleware that sends the request data to a module that stores logs in a file debug.log inside folder logs. The code for writting to file is not giving any errors, but I can't see any folder named log nor any file named debug.log. Further when I try to see full path of the file it gives /code/logs/debug.log I have searched my whole system but can't find this path Output for above code is: web_1 | [EventTracker INFO]: log sent for storage web_1 | [INFO] present working directory: . web_1 | [INFO] creating directory web_1 | INFO create Dir resutl: None web_1 | {INFO} Trying to open the file for writing logs web_1 | {INFO} realpath of file is: /code/debug.log web_1 | {INFO} abs path of file is: /code/debug.log web_1 | INFO file write: 432 web_1 | [INFO] WRITTING TO FILE web_1 | [02/Jun/2018 06:39:16] "GET /community-view/1/ HTTP/1.1" 200 17353 web_1 | [EventTracker.sendRequestData INFO] new data object added to bucket
score: 0
has comment: http://stackoverflow.com/comment/88318901
tagged with: file-io
answer count: 1
has title: can't see the file created in python
has comment: http://stackoverflow.com/comment/88318674
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50654280
has comment: http://stackoverflow.com/comment/88319251
has comment: http://stackoverflow.com/comment/88318491
has comment: http://stackoverflow.com/comment/88318913
type: Question

http://stackoverflow.com/q/50637234
upvote count: 2
score: 0
downvote count: 2
has title: How would I loop this on Python?
has comment: http://stackoverflow.com/comment/88284502
has answer: http://stackoverflow.com/a/50637321
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50637432
answer count: 4
has answer: http://stackoverflow.com/a/50637297
has comment: http://stackoverflow.com/comment/88284460
favorite count: 0
has comment: http://stackoverflow.com/comment/88284561
has body: How would I loop this code to make it so that the user inputs the number of friends they have, their names, and in the end, the program will be able to output the information? This is what I have so far, but I believe it's incorrect. Friends = int(input("Please enter number of friends") for i in range(Friends): Name = input("Please enter friend number 1:")
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/50637397

http://stackoverflow.com/comment/88216486
type: Comment
type: QuestionComment
has text: xml= soupTop.findChildren(recursive=False) for tag in xml: s =tag.findAll("child", {"href" : re.compile(r".*")}) print (s)
comment on: http://stackoverflow.com/q/50603385
score: 0

http://stackoverflow.com/comment/88105791
type: Comment
type: QuestionComment
has text: If the problem is not caused by the IDE then avoid using it, clearly the error is not generated by pycharm.
comment on: http://stackoverflow.com/q/50547526
score: 0

http://stackoverflow.com/a/50545902
downvote count: 0
answers question: http://stackoverflow.com/q/50544310
type: Answer
score: 2
has body: with open("coordinates.json", 'w') as fp: fp.write('{') for my_dict in all_dict: if (my_dict!=all_dict[-1]): #fp.write('"key":'+json.dumps(my_dict)+',\n') else: fp.write('"key":'+json.dumps(my_dict)) fp.write('}')
upvote count: 2

http://stackoverflow.com/q/50670879
accepted answer: http://stackoverflow.com/a/50671111
has title: pandas inserting rows in a monotonically increasing dataframe using itertuples
tagged with: python
type: AnsweredQuestion
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/50671086
has body: I've been searching for a solution to this for a while, and I'm really stuck! I have a very large text file, imported as a panda dataframe containing just two columns but with hundreds of thousands to millions of rows. The columns contain packet dumps: one is the data of the packets formatted as ascii representations of monotonically increasing integers, and the second the packet time. I want to go through this dataframe, and make sure that the dataframe is monotonically increasing, and if there are missing data, to insert a new rows in order to make the list monotonically increasing. i.e the 'data' column should be filled in with the appropriate value but the time should be changed to 'NaN' or 'NULL', etc. The following is a sample of the data: data frame_time_epoch 303030303030303000 1527986052.485855896 303030303030303100 1527986052.491020305 303030303030303200 1527986052.496127062 303030303030303300 1527986052.501301944 303030303030303400 1527986052.506439335 So I have two questions: 1) I've been trying to loop through the dataframe using itertuples to try to get the next row do a comparison with the current row and if the difference s more than the 100 to add a new row, but unfortunately I've struggled with this since, there doesn't seem to be a good way to retreive the row after the one called. 2) Is there a better way (faster) way to do this other than the way I've proposed? This may be trivial, though I've really struggled with it. Thank you in advance for your help.
type: Question
answer count: 2
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/50671086
has answer: http://stackoverflow.com/a/50671111

http://stackoverflow.com/q/50670024
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/50670087
tagged with: python
score: 4
type: AnsweredQuestion
tagged with: python-3.x
type: Question
tagged with: opencv
has body: I am following this project to make a AI that plays Google Chrome Dino game. I am stuck at a point while capturing screen feed to generate training data. I am new to CV The project is supposed to supposed to break the video feed and save the CSV file in cv2.waitKey(25) &amp; 0xFF == ord('q'): condition. Which I believe is when key "q" is pressed. But nothing happens when I press 'q'. The print statement in this if condition doesn't print when I press q. Also although the console prints the print statement in 'up' ,'down' or 't' key pressed condition but the cv2.imwrite('./images/frame_(0).jpg'.format(x), img) Doesn't seem to be working as no images in the images folder are saved. Here is the code import cv2 from mss import mss import numpy as np import keyboard #Captures dinasour run for given coordinates def start(): """ Capture video feed frame by frame, crops out coods and the dino then process """ sct = mss() coordinates = { 'top': 168, 'left': 230, 'width': 624, 'height': 141 } with open('actions.csv','w') as csv: x = 0 while True: img = np.array(sct.grab(coordinates)) #crop out the dino from the image array img = img[::,75:624] #edge detection to reduce ammount of image processing work img = cv2.Canny(img, threshold1=100, threshold2=200) if keyboard.is_pressed('up arrow'): cv2.imwrite('./images/frame_(0).jpg'.format(x), img) csv.write('1\n') print('jump write') x += 1 if keyboard.is_pressed('down arrow'): cv2.imwrite('./images/frame_(0).jpg'.format(x), img) csv.write('2\n') print('duck') x += 1 if keyboard.is_pressed('t'): cv2.imwrite('./images/frame_(0).jpg'.format(x), img) csv.write('0\n') print('nothing') x += 1 # break the video feed if cv2.waitKey(25) &amp; 0xFF == ord('q'): csv.close() cv2.destroyAllWindows() print('Exited') break def play(): sct = mss() coordinates = { 'top': 168, 'left': 230, 'width': 624, 'height': 141 } img = np.array(sct.grab(coordinates)) # crop out the dinosaur from the image array img = img[::,75:615] # edge detection to reduce a…
has answer: http://stackoverflow.com/a/50670087
upvote count: 4
has title: cv2.waitKey(25) & 0xFF == ord('q'): and cv2.imwrite() not working

http://stackoverflow.com/comment/88445132
type: QuestionComment
score: 0
has text: You didn't really answer my question. I do not get how calling `client.listdir()` proves that `/foo/bar` exists. What exactly does your call of `client.listdir()` return?
comment on: http://stackoverflow.com/q/50698488
type: Comment

http://stackoverflow.com/a/50544856
has comment: http://stackoverflow.com/comment/88102715
has comment: http://stackoverflow.com/comment/88113955
has comment: http://stackoverflow.com/comment/88131524
has body: The driver.get(account_to_follow_link) causes selenium to navigate away from the page you just logged into, effectively logging you out. You can't use driver.get(). What will be more successful is finding an element on the page that is loaded by the server after login is successful, and switching to an element or context that is already loaded by the page. This means using a driver.switch_to...() probably.
answers question: http://stackoverflow.com/q/50544761
score: 0
type: Answer

http://stackoverflow.com/comment/88352808
has text: OP, maybe consider to post this kind of question on https://raspberrypi.stackexchange.com/
comment on: http://stackoverflow.com/q/50669030
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50646012
score: 1
has body: Ok, huge thanks to the Udemy course posted by Mark Winterbottom for the Django Rest Framework. I'll go ahead and leave this here for anybody else struggling with understanding some basic ideas in the Django Rest Framework. JSON data is extracted by having the frontend hit urls determined by your api. So this becomes a question of "how do I implement some search functionality that's in a url?". Django uses the Model, View, Controller pattern. A Model is what interacts with the database, and allows you to extract data from it without needing to understand how to query using actual SQL code (uses something called Object Relational Mapping to do this, or ORM, and your Models are in the model.py file). The Controller, how you interact with the pulled data to create/read/update/delete stuff in your api is saved in views.py (a bit counter intuitive, seeing as the View is what you would have in your templates folder [HTML pages and such]). You can implement something called filters in your Controller (views.py) to allow you to search by specific information to get that ?search=whateveryouresearching url, by including the following: from rest_framework import filters and adding this to your ViewSet you want to search: filter_backends = (filters.SearchFilter,) #allows for search functionality search_fields = ('name','email') #which can be any Field in your viewset This ?search=whateveryouresearching created by the filter is how some front end device will access specific searched information (such as a specific user input linke English or Mandarin inside 'language').
upvote count: 1
answers question: http://stackoverflow.com/q/50624345
type: Answer
downvote count: 0

http://stackoverflow.com/q/50600831
downvote count: 0
tagged with: xgboost
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
upvote count: 2
tagged with: scipy
type: Question
has body: I am doing a boosted classification trees vs. boosted regression trees comparison in python using xgboost as partly a project for a client and partly an internal experiment. I am using the exact same data but am modeling different targets. For the boosted classification trees model I transpose the data to give me a Good/Bad flag as the target and use the probability of someone being good/bad as the sample weight. We have used this approach successfully on other use cases, getting quite accurate models with good point predictions. By using early stopping I end up with a model with around 1000 estimators after tuning parameters etc. For the boosted regression trees model I am using the sample weight (basically a probability of someone being good/bad) as a target and end up with ~12000 estimators in the final model. Why is there such a large discrepancy between the continuous target and the discrete target in terms of model complexity?
has title: XGBRegressor model generates many more trees than a similar XGBClassifier model

http://stackoverflow.com/q/50642909
upvote count: 3
has body: I am extending a program that run without any issue in my Linux machine but not in Windows. I need to make it in Windows because the Linux machine has some issues in maintaining the Bluetooth connection. This the error I am getting: Traceback (most recent call last): File "myProject.py", line 106, in &lt;module&gt; application = Server(options, args) File "myProject.py", line 42, in __init__ super(Server, self).__init__(options, args) File "C:\Users\admin\Documents\Python\Server\lib\kernel.py", line 30, in __init__ inject.configure(self.__configure_dependencies) File "C:\Program Files\Python35\lib\site-packages\inject.py", line 102, in configure _INJECTOR = Injector(config) File "C:\Program Files\Python35\lib\site-packages\inject.py", line 230, in __init__ config(binder) File "C:\Users\admin\Documents\Python\Server\lib\kernel.py", line 58, in __configure_dependencies module = importlib.import_module(module_source, False) File "C:\Program Files\Python35\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 985, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 968, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 955, in _find_and_load_unlocked ImportError: No module named 'src\\myProject_config\\module' I am sure the problem is with the environment not with the code that is why I did not include any.
score: 0
downvote count: 3
tagged with: dependency-injection
has title: Python - programs works in Linux but not in windows
accepted answer: http://stackoverflow.com/a/50643000
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88296058
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: pip
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/50643000

http://stackoverflow.com/comment/91189548
comment on: http://stackoverflow.com/a/52119035
type: Comment
score: 1
has text: Welcome to Stack Overflow! Please check that code in your answer is possible to execute. You will probably want to fix the indentation. Also, please explain why you think that your answer is better than the existing ones. Note that your solution fails if the list contains less than two items.
type: AnswerComment

http://stackoverflow.com/q/50613346
favorite count: 0
has answer: http://stackoverflow.com/a/50613682
has body: This is the content of the textfile I am using: [{"name": "Bitcoin", "symbol": "BTC", "rank": 1, "slug": "bitcoin", "tokens": ["Bitcoin", "bitcoin", "BTC"], "id": 1}, {"name": "Ethereum", "symbol": "ETH", "rank": 2, "slug": "ethereum", "tokens": ["Ethereum", "ethereum", "ETH"], "id": 1027}, ... ] How do I retrieve each "name" element of each coin and save it into a temporary variable?
linked to: http://stackoverflow.com/q/39547056
tagged with: python
tagged with: dictionary
has title: Retrieving an element of each item in an array
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50613972
type: UnansweredQuestion
upvote count: 1
tagged with: http://stackoverflow.com/tag/json
type: Question
answer count: 2
downvote count: 0
score: 1

http://stackoverflow.com/q/50553725
tagged with: python
has body: I'm trying to run this command in python. BB = os.environ["BB"] BBDISP = os.environ["BBDISP"] NOW = datetime.datetime.now() COLOR="green" MSG="Widgets loaded successfully." NODE="server01" retvalue = os.popen("BB BBDISP \"status NODE.thisIsATest COLOR str(NOW) MSG \"").readlines() print retvalue And I'm getting the following error: sh: 1: BB: not found But I"m able to print that variable to screen. print BB The output is /usr/lib/xymon/server/bin/xymon
has comment: http://stackoverflow.com/comment/88118241
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50553862
has comment: http://stackoverflow.com/comment/88118268
type: Question
accepted answer: http://stackoverflow.com/a/50553862
has answer: http://stackoverflow.com/a/50553844
tagged with: python-2.7
score: 0
answer count: 2
has title: Can't run os.popen in python script
possible better answer: http://stackoverflow.com/a/50553844
has comment: http://stackoverflow.com/comment/88118220

http://stackoverflow.com/q/50665558
tagged with: python-3.x
type: Question
answer count: 2
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/50665612
score: 0
has answer: http://stackoverflow.com/a/50665613
upvote count: 1
has comment: http://stackoverflow.com/comment/88341095
downvote count: 1
has comment: http://stackoverflow.com/comment/88341044
possible better answer: http://stackoverflow.com/a/50665613
has body: I'm using Python 3.6. I'm having an issue with reformatting dates. My code is currently processing 610 dates, but the code throws a Value Error on dates containing the month of August. ERROR:time data 'Augu 30, 2017' does not match format '%B %d, %Y' Here's the HTML string that my code is trying to reformat. August 30th, 2017 The date in this string is August 30th, 2017, so what is causing the Value Error? Here's my code: publishedDateFormat = table.find('div', {'class': 'date'}) for date in publishedDateFormat.find('span'): cleanDate = date.replace('nd', '').replace('rd', '').replace('st', '').replace('th', '') locale.setlocale(locale.LC_ALL, 'en_US') publishedDate = datetime.datetime.strptime(cleanDate, '%B %d, %Y').strftime('%m%d%Y') list_of_cells.append(publishedDate)
accepted answer: http://stackoverflow.com/a/50665612
has title: ValueError: time data does not match format
type: AnsweredQuestion
favorite count: 0

http://stackoverflow.com/comment/88226069
score: 1
comment on: http://stackoverflow.com/q/50608053
has text: Unless you explain or show how we can reconstruct the hierarchy, all we can basically do is a simple counting of the labels. Also, it is important to know what you want to show. Talking about a distribution: You can count how many labels are present at each node for example and look at the distribution of labels at each level of the hierarchy but we need to know how we can do that with your labels.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50614104
upvote count: 2
has body: There are a few errors in you code. Use a return statement to output the dictionary. The while-loop does not loop as you are breaking on the first iteration. Use an if-statement to check if the line is empty instead. The last entries in the client_details dict are overwritten on each iteration. Create a new entry instead, probably using the client_id as key. It is recommended you use a with context manager to open your file. It is preferable to provide the name of your file to your function and let it open it instead of having a globally opened file. Here is a fixed version of your code. def get_all_client_id(file): client_details = {} with open(file, 'r') as f: for line in f: element = line.strip().split(',') if element: client_id, lat, long, *more = element client_details[client_id] = {'lat': lat, 'long': long} return client_details clients_dict = get_all_client_id("C:\\Users\\clients.txt")
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88251107
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50613862
accepted answer of: http://stackoverflow.com/q/50613862
has comment: http://stackoverflow.com/comment/88238556

http://stackoverflow.com/a/50589747
answers question: http://stackoverflow.com/q/50576770
has comment: http://stackoverflow.com/comment/88194590
has comment: http://stackoverflow.com/comment/88191903
has comment: http://stackoverflow.com/comment/88195181
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/88194675
score: 2
has comment: http://stackoverflow.com/comment/88190895
has body: The last parameter instantiates a C integer (c_int(0)) and passes it as a pointer. This matches the last parameter definition loosely. It should be a DWORD which is typically defined as unsigned long (c_ulong in ctypes). Using ctypes.byref is more efficient than creating a pointer. The parameter is used to return the thread ID as an output parameter, so need the address of an instance of the correct C type to store the ID. Here's a working example that explicitly defines then inputs/outputs of each function with ctypes. Note that ctypes has pre-defined Windows types in wintypes: import ctypes as c from ctypes import wintypes as w LPTHREAD_START_ROUTINE = c.WINFUNCTYPE(w.DWORD,w.LPVOID) SIZE_T = c.c_size_t k32 = c.WinDLL('kernel32') test = c.WinDLL('test') CreateThread = k32.CreateThread CreateThread.argtypes = w.LPVOID,SIZE_T,LPTHREAD_START_ROUTINE,w.LPVOID,w.DWORD,w.LPDWORD CreateThread.restype = w.HANDLE WaitForSingleObject = k32.WaitForSingleObject WaitForSingleObject.argtypes = w.HANDLE,w.DWORD WaitForSingleObject.restype = w.DWORD sa = None # No security specified. None == NULL pointer. stack = 0 # Use default stack start = LPTHREAD_START_ROUTINE(test.func) param = 0x12345 flags = 0 # start thread immediately tid = w.DWORD() h = CreateThread(sa,stack,start,param,flags,c.byref(tid)) WaitForSingleObject(h,1000) # wait for the thread to exit. Here's the code for a simple C function to run as a thread: #include &lt;stdio.h&gt; __declspec(dllexport) unsigned long __stdcall func(void* p) { printf("%p\n",p); return 0; } Here's the output: 0000000000012345
has comment: http://stackoverflow.com/comment/88194552
accepted answer of: http://stackoverflow.com/q/50576770
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88287075
type: Comment
score: 0
type: AnswerComment
has text: IDK, I am using anaconda since before miniconda existed; I've never looked into it.
comment on: http://stackoverflow.com/a/50638040

http://stackoverflow.com/a/59190824
type: Answer
has body: This didn't work for me. I hade to write the following in the .bat file for %%i in (/Shutdown/*.py) do @python.exe C:/Shutdown/%%i I put the .bat file in the shutdown folder and addded this to the PATH. But I guess it doesn't matter if the .bat file is in another folder which is also included in the PATH ofcourse. In the gpedit.msc I had to add the link to the .bat file in the User Configuration -> Windows settings -> Script field, not in the Computer Configuration. I'm running Windows 10, and Python 3.7
score: 0
has comment: http://stackoverflow.com/comment/112146080
answers question: http://stackoverflow.com/q/50601650

http://stackoverflow.com/comment/88354185
type: Comment
has text: runs fine for me except for that pen typo. Could be an IDE problem; what IDE are you using
score: 0
comment on: http://stackoverflow.com/q/50672193
type: QuestionComment

http://stackoverflow.com/q/50618066
has answer: http://stackoverflow.com/a/50618763
type: AnsweredQuestion
score: 1
tagged with: dataframe
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50618087
tagged with: sorting
favorite count: 0
tagged with: pandas
has body: Here's my data No Candidate_A Candidate_B Candidate_C 1 8 9 12 2 18 9 12 3 9 9 7 Here's the result what I want, the logic is Candidate_A is more than Candidate_B, Candidate_B wins, if not Candidate_A, basically it just sorting algorithm No Candidate_A Candidate_B Candidate_C Result 1 8 9 12 Candidate_C 2 18 9 12 Candidate_A 3 9 9 7 Candidate_A
has comment: http://stackoverflow.com/comment/88247711
has title: How do I get winner voter on pandas based on sorting algorithm
accepted answer: http://stackoverflow.com/a/50618087
has comment: http://stackoverflow.com/comment/88247770
upvote count: 1
possible better answer: http://stackoverflow.com/a/50618763
tagged with: python

http://stackoverflow.com/comment/88262676
score: 0
comment on: http://stackoverflow.com/q/50626107
type: Comment
type: QuestionComment
has text: findElements would return a list of WebElements, you need to iterate over this list and call `.getAttribute('id')` on individual Webelement

selenium-webdriver
tags question: http://stackoverflow.com/q/50558066
tags question: http://stackoverflow.com/q/50691692
tags question: http://stackoverflow.com/q/50679623
tags question: http://stackoverflow.com/q/50653270
tags question: http://stackoverflow.com/q/50543364
tags question: http://stackoverflow.com/q/50692358
tags question: http://stackoverflow.com/q/50596456
tags question: http://stackoverflow.com/q/50574869
tags question: http://stackoverflow.com/q/50629595
tags question: http://stackoverflow.com/q/50685736
tags question: http://stackoverflow.com/q/50647051
tags question: http://stackoverflow.com/q/50637373
tags question: http://stackoverflow.com/q/50689167
tag name: selenium-webdriver
tags question: http://stackoverflow.com/q/50613391
tags question: http://stackoverflow.com/q/50679032
tags question: http://stackoverflow.com/q/50679605
tags question: http://stackoverflow.com/q/50682811
tags question: http://stackoverflow.com/q/50629337
tags question: http://stackoverflow.com/q/50544761
tags question: http://stackoverflow.com/q/50619029
tags question: http://stackoverflow.com/q/50611045
tags question: http://stackoverflow.com/q/50668689
tags question: http://stackoverflow.com/q/50560189
tags question: http://stackoverflow.com/q/50605373
type: Tag
tags question: http://stackoverflow.com/q/50640686
tags question: http://stackoverflow.com/q/50634788
tags question: http://stackoverflow.com/q/50616631
tags question: http://stackoverflow.com/q/50658428
tags question: http://stackoverflow.com/q/50674355
tags question: http://stackoverflow.com/q/50692333
tags question: http://stackoverflow.com/q/50643610

http://stackoverflow.com/a/67199394
downvote count: 1
upvote count: 16
has comment: http://stackoverflow.com/comment/130845429
answers question: http://stackoverflow.com/q/50571317
type: Answer
has comment: http://stackoverflow.com/comment/130853493
has comment: http://stackoverflow.com/comment/132432980
has body: TLDR; I solved the problem with a custom patch Explanation The problem comes from the Google bot recognition system. As other similar systems do, it stops serving too frequent requests coming from suspicious clients. Some of the features used to recognize trustworthy clients are the presence of specific headers generated by the javascript code present on the web pages. Unfortunately, the python requests library does not provide such a level of camouflage against those bot recognition systems since javascript code is not even executed. So the idea behind my patch is to leverage the headers generated by my browser interacting with google trends. Those headers are generated by the browser meanwhile I am logged in using my Google account, in other words, those headers are linked with my google account, so for them, I am trustworthy. Solution I solved in the following way: First of all you must use google trends from your web browser while you are logged in with your Google Account; In order to track the actual HTTP GET made: (I am using Chromium) Go into "More Tools" -> "Developers Tools" -> "Network" tab. Visit the Google Trend page and perform a search for a trend; it will trigger a lot of HTTP requests on the left sidebar of the "Network" tab; Identify the GET request (in my case it was /trends/explore?q=topic&geo=US) and right-click on it and select Copy -> Copy as cURL; Then go to this page and paste the cURL script on the left side and copy the "headers" dictionary you can find inside the python script generated on the right side of the page; Then go to your code and subclass the TrendReq class, so you can pass the custom header just copied: from pytrends.request import TrendReq as UTrendReq GET_METHOD='get' import requests headers = { ... } class TrendReq(UTrendReq): def _get_data(self, url, method=GET_METHOD, trim_chars=0, **kwargs): return super()._get_data(url, method=GET_METHOD, trim_chars=trim_chars, headers=headers, **kwargs) Remove any "import TrendReq" fr…
has comment: http://stackoverflow.com/comment/132432923
has comment: http://stackoverflow.com/comment/137034431
score: 15

http://stackoverflow.com/comment/88191379
has text: Can you file a bug at github.com/microsoft/ptvsd ?
comment on: http://stackoverflow.com/q/50570299
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/102072944
comment on: http://stackoverflow.com/a/57224325
score: 0
type: AnswerComment
has text: Do you know if it is possible to add multiple texts to the pop up? i.e. `df[['latitude', 'longitude','use_code_name1','use_code_name2','use_code_name3']` ?
type: Comment

http://stackoverflow.com/comment/88114328
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50551147
type: Comment
has text: I need n'th row of Close. So for example 100 th Close's std will be std of [75:100]

http://stackoverflow.com/q/50549841
has answer: http://stackoverflow.com/a/50550181
type: Question
has title: Next Button XPath Changes on Page #2, Won't Loop
accepted answer: http://stackoverflow.com/a/50550181
tagged with: python
score: 0
answer count: 2
tagged with: selenium
has body: I have a script that loops through a series of elements for titles, then clicks "next" to load the next series of elements to be scraped. The issue is the xpath of the "next" button changes on page 2 and quite possibly on page 3. I cannot use find by class or find by ID because there are more than one occurrence of those class/ID names. Once it cannot find the "next" button on the 2nd page the script errors out. while True: deal_title = browser.find_elements_by_xpath("//a[@id='dealTitle']/span") titles = [] for title in deal_title: titles.append(title.text) deal_link = browser.find_elements_by_xpath("//div[@class='a-row dealDetailContainer']/div/a[@id='dealTitle']") links = [] for link in deal_link: links.append(link.get_attribute('href')) deal_image = browser.find_elements_by_xpath("//a[@id='dealImage']/div/div/div/img") images = [] for image in deal_image: images.append(image.get_attribute('src')) deal_price = browser.find_elements_by_xpath("//div[@class='a-row priceBlock unitLineHeight']/span") prices = [] for price in deal_price: prices.append(price.text) try: #clicks next button - this is the xpath for the page 1 button browser.find_element_by_xpath("//span[@class='a-declarative']/div[2]/ul/li[@class='a-last']/a").click() except NoSuchElementException: break Below is the xpath for the next button on page 2: browser.find_element_by_xpath("//span[@class='a-declarative']/div[1]/ul/li[@class='a-last']/a").click()
possible better answer: http://stackoverflow.com/a/50556347
has answer: http://stackoverflow.com/a/50556347
type: AnsweredQuestion

http://stackoverflow.com/comment/88288862
type: QuestionComment
has text: The hard part is actually defining "best". I can't see that there is a natural definition. Additionally, depending on your data source, you might also consider relaxing the "enclosed" parts (e.g. data from physical measurements might produce outliers).
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50638823

http://stackoverflow.com/a/50545522
has body: General advice: Try using python's inbuilt features like lambda, zip, map, filter, etc. as frequent as possible. &gt;&gt;&gt; a = range(27) &gt;&gt;&gt; b = range(3) &gt;&gt;&gt; result = [map(lambda x: x * b[i], a[9*i: 9*(i+1)]) for i in xrange(len(b))] &gt;&gt;&gt; result [[0, 0, 0, 0, 0, 0, 0, 0, 0], [9, 10, 11, 12, 13, 14, 15, 16, 17], [36, 38, 40, 42, 44, 46, 48, 50, 52]]
type: Answer
answers question: http://stackoverflow.com/q/50545386
score: 0

http://stackoverflow.com/comment/88250950
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50620564
has text: you mean data or the declare of the model class?

http://stackoverflow.com/a/50632508
answers question: http://stackoverflow.com/q/50631957
downvote count: 1
score: -1
has body: With a bit research and @zvone and @DeepSpace comments to the original post. I found out this: Versions are not floating point numbers, hence they do not fall under category of decimal numbers, hence the arithmetic of decimal numbers won't apply to versioning. According to semantic versioning 2.0.0 (https://semver.org/#spec-item-2) a version number should not be followed by leading zeros. Hence 2.06 is a bad versioning way to go. It should have been2.1, 2.6 etc to begin with. If you follow semantic versioning 2.0.0 you can avoid this dilema.
upvote count: 0
type: Answer

http://stackoverflow.com/comment/120908430
comment on: http://stackoverflow.com/a/60515993
type: Comment
score: 6
has text: Every 6 months I find my way back to this answer after forgetting this trick lol, thanks Alex!
type: AnswerComment

http://stackoverflow.com/comment/88260275
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50624679
has text: Very well, got it.
score: 0

http://stackoverflow.com/comment/88316211
type: Comment
comment on: http://stackoverflow.com/q/50652724
score: 0
type: QuestionComment
has text: Is it mandatory that the solution is able to terminate even those functions which are already started when the first N finish? Or is it enough to say "No new jobs will start after the first N finished, but already-started jobs will be allowed to complete even if we ignore their results"? If you need the former, see: https://stackoverflow.com/questions/42782953/python-concurrent-futures-how-to-make-it-cancelable - it is not directly possible using the library you are using.

http://stackoverflow.com/q/50586045
has comment: http://stackoverflow.com/comment/88181413
tagged with: python
has answer: http://stackoverflow.com/a/50586233
type: UnansweredQuestion
tagged with: encryption
has comment: http://stackoverflow.com/comment/88181475
type: Question
tagged with: encoding
answer count: 1
has body: I'm trying to create an API with token to communicate between an Raspberry Pi and a Webserver. Right now i'm tring to generate an Token with Python. from Crypto.Cipher import AES import base64 import os import time import datetime import requests BLOCK_SIZE = 32 BLOCK_SZ = 14 #!/usr/bin/python salt = "123456789123" # Zorg dat de salt altijd even lang is! (12 Chars) iv = "1234567891234567" # Zorg dat de salt altijd even lang is! (16 Chars) currentDate = time.strftime("%d%m%Y") currentTime = time.strftime("%H%M") PADDING = '{' pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s))) DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING) secret = salt + currentTime cipher=AES.new(key=secret,mode=AES.MODE_CBC,IV=iv) encode = currentDate encoded = EncodeAES(cipher, encode) print (encoded) The problem is that the output of the script an exta b' adds to every encoded string.. And on every end a ' C:\Python36-32&gt;python.exe encrypt.py b'Qge6lbC+SulFgTk/7TZ0TKHUP0SFS8G+nd5un4iv9iI=' C:\Python36-32&gt;python.exe encrypt.py b'DTcotcaU98QkRxCzRR01hh4yqqyC92u4oAuf0bSrQZQ=' Hopefully someone can explain what went wrong. FIXED! I was able to fix it to decode it to utf-8 format. sendtoken = encoded.decode('utf-8')
has title: Python adds extra to crypt result
has comment: http://stackoverflow.com/comment/88181981
score: 0
has comment: http://stackoverflow.com/comment/88181756

pyside2
tags question: http://stackoverflow.com/q/50626583
type: Tag
tags question: http://stackoverflow.com/q/50580039
tag name: pyside2
tags question: http://stackoverflow.com/q/50582560
tags question: http://stackoverflow.com/q/50609986

http://stackoverflow.com/a/50587003
score: 3
downvote count: 0
has body: Use Boolean Indexing and the condition would be arr[0] != 0: arr[:, arr[0] != 0] #array([[ 51.78 , 17. ], # [ 51.63 , 13. ], # [ 51.77 , 52. ], # [ 52.02 , 34. ], # [ 49.955, 77. ], # [ 50.75 , 48. ], # [ 51.1 , 12. ], # [ 51.52 , 13. ], # [ 50.48 , 17. ], # [ 51.71 , 97. ]])
type: AcceptedAnswer
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/50586926
accepted answer of: http://stackoverflow.com/q/50586926

http://stackoverflow.com/comment/88165352
type: Comment
comment on: http://stackoverflow.com/a/50577708
type: AnswerComment
has text: I am using Django 1.9.12
score: 0

http://stackoverflow.com/a/50580254
type: Answer
has comment: http://stackoverflow.com/comment/88170927
has body: If you have the binary data on hand (b, right?) and you are only interested in one field, why can you not just access that field directly? last_traded_price_bytes = b[88:98] Might want to double check those numbers, pretty sure it started at the 88th byte.
answers question: http://stackoverflow.com/q/50580050
accepted answer of: http://stackoverflow.com/q/50580050
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/88170975

psycopg2
tags question: http://stackoverflow.com/q/50666600
type: Tag
tags question: http://stackoverflow.com/q/50697030
tags question: http://stackoverflow.com/q/50665565
tags question: http://stackoverflow.com/q/50570865
tags question: http://stackoverflow.com/q/50665715
tag name: psycopg2

http://stackoverflow.com/comment/88236539
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50613188
score: 0
has text: Exactly that; a datetime. `with open('{}_data.json'.format(datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')), 'w') as outfile:` but with some better organisation/PEP8 in the code.

http://stackoverflow.com/q/50642532
favorite count: 0
tagged with: python
type: AnsweredQuestion
has body: I am developing unit tests to an existing library, and I would like to test if the arguments a function is called with match certain criteria. In my case the function to test is: class ... def function(self): thing = self.method1(self.THING) thing_obj = self.method2(thing) self.method3(thing_obj, 1, 2, 3, 4) For the unit tests I have patched the methods 1, 2 and 3 in the following way: import unittest from mock import patch, Mock class ... def setUp(self): patcher1 = patch("x.x.x.method1") self.object_method1_mock = patcher1.start() self.addCleanup(patcher1.stop) ... def test_funtion(self) # ??? In the unit test I would like to extract the arguments 1, 2, 3, 4 and compare them e.g. see if the 3rd argument is smaller than the fourth one ( 2 &lt; 3). How would I go on about this with mock or another library?
has answer: http://stackoverflow.com/a/50723240
tagged with: python-unittest
type: Question
upvote count: 4
has title: Python unittest check function call args
tagged with: mocking
downvote count: 0
score: 4
accepted answer: http://stackoverflow.com/a/50723240
tagged with: python-2.7
answer count: 1

http://stackoverflow.com/a/50636165
type: AcceptedAnswer
upvote count: 7
type: Answer
answers question: http://stackoverflow.com/q/50635960
has body: You actually can remove items from a list while iterating over it but do read links by @ReblochonMasque. Here is one way of removing duplicates: def remove_items_from_list(ordered_list, temp): n = len(ordered_list) for i in range(n - 1, -1, -1): if ordered_list[i] in temp: del ordered_list[i] Then &gt;&gt;&gt; remove_items_from_list(my_list, temp) &gt;&gt;&gt; print(my_list) [2, 3, 4] However, one of the easiest ways of solving your problem is to use sets: list(set(my_list) - set(temp)) When using this approach, order of items in the resulting list may be arbitrary. Also, this will create a new list instead of modifying an existing list object. If order is important - use list comprehension: [v for v in my_list if v not in temp]
accepted answer of: http://stackoverflow.com/q/50635960
downvote count: 0
score: 7
has comment: http://stackoverflow.com/comment/88289782

http://stackoverflow.com/a/56224367
downvote count: 0
answers question: http://stackoverflow.com/q/50557234
has comment: http://stackoverflow.com/comment/137619672
has body: Modify MySQL encryption: ALTER USER 'lcherukuri'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
type: Answer
upvote count: 6
score: 6

http://stackoverflow.com/comment/88430367
has text: Thanks @jxc. If I wanted to use that df for future work what output code would I use?
type: Comment
comment on: http://stackoverflow.com/a/50659514
type: AnswerComment
score: 0

http://stackoverflow.com/q/50552065
answer count: 3
has comment: http://stackoverflow.com/comment/88114972
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/50552084
score: -1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50552084
has answer: http://stackoverflow.com/a/50552188
downvote count: 2
tagged with: text-formatting
upvote count: 1
has body: I have 100 lines where each line consists of some sentences.Each line starts with some characters followed by -rrb-. How can I format the text so that each line actually starts after the -rrb-. Line Example: Lorem ipsum -lrb- dolor -rrb- sit amet, consectetur adipiscing elit. Nam quis dolor a sapien efficitur fermentum egestas ut elit. Nulla porttitor diam id orci bibendum volutpat. Quisque imperdiet euismod neque in efficitur. I want for this and every line: sit amet, consectetur adipiscing elit. Nam quis dolor a sapien efficitur fermentum egestas ut elit. Nulla porttitor diam id orci bibendum volutpat. Quisque imperdiet euismod neque in efficitur. So I want to start this and every 100 lines from the word after -rrb- ( "sit" for this example).
has answer: http://stackoverflow.com/a/50552238
type: Question
has comment: http://stackoverflow.com/comment/88114926
has title: How to cut first characters until a special character found?
accepted answer: http://stackoverflow.com/a/50552188

http://stackoverflow.com/comment/88426710
score: 0
type: Comment
type: QuestionComment
has text: Please show some actual (possibly abbreviated) values, so one can test a recovery strategy.
comment on: http://stackoverflow.com/q/50693871

http://stackoverflow.com/a/50667050
score: 3
upvote count: 3
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50667036
has comment: http://stackoverflow.com/comment/88344390
answers question: http://stackoverflow.com/q/50667036
downvote count: 0
has body: I believe that you want: print (df['tweet text'].str[-12:-1]) 0 example.com Name: tweet text, dtype: object More general solution is with regex with str.findall for list of all links and if necessary select first by indexing with str[0]: pat = r'(?:http|ftp|https)://(?:[\w_-]+(?:(?:\.[\w_-]+)+))(?:[\w.,@?^=%&amp;:/~+#-]*[\w@?^=%&amp;/~+#-])?' print (df['tweet text'].str.findall(pat).str[0]) 0 https://example.com Name: tweet text, dtype: object

http://stackoverflow.com/comment/88163316
type: AnswerComment
has text: table structure is as below - `db.define_table('spr_details', Field('SPR_name', 'string', unique=True, notnull=True), Field('Object_location',notnull=True), Field('NSK_System',notnull=True,), primarykey = ['SPR_name'],migrate=True)` `db.define_table('my_master_table', Field('Test_id',notnull=True), Field('Test_suite',notnull=True), Field('Test_category',notnull=True), Field('Test_unit',notnull=True), Field('Test_case',notnull=True), Field('Applicability', 'reference spr_details.SPR_name'),migrate=True)`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50569335

http://stackoverflow.com/comment/88391444
score: 0
has text: @StephenRauch No
type: QuestionComment
comment on: http://stackoverflow.com/q/50690650
type: Comment

http://stackoverflow.com/comment/88128283
has text: There is no error output, it will stop for few seconds then keep showing the next frame.
comment on: http://stackoverflow.com/q/50558627
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50631650
has body: Use something like this: import json from django.http import JsonResponse def index(request): if request.method == 'GET': context = { 'entry_list': Entry.objects.filter()[:5], } return JsonResponse(json.dumps(context), safe=False) else: return JsonResponse({"err_msg": "Failed"})
score: 2
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/88273826
answers question: http://stackoverflow.com/q/50631477
has comment: http://stackoverflow.com/comment/88274439
has comment: http://stackoverflow.com/comment/88273602
type: Answer

http://stackoverflow.com/q/50558244
linked to: http://stackoverflow.com/q/43636321
has title: Optimizer doesn't consistently improve training accuracy
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/50559589
score: 0
has body: I'm trying to train a logistic regression model, but no matter how small I make the training set, the training accuracy does not increase consistently. I've shrunk the training set to just 3 examples, and the model sometimes starts at 66.66% training accuracy and ends with 33.33%. Other times it starts with 0% and ends with 66.66%. It never reaches 100% accuracy. It has the same behavior with training sets of size 32, 200, and 400, with starting accuracy around 50% and ending accuracy between 40% and 60%. The model code is as follows: def get_batch(index, tensors, batch_size, nItems): xs, ys = tensors begin = index * batch_size end = min((index+1)*batch_size, nItems) y_b = ys[begin:end] (inds, vals, dsize) = xs nInds = inds[(begin &lt;= inds[:,0]) &amp; (inds[:,0] &lt; end)] - np.array([begin, 0]) nVals = vals[:nInds.shape[0]] nDsize = (end - begin, dsize[1]) x_b = tf.SparseTensorValue(nInds, nVals, nDsize) return (x_b, y_b) class OneLayerNet(object): def __init__(self, num_feats, num_outputs): self.batch_size = 3 self.epochs = 100 self.eta = 0.01 self.reg_const = 0 self.x = tf.sparse_placeholder(tf.float64, name="placeholderx") # num_sents x num_feats self.y = tf.placeholder(tf.float64, name="placeholdery") # 1 x num_sents self.w = tf.Variable(tf.random_normal([num_feats, num_outputs], stddev=0.01, dtype=tf.float64)) # num_feats x 1 self.b = tf.Variable(tf.zeros([num_outputs], dtype=tf.float64)) self.wx = tf.sparse_tensor_dense_matmul(self.x, self.w) self.scores = tf.add(self.wx, self.b) self.probs = 1 / (1 + tf.exp(-self.scores)) self.probs = tf.clip_by_value(self.probs, 0.001, .999) self.loss_vect = self.y*tf.log(self.probs) + (1-self.y)*tf.log(1-self.probs) self.loss = -tf.reduce_mean(self.loss_vect) # + self.reg_const/2 * tf.square(tf.norm(self.w)) self.optimizer = tf.train.AdamOptimizer(learning_rate=self.eta).minimize(self.loss) self.session = tf.Session() self.session.run(tf.global_variables_initializer()) def train(self, x, y, loss_graph_file): session = se…
answer count: 1
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50662579
accepted answer: http://stackoverflow.com/a/50662607
type: Question
tagged with: syntax-error
answer count: 1
has body: I'm new in python. I want to make a new array for saving types of every part of my JSON data. And check again, if any part have one type in that array then save in another file text call 'type0.txt' , 'type1.txt', ... . So here is my code. from __future__ import print_function import json # Remember to check the path to articles.json relative to this file before executing with open('articles.json') as json_data: # Load JSON articles = json.load(json_data) print(len(articles), "Articles loaded succesfully") # Loop through every article in the json file typeLabel = [] for article in articles: typeL = article["type"] typeLabel.append(typeL) typeLabel = set(typeLabel) typeLabel = list(set(typeLabel)) seen = set() resultType = [] for item in typeLabel: if item not in seen: seen.add(item) resultType.append(item) for article in articles x = 0 for i in range(0,len(resultType) - 1): if article["type"] = resultType[i]: filePathName = resultType[i] + x + '.txt' with open(filePathName, 'w') as reader: json.dump(article["content"], reader) x += 1 pass And first I get an error for article in articles ^ SyntaxError: invalid syntax Then I'm not sure if I write the rest are right syntax or not, so can you help me fix my code. Many thanks!!
downvote count: 0
favorite count: 0
tagged with: python
upvote count: 3
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/50662607
has title: Save many files text from JSON data in python
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/q/50569748
has comment: http://stackoverflow.com/comment/88149943
tagged with: python
has answer: http://stackoverflow.com/a/50570738
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88149717
has body: So, i need to update ComboBox in MainWindow after Another Window is closed. here's button's function to open another window import AnotherWindow as cl def inputclass(self): self.InputClass = cl.InputWindow() self.InputClass.show() self.boxclass() def boxclass(self): self.BoxClass.clear() with open('data/ClassSuara.csv','rb') as f : reader = csv.reader(f) listsuara = list(reader) for a in listsuara: cek = str(a) b = cek[2:-2] self.BoxClass.addItem(b) here AnotherWindow Window class InputWindow(QtGui.QMainWindow, gui.Ui_KelasSuara): def __init__(self): QtGui.QMainWindow.__init__(self) gui.Ui_KelasSuara.__init__(self) self.setupUi(self) self.BtnTambah.clicked.connect(self.Tambahkan) def Tambahkan(self): self.listClass.clear() ClassSuara = open('data/ClassSuara.csv','a') ClassSuara.write(self.lineClass.text()+'\n') ClassSuara.close() But after AnotherWindow is closed, self.boxclass() wont execute
type: Question
has comment: http://stackoverflow.com/comment/88150378
tagged with: qdialog
tagged with: pyqt4
has title: How do i know if another window is closed?
accepted answer: http://stackoverflow.com/a/50570738
has comment: http://stackoverflow.com/comment/88150548
score: 0
has comment: http://stackoverflow.com/comment/88149476
has comment: http://stackoverflow.com/comment/88149673
answer count: 1

http://stackoverflow.com/comment/88184633
comment on: http://stackoverflow.com/q/50587433
has text: In the end you want to return a (sorted) `list`, so every return statement has to return a `list`, since you will call this recursively and aggregate the returned values. Your outermost function call (so the first function call) will then return the sorted list. You can easily concatenate two lists using `list.extend`, mutating the calling instance, or the binary `+` operator, returning a new list of the concatenation of its arguments. Take a look how the recursion is done in case of the Fibonacci sequence here: https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50553897
has comment: http://stackoverflow.com/comment/88123355
type: Answer
downvote count: 0
has body: You are messing up while offering to the queue. Initially you are doing q.put((root,level)) and some other places you are doing q.put(level + 1,node.left),q.put(level + 1,node.right). See the following corrected code: from collections import defaultdict from queue import Queue class Node: def __init__(self,data): self.val = data self.left = None self.right = None def levelOrderTraversal(root): result = defaultdict(list) if not root: return result q = Queue() level = 0 q.put((level, root)) while not q.empty(): e = q.get() level = e[0] #Throws error: TypeError: 'Node' object does not support indexing node = e[1] result[level].append(node.val) if node.left: q.put((level + 1,node.left)) if node.right: q.put((level + 1,node.right)) return result def test1(): root = Node(1) root.left = Node(2) root.right = Node(3) return levelOrderTraversal(root) print(test1()) # prints defaultdict(&lt;class 'list'&gt;, {0: [1], 1: [2, 3]}) Working code in Ideone https://ideone.com/Xy0OR8
score: 1
answers question: http://stackoverflow.com/q/50553804
upvote count: 1
has comment: http://stackoverflow.com/comment/88123429
has comment: http://stackoverflow.com/comment/88186991

amazon-elastic-beanstalk
tag name: amazon-elastic-beanstalk
tags question: http://stackoverflow.com/q/50551097
type: Tag
tags question: http://stackoverflow.com/q/50548328
tags question: http://stackoverflow.com/q/50616566
tags question: http://stackoverflow.com/q/50575729

http://stackoverflow.com/comment/88131763
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50560652
has text: Can you create sample data and expected output?

http://stackoverflow.com/q/50543573
tagged with: elastic-stack
score: -1
has body: I have a JSON file with nested JSON objects. I want to index this JSON file into my Elasticsearch via Logstash, but Elasticsearch doesn't support nested JSON (yet). Is there a way in python to convert these nested objects to simple JSON, that is searchable? The JSON I'm using is created by a python script that uses Nmap and determine hosts on a network. At this moment the ports array cannot be search, which is the whole purpose of my project. This is because a JSON array is indexed as one field into the database instead their own JSON fields. Sample: { "host": { "status": { "_state": "up", "_reason": "echo-reply", "_reason_ttl": "60" }, "address": { "_addr": "xxx.xxx.xxx.xxx", "_addrtype": "ipv4" }, "hostnames": { "hostname": { "_name": "xxxxxx.com", "_type": "PTR" } }, "ports": { "extraports": { "extrareasons": { "_reason": "no-responses", "_count": "994" }, "_state": "filtered", "_count": "994" }, "port": [ { "state": { "_state": "closed", "_reason": "reset", "_reason_ttl": "60" }, "service": { "_name": "ftp-data", "_method": "table", "_conf": "3" }, "_protocol": "tcp", "_portid": "20" }, { "state": { "_state": "open", "_reason": "syn-ack", "_reason_ttl": "60" }, "service": { "cpe": "cpe:/a:vsftpd:vsftpd", "_name": "ftp", "_product": "vsftpd", "_version": "2.0.8 or later", "_hostname": "Welcome", "_method": "probed", "_conf": "10" }, "_protocol": "tcp", "_portid": "21" }, { "state": { "_state": "open", "_reason": "syn-ack", "_reason_ttl": "60" }, "service": { "cpe": "cpe:/a:openbsd:openssh:5.3", "_name": "ssh", "_product": "OpenSSH", "_version": "5.3", "_extrainfo": "protocol 2.0", "_method": "probed", "_conf": "10" }, "_protocol": "tcp", "_portid": "22" }, { "state": { "_state": "open", "_reason": "syn-ack", "_reason_ttl": "60" }, "service": { "cpe": "cpe:/a:apache:http_server:2.2.15", "_name": "http", "_product": "Apache httpd", "_version": "2.2.15", "_extrainfo": "(CentOS)", "_method": "probed", "_conf": "10" }, "_protocol": "tcp", "_portid": "80" }, { "state":…
has answer: http://stackoverflow.com/a/50543614
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88098299
linked to: http://stackoverflow.com/q/6027558
has comment: http://stackoverflow.com/comment/88098257
upvote count: 0
has title: Converting nested JSON array to simple JSON in Python
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/json
tagged with: nmap
type: Question

http://stackoverflow.com/comment/88151358
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50543148
type: Comment
has text: Still doesn't work as `//` isn't a Python comment character. Also, the global `list` should be called something else as `list` is a Python built-in and you've redefined it. Finally, the use of a global at all is a bad design -- if we call `recursion(5)` twice, the second time we get back `[1, 4, 9, 16, 25, 1, 4, 9, 16, 25]`

http://stackoverflow.com/comment/88176117
type: AnswerComment
has text: @killerT2333 - Give me some time for timings :)
comment on: http://stackoverflow.com/a/50583316
type: Comment
score: 1

http://stackoverflow.com/a/50601384
has body: There are a limited number of frames in a video, you are already extracting all of them. vidcap.read grabs, decodes and returns the next video frame, and when there are no more frames it will return false which is what you are handling already. To rotate try this (change the degree to what you need it to be): import cv2 vidcap = cv2.VideoCapture('20180530_115209.mp4') success,image = vidcap.read() h, w = image.shape[:2] M = cv2.getRotationMatrix2D((w / 2, h / 2), 90, 1.0) count = 0 success = True while success: rotated90 = cv2.warpAffine(image, M, (h, w)) cv2.imwrite("sushant_2/image/frame%d.jpg" % count, rotated90) # save frame as JPEG file success,image = vidcap.read() print('Read a new frame: ', count) count += 1
has comment: http://stackoverflow.com/comment/88212894
score: 0
answers question: http://stackoverflow.com/q/50601275
type: Answer

http://stackoverflow.com/comment/88298475
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50636769
has text: No. r2 can be negative. Please look at these posts: [Post1](https://stats.stackexchange.com/q/12900/133411) and [Post2](https://stats.stackexchange.com/q/183265/133411)
type: AnswerComment

http://stackoverflow.com/a/62649924
score: 0
type: Answer
has body: Just run the below code ... def MouseMoveTo(x, y): x = 1 + int(x * 65536./1920.)#1920 width of your desktop y = 1 + int(y * 65536./1080.)#1080 height of your desktop extra = ctypes.c_ulong(0) ii_ = Input_I() ii_.mi = MouseInput(x,y,0, (0x0001 | 0x8000), 0, ctypes.pointer(extra) ) x = Input( ctypes.c_ulong(0), ii_ ) SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
answers question: http://stackoverflow.com/q/50601200

http://stackoverflow.com/comment/88221178
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50593250
score: 0
has text: you can unpack a tuple, but this is not critical - more important is what you are trying to achive through `ax.fill_betweenx(y_p[0], outliers, x_p[0], where= outliers<x_p[0],...`? it has to be `Axes.fill_between(x, y1, y2=0,..)`, the first coordinate is xm and you are putting a y there. what is the intent for the fill area?

http://stackoverflow.com/comment/88305133
type: Comment
comment on: http://stackoverflow.com/q/50647108
has text: try and reset your migrations and start from scratch
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88173894
type: Comment
type: QuestionComment
score: 1
has text: But where's the question?
comment on: http://stackoverflow.com/q/50582432

http://stackoverflow.com/a/50641227
has comment: http://stackoverflow.com/comment/88293373
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50641053
answers question: http://stackoverflow.com/q/50641053
type: Answer
downvote count: 0
score: 1
has body: Can you try using str.contains with case=False Ex: import pandas as pd dprev = "eiffel tower" df = pd.DataFrame({"place": ["eiffel tower", "Eiffel tower", "Hello"], "data":[1,2,3]}) print(df.loc[df['place'].str.contains(dprev, case=False)]) Output: data place 0 1 eiffel tower 1 2 Eiffel tower
has comment: http://stackoverflow.com/comment/88293425
has comment: http://stackoverflow.com/comment/88294012
type: AcceptedAnswer

http://stackoverflow.com/comment/88392351
comment on: http://stackoverflow.com/q/50686936
score: 0
type: QuestionComment
type: Comment
has text: The exact opposite of a Conv2D with `padding='valid'`. Conv2D removes borders based on filter size. Conv2DTranspose adds them.

http://stackoverflow.com/q/50551952
has body: I have been trying to do some analysis on the Year column in the csv file, Since it's in object data type, I am trying to convert to float to carry forward my analyses. Code##... import pandas as pd data=pd.read_csv(r"data1.csv",sep=None,engine='python') Year Length Title Subject Actor Actress Director 1 1990 111 Tie Me Up! Tie Me Down! Comedy Banderas, Antonio Abril, 2 1991 113 High Heels Comedy Bosé, Miguel Abril, Victoria Almodóvar, data.dtypes Year object Length object Title object Subject object Actor object Actress object Then I use the below code to convert the "Year" column to float datatype.Though it's converted successful when calling the column "Year" alone, buy the result is reflected when I run the code" data.dtypes" again to check the datatypes of the column. pd.to_numeric(data["Year"],errors='coerce') 1654 1990.0 1655 1932.0 1656 1989.0 1657 1988.0 1658 1977.0 1659 1991.0 Name: Year, dtype: float64 data.dtypes Year object Length object Title object Subject object Actor object Actress object The conversion happened only for the column at that moment and not reflected and saved in the table How to convert the column's data type object to float and save it in the table as it can be used for further analyses.
has answer: http://stackoverflow.com/a/50556772
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50551971
tagged with: type-conversion
tagged with: pandas
favorite count: 0
tagged with: data-analysis
type: Question
score: 0
answer count: 2
upvote count: 1
tagged with: python
downvote count: 1
has title: converting the column's data type object to float in pandas using python

http://stackoverflow.com/comment/88118609
type: Comment
comment on: http://stackoverflow.com/q/50553846
type: QuestionComment
score: 0
has text: When it crashes, do you get an error message? If so, what is the exact error message?

http://stackoverflow.com/q/50573084
downvote count: 0
type: UnansweredQuestion
tagged with: montecarlo
type: Question
upvote count: 2
has body: I have implemented a Kmeans using Scikit Learn command and I have tried Elbow and Silhoutte Coefficient to find the optimal K. I am planning to use gap statistics to further verify my results. def optimalK(data, nrefs=3, maxClusters=15): gaps = np.zeros((len(range(1, maxClusters)),)) resultsdf = pd.DataFrame({'clusterCount':[], 'gap':[]}) for gap_index, k in enumerate(range(1, maxClusters)): # Holder for reference dispersion results refDisps = np.zeros(nrefs) for i in range(nrefs): # Create new random reference set randomReference = np.random.random_sample(size=data.shape) # Fit to it km = KMeans(k) km.fit(randomReference) refDisp = km.inertia_ refDisps[i] = refDisp km = KMeans(k) km.fit(data) origDisp = km.inertia_ # Calculate gap statistic gap = np.log(np.mean(refDisps)) - np.log(origDisp) # Assign this loop's gap statistic to gaps gaps[gap_index] = gap resultsdf = resultsdf.append({'clusterCount':k, 'gap':gap}, ignore_index=True) return (gaps.argmax() + 1, resultsdf) However my plots for gap statistic is increasing therefore optimal number of clusters is always the end point for my range of clusters. Assume I am defining cluster range to be from 1 to 10 then optimal will be 10. According to the internet websites and the original paper the workaround is to implement the standard 1 error in which GAP(K)> GAP(K+1)- S(K+1) Can anyone explain to me how to implement this in the above code? I do not know how to calculate the S(k+1) since it involves finding the standard deviation of the reference distribution. s(k+1) = sd(k+1)*square_root(1+(1/B)) B is the number of copies of Monte Carlo Samples. I look at different websites but it seems they did not implement the gap statistics with standard 1 error.
answer count: 1
tagged with: k-means
has answer: http://stackoverflow.com/a/50686490
has title: Gap Statistics with Standard 1 error
tagged with: scikit-learn
favorite count: 0
tagged with: statistics
tagged with: python
score: 2

lemmatization
type: Tag
tag name: lemmatization
tags question: http://stackoverflow.com/q/50685343

http://stackoverflow.com/q/50659623
linked to: http://stackoverflow.com/q/50659491
answer count: 2
tagged with: concatenation
tagged with: pandas
score: 3
downvote count: 0
favorite count: 0
has title: Concat DataFrames diagonally
tagged with: python
has answer: http://stackoverflow.com/a/50659624
type: AnsweredQuestion
upvote count: 3
has body: This is a self answered question. Given two dataFrames, x 0 1 0 1 2 1 3 4 y 0 1 2 0 5 6 7 1 8 9 X 2 Y Z 0 The diagonal concatenation of x and y is given by: 0 1 3 4 5 0 1.0 2.0 NaN NaN NaN 1 3.0 4.0 NaN NaN NaN 2 NaN NaN 5 6 7 3 NaN NaN 8 9 X 4 NaN NaN Y Z 0 What is the easiest and simplest way of doing this? I would like to consider two cases: concatenating two dataFrames concatenating an unspecified number of dataFrames (list of DataFrames)
accepted answer: http://stackoverflow.com/a/50659624
possible better answer: http://stackoverflow.com/a/50660508
has answer: http://stackoverflow.com/a/50660508
type: Question
tagged with: dataframe

http://stackoverflow.com/comment/88184664
comment on: http://stackoverflow.com/q/50587445
score: 0
type: Comment
type: QuestionComment
has text: @juanpa.arrivillaga the operations he is doing, he can perform that operation with less time in pandas. If data is huge.

http://stackoverflow.com/q/50683503
has comment: http://stackoverflow.com/comment/88465808
answer count: 0
upvote count: 3
has title: Data Manipulation in Python
has comment: http://stackoverflow.com/comment/88381153
has comment: http://stackoverflow.com/comment/88377080
type: Question
has body: I am dealing with a data set which has the following fields: ID Person_Name Person_Country 110 Marc CA 110 Sean CN 111 Matt IN 111 Rob AU 112 Mike US I intend grouping the data in the following way: ID Person_Name Person_Country 110 Marc; Sean CA; CN 111 Matt; Rob IN; AU 112 Mike US I tried using the built-in functions like .pivot_table() and .unstack(), but they weren't helpful since I am dealing with non-numeric data.
downvote count: 0
linked to: http://stackoverflow.com/q/38127209
has comment: http://stackoverflow.com/comment/88381467
duplicate of: http://stackoverflow.com/q/44368537
tagged with: pandas
has comment: http://stackoverflow.com/comment/88381588
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88377090
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/32117848
tagged with: python
has comment: http://stackoverflow.com/comment/88376975
score: 3

http://stackoverflow.com/comment/88187301
type: AnswerComment
has text: `s = str(x) + '.'` appends a `.` to x as var s, you then try and conver s to a float..
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50588945

http://stackoverflow.com/comment/88315909
type: Comment
has text: I don't understand your comment. If you don't understand my answer look at the output of df at the bottom. This is the modified df that I used to check the code. Sales, the output of the function has the correct sum of Sale transactions (20+53+160) and the count of user IDs is also correct - 3. There is no need to set User_ID as the index of the data frame - in fact this is a bug.
comment on: http://stackoverflow.com/a/50652508
type: AnswerComment
score: 0

http://stackoverflow.com/q/50620831
has comment: http://stackoverflow.com/comment/88252266
has body: I have a file contains string "1234" and I save it with "utf-8". Then I open it with python3: with open('test2.txt', 'r', encoding="utf-8") as f: for line in f.readlines(): line = line.strip() print("len: ", len(line)) print(line[0]) print(line[1]) I got this output: len: 5 1 If I save it with "ANSI", there will be no extra space. I have tried created it with UltraEdit and the space remains the same. How can I remove the space?
downvote count: 0
has comment: http://stackoverflow.com/comment/88280472
favorite count: 0
linked to: http://stackoverflow.com/q/6786609
has comment: http://stackoverflow.com/comment/88253876
has comment: http://stackoverflow.com/comment/88251511
has comment: http://stackoverflow.com/comment/88251750
has comment: http://stackoverflow.com/comment/88252588
tagged with: python
tagged with: python-3.x
answer count: 0
upvote count: 3
type: UnansweredQuestion
has title: Got an extra space in the head of line in python3, which can not remove with strip()
type: Question
score: 3
has comment: http://stackoverflow.com/comment/88251436
has comment: http://stackoverflow.com/comment/88252279
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/88251460

http://stackoverflow.com/q/50601200
answer count: 2
score: 0
has body: I found solution to emulate mouse movement by DirectInput. Point is to use python script to navigate character in 3D Game. That means that have to use relative mouse movement. Everything was working but when i try calculate relationship between x Units (in MouseMoveTo function) and Angle character turn in game, I found out that aritmetics did not work well. For example: When i move mouse 2 x 200 Units Left then 1 x 400 Units Right character not looking at same direction (cursor is not at same place if in desktop) 2x200 &lt; 1x400 If i try to animate movement (for example divide movement to 50 steps), it gets even worse. Am i doing something wrong or it is normal behavior? if it is normal behavior, is there any way i can calculate to correct number of units passing to MouseMove To()? import ctypes import time # C struct redefinitions PUL = ctypes.POINTER(ctypes.c_ulong) class KeyBdInput(ctypes.Structure): _fields_ = [("wVk", ctypes.c_ushort), ("wScan", ctypes.c_ushort), ("dwFlags", ctypes.c_ulong), ("time", ctypes.c_ulong), ("dwExtraInfo", PUL)] class HardwareInput(ctypes.Structure): _fields_ = [("uMsg", ctypes.c_ulong), ("wParamL", ctypes.c_short), ("wParamH", ctypes.c_ushort)] class MouseInput(ctypes.Structure): _fields_ = [("dx", ctypes.c_long), ("dy", ctypes.c_long), ("mouseData", ctypes.c_ulong), ("dwFlags", ctypes.c_ulong), ("time",ctypes.c_ulong), ("dwExtraInfo", PUL)] class Input_I(ctypes.Union): _fields_ = [("ki", KeyBdInput), ("mi", MouseInput), ("hi", HardwareInput)] class Input(ctypes.Structure): _fields_ = [("type", ctypes.c_ulong), ("ii", Input_I)] # Actuals Functions def MouseMoveTo(x, y): extra = ctypes.c_ulong(0) ii_ = Input_I() ii_.mi = MouseInput(x, y, 0, 0x0001, 0, ctypes.pointer(extra)) command = Input(ctypes.c_ulong(0), ii_) ctypes.windll.user32.SendInput(1, ctypes.pointer(command), ctypes.sizeof(command))
has title: Python DirectInput Mouse Relative Moving act not as expected
tagged with: python-3.x
has answer: http://stackoverflow.com/a/53540890
tagged with: python
tagged with: mouse
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/62649924
has answer: http://stackoverflow.com/a/62649924
tagged with: directinput
type: Question
accepted answer: http://stackoverflow.com/a/53540890

http://stackoverflow.com/q/50647917
tagged with: cython
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88310898
has answer: http://stackoverflow.com/a/50648899
tagged with: compilation
has title: Cython: ValueError: '...'.Candle has the wrong size, try recompiling. Expected 16, got 24
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88308414
has body: I have 3 cython files: File 1 - candle.pxd: cdef class Candle: cdef: int ts File 2 - candle.pyx: cdef class Candle: def __init__(self, int ts): self.ts = ts File 3 - feeder.pyx: from src.cython.candle cimport Candle cdef class Feeder: cdef instantiate_first_candle(self): cdef int a = 1 # Instantiates Candle cdef Candle candle = Candle(a) The exact error it is throwing is: from src.cython.feeder import Feeder File "src/cython/candle.pxd", line 3, in init feeder ValueError: src.cython.candle.Candle has the wrong size, try recompiling. Expected 16, got 24 I have not much of a clue of what is going on and how to solve this. I have tried quite a few different things without success. Update: I was able to import Candle on IPython, when I try to instantiate an object I get this error: AttributeError: 'candle.Candle' object has no attribute 'ts'
tagged with: python
has comment: http://stackoverflow.com/comment/88308443
score: 1

http://stackoverflow.com/comment/88274199
type: Comment
comment on: http://stackoverflow.com/a/50632027
score: 1
type: AnswerComment
has text: Version numbers are not floats; they can have more than 2 fields.

http://stackoverflow.com/comment/132758152
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50667147
type: Comment
has text: Definitely, it depends on the situation. In my case, the job is running per a request from a client and the request should be processed with the data that the client requested. This is very problomatic as if the instance you pass to celery task has relationships and the relationships have their own as well. This goes out of hand and cannot be simply encoded in JSON.

http://stackoverflow.com/a/62756845
type: Answer
answers question: http://stackoverflow.com/q/50666680
has body: Here is the PyQt5 implementation: from PyQt5 import QtWidgets, QtGui, QtCore class ChecklistDialog(QtWidgets.QDialog): def __init__(self, name, stringlist=None, checked=False, icon=None, parent=None, ): super(ChecklistDialog, self).__init__(parent) self.name = name self.icon = icon self.model = QtGui.QStandardItemModel() self.listView = QtWidgets.QListView() for string in stringlist: item = QtGui.QStandardItem(string) item.setCheckable(True) check = \ (QtCore.Qt.Checked if checked else QtCore.Qt.Unchecked) item.setCheckState(check) self.model.appendRow(item) self.listView.setModel(self.model) self.okButton = QtWidgets.QPushButton('OK') self.cancelButton = QtWidgets.QPushButton('Cancel') self.selectButton = QtWidgets.QPushButton('Select All') self.unselectButton = QtWidgets.QPushButton('Unselect All') hbox = QtWidgets.QHBoxLayout() hbox.addStretch(1) hbox.addWidget(self.okButton) hbox.addWidget(self.cancelButton) hbox.addWidget(self.selectButton) hbox.addWidget(self.unselectButton) vbox = QtWidgets.QVBoxLayout(self) vbox.addWidget(self.listView) vbox.addStretch(1) vbox.addLayout(hbox) self.setWindowTitle(self.name) if self.icon: self.setWindowIcon(self.icon) self.okButton.clicked.connect(self.onAccepted) self.cancelButton.clicked.connect(self.reject) self.selectButton.clicked.connect(self.select) self.unselectButton.clicked.connect(self.unselect) def onAccepted(self): self.choices = [self.model.item(i).text() for i in range(self.model.rowCount()) if self.model.item(i).checkState() == QtCore.Qt.Checked] self.accept() def select(self): for i in range(self.model.rowCount()): item = self.model.item(i) item.setCheckState(QtCore.Qt.Checked) def unselect(self): for i in range(self.model.rowCount()): item = self.model.item(i) item.setCheckState(QtCore.Qt.Unchecked) if __name__ == '__main__': import sys fruits = [ 'Banana', 'Apple', 'Elderberry', 'Clementine', 'Fig', 'Guava', 'Mango', 'Honeydew Melon', 'Date', 'Watermelon', 'Tangerine', 'Ugli Fruit', 'Juniperberry', 'Kiwi', '…
score: 0

http://stackoverflow.com/a/50560735
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50560673
has comment: http://stackoverflow.com/comment/88132102
type: Answer
has body: You can use phisicalservers__isnull lookup for this: def get_queryset(self): filters = {'{}__contains'.format(key): value for key, value in query_params.items()} if query_params.get('serverscount') == 0: filters.update({'phisicalservers__isnull': True}) return PhysicalServerTask.objects.filter(**filters)
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50560673
has comment: http://stackoverflow.com/comment/88132032

http://stackoverflow.com/q/50608937
tagged with: text
type: AnsweredQuestion
upvote count: 0
tagged with: mysql
accepted answer: http://stackoverflow.com/a/50609047
type: Question
has answer: http://stackoverflow.com/a/50609164
has title: how to use "in" condition with many text define in python
tagged with: database
has body: i want to get correct result from my condition, here is my condition this is my database and here is my code : my define text #define country = ('america','indonesia', 'england', 'france') city = ('new york', 'jakarta', 'london', 'paris') c1="Country" c2="City" c3="&lt;blank&gt;" and condition ("text" here is passing from select database, ofc using looping - for) if str(text) in str(country) : stat=c1 elif str(text) in str(city) : stat=c2 else : stat=c3 and i got wrong result for the condition, like this any solution to make this code work ? it work when just contain 1 text when using "in", but this case define so many text condition.
score: -1
has answer: http://stackoverflow.com/a/50609047
answer count: 3
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50609483
possible better answer: http://stackoverflow.com/a/50609164
tagged with: phpmyadmin
tagged with: python

http://stackoverflow.com/comment/140102194
type: AnswerComment
has text: More specifically: You can add `extension-pkg-whitelist=pygame` under `[MASTER]` in your `.pylintrc` file to prevent Pylint import errors for Pygame.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52927347

http://stackoverflow.com/q/50571412
has answer: http://stackoverflow.com/a/50571593
accepted answer: http://stackoverflow.com/a/50571593
has body: my intent is every time a sms is sent to my server the server should look thru the database to see if the number from the sms is already a stored object if it isn't then create and save the object to the database what am i doing wrong? views.py from django.http import request from django_twilio.decorators import twilio_view from django_twilio.request import decompose from twilio.twiml.messaging_response import MessagingResponse from .models import Contacts @twilio_view def sms_choice(request): twilio_request = decompose(request) contact_num = twilio_request.from_ contact_info = ['Thanks for your subscription', "How old are you?", "Annual Income?"] response = twilio_request.body resp = MessagingResponse() subscribers = [Contacts.objects.all()] for contact in subscribers: if contact_num != contact.customer_number: b = Contacts(customer_number=contact_num) b.save() resp.message(contact_info[0]) elif contact_num == contact.customer_number: resp.message(contact_info[1]) print(contact_num, response) return str(resp) models.py from django.db import models class Contacts (models.Model): customer_number = models.CharField(max_length=15) customer_age = models.CharField(max_length=4, null=True) customer_income = models.CharField(max_length=10, null=True) def __unicode__(self): return self.customer_number
type: Question
has title: how to use django objects in views
has comment: http://stackoverflow.com/comment/88152634
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88152732
has comment: http://stackoverflow.com/comment/88152512
score: -3
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88152617
has comment: http://stackoverflow.com/comment/88152612
type: AnsweredQuestion
upvote count: 0
downvote count: 3
has comment: http://stackoverflow.com/comment/88152624
has comment: http://stackoverflow.com/comment/88152573

http://stackoverflow.com/a/50671901
accepted answer of: http://stackoverflow.com/q/50671524
has comment: http://stackoverflow.com/comment/118297397
score: 12
type: AcceptedAnswer
downvote count: 0
has body: Using draw contours, you can draw the shape all at once. img = np.zeros([512, 512, 3],np.uint8) a = np.array([(375, 193), (364, 113), (277, 20), (271, 16), (52, 106), (133, 266), (289, 296), (372, 282)]) cv2.drawContours(img, [a], 0, (255,255,255), 2) If you don't want the image closed and want to continue how you started: image = np.zeros([512, 512, 3],np.uint8) pointsInside = [(375, 193), (364, 113), (277, 20), (271, 16), (52, 106), (133, 266), (289, 296), (372, 282)] for index, item in enumerate(pointsInside): if index == len(pointsInside) -1: break cv2.line(image, item, pointsInside[index + 1], [0, 255, 0], 2) Regarding your current code, it looks like you are trying to access the next point by indexing the current point. You need to check for the next point in the original array. A more Pythonic way of doing the second version would be: for point1, point2 in zip(a, a[1:]): cv2.line(image, point1, point2, [0, 255, 0], 2)
type: Answer
answers question: http://stackoverflow.com/q/50671524
upvote count: 12

tensor
tags question: http://stackoverflow.com/q/50588958
tags question: http://stackoverflow.com/q/50598857
tags question: http://stackoverflow.com/q/50561325
tags question: http://stackoverflow.com/q/50596380
tags question: http://stackoverflow.com/q/50547249
tags question: http://stackoverflow.com/q/50560463
tags question: http://stackoverflow.com/q/50663243
tag name: tensor
type: Tag

http://stackoverflow.com/q/50548316
has answer: http://stackoverflow.com/a/50548615
type: AnsweredQuestion
upvote count: 7
type: Question
tagged with: discord.py
has body: How to create sub commands in python bot. @bot.group(pass_context=True) async def First(ctx): if ctx.invoked_subcommand is None: await bot.say('Invalid sub command passed...') @First.command(pass_context=True) async def Second(ctx): msg = 'Finally got success {0.author.mention}'.format(ctx.message) await bot.say(msg)
accepted answer: http://stackoverflow.com/a/50548615
answer count: 2
possible better answer: http://stackoverflow.com/a/68147499
has answer: http://stackoverflow.com/a/68147499
downvote count: 0
has title: Subcommands in Python Bot
score: 7
tagged with: discord
favorite count: 0
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/123443793

http://stackoverflow.com/comment/88269160
comment on: http://stackoverflow.com/q/50629269
type: QuestionComment
score: 0
has text: A single file with the whole list for every page, every part, every match/mismatch
type: Comment

http://stackoverflow.com/q/50648481
upvote count: 2
has comment: http://stackoverflow.com/comment/88307808
has answer: http://stackoverflow.com/a/50648783
possible better answer: http://stackoverflow.com/a/50648793
has comment: http://stackoverflow.com/comment/88309188
has title: CSV to dict in Python
has comment: http://stackoverflow.com/comment/88309534
has answer: http://stackoverflow.com/a/50648793
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88307851
has comment: http://stackoverflow.com/comment/88307940
has comment: http://stackoverflow.com/comment/88307945
type: Question
has comment: http://stackoverflow.com/comment/88309348
accepted answer: http://stackoverflow.com/a/50648783
downvote count: 0
has answer: http://stackoverflow.com/a/50648809
favorite count: 0
has comment: http://stackoverflow.com/comment/88307821
has body: I have a csv-like file that wants to transfer into dict in Python. Heres the sample file: file start: ... ... [section-1] # basically a setup info with &lt;key-value&gt; pair date,2/16/2018 label,test3 size,25 ... [section-2] # contains test parameters and data NO,parameter1,parameter2 1,50,30 2,-20,32 ... ... file end I roughly have an idea of how to handle this file, to goal is to easily access each record. Something like dict maybe: {'date':2/16/2018, 'label':test3, 'size':25, 'data':[{'NO':1,'parameter1':50,'parameter2':30} {'NO':2,'parameter2':-20,'parameter2',32}] } the usecase is I want to extract these data and load it into database. The [section-1] data will go to top-level table. And [section-2] data will be loaded into child table based on [section-1] info. I'm very new to Python. Do you think this is the right direction to convert this file? Can someone tell me how to do this? Thanks
answer count: 3
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/88307679
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/88307809
has comment: http://stackoverflow.com/comment/88308001
score: 2
has comment: http://stackoverflow.com/comment/88307658

http://stackoverflow.com/comment/88808543
comment on: http://stackoverflow.com/a/50837051
score: 0
type: AnswerComment
has text: No @Jundiaius, I'm ruuning it with uwsgi uwsgi.ini The uwsgi.ini file is on github, it contains wsgi = pywb.apps.wayback
type: Comment

http://stackoverflow.com/comment/88096381
type: Comment
has text: @Mixone I have my program hosted in aws. The program takes some time for processing long audio files, when the client side goes into time out issue. How can I asynchronously run the processing in the back end and return the result? Currently the system works fine for short audio files and return the result in json format. Also, if I run in asynchronous mode, what would be the best way to return the result?
comment on: http://stackoverflow.com/q/50542149
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88125470
score: 1
has text: The built-in module only supports a very limited set of XPath. I recommend you do `for x in root.findall('dw:product/dw:custom-attributes/dw:custom-attribute'):` and then do the attribute checks with a regular Python `if`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50557311

http://stackoverflow.com/q/50569835
type: Question
has answer: http://stackoverflow.com/a/50570315
downvote count: 0
tagged with: postgresql
tagged with: django-queryset
answer count: 1
favorite count: 0
has body: I have a Django query which running well but I the execution slower than I make this same query in terminal. In curiosity I have run the django query (i have read it from Django Debug Tooltbar) in terminal and I got the same slow query. I tried to find out what could be the problem and I suspect to the ::timestamp conversion. I try to present my problem below: My django query: query=Table.filter(time_stamp__range=('2017-05-28 01:00:00', '2017-05-28 07:00:00')).values('time_stamp', 'value') Which is equalt to this raw sql statment according to Django Debug Toolbar: SELECT * FROM "table" WHERE "table"."time_stamp" BETWEEN '2018-05-28T01:00:00.004325'::timestamp AND '2018-05-28T07:00:00.004325'::timestamp Based on the Debug Toolbar result I got 1436,11 ms running time. After that I logged in into my PostgreSQl database via terminal and I used this query: select * from table where time_stamp between '2018-05-28 01:00:00' and '2018-05-28 07:00:00'; Here I got 753.086 ms execiton time. The sample of my model: class Table(models.Model): time_stamp = models.DateTimeField() value = models.FloatField(blank=True, null=True) In my mind the two query is the same except the timestamp (::timestamp) conversation in Django query. How could I avoid the the timestamp conversation in my Django query which I think coused the slow query? Thank you in advace for your help!
upvote count: 2
tagged with: django-orm
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: Execution time difference between Django query and raw sql query in terminal
score: 2

http://stackoverflow.com/q/50676651
upvote count: 2
type: Question
has body: I have dataframe in the following form: W1 W2 W3 W4 0 1 1 0 1 1 1 1 1 0 0 0 0 1 0 1 For every row, I want to randomly select single element that is 1 and make other ones zero. Initial zeros stay zeros E.g. W1 W2 W3 W4 0 1 0 0 0 1 0 0 1 0 0 0 0 0 0 1 I have very convoluted solution that uses iterrows(), but I'm looking for a pandastic one.
accepted answer: http://stackoverflow.com/a/50677009
possible better answer: http://stackoverflow.com/a/50676729
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/50694814
downvote count: 0
has title: How to randomly select elements from subset of dataframe?
favorite count: 0
has answer: http://stackoverflow.com/a/50677009
tagged with: python
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/50676729

http://stackoverflow.com/comment/88200983
comment on: http://stackoverflow.com/q/50595909
type: Comment
type: QuestionComment
has text: What is a "hex number"? On most modern architectures, primitive number types are *binary*, and only the way they are printed to the screen is changed when you work with "hex numbers". Or perhaps you want a particular sequence of bytes, represented by the hexadecimal digits you are inputting?
score: 0

http://stackoverflow.com/a/50576492
upvote count: 3
downvote count: 1
has body: String are immutable. There exist no str method that allows to mutate them. That being said, the reason you see the same id multiple times is because when an object is no longer in use, Python will reuse its position in memory. And what id does is precisely to provide a unique identifier by returning the position of the object in memory. One way to convince yourself that this is indeed the reason for your observation would be to make sure to always have a reference to each of the string you create by adding them to a list. Code mystring = "" mylist = ["This ", "That ", "This ", "That ", "This ", "That ", "This ", "That "] # A list to keep a reference to each string created_strings = [] for item in mylist: mystring = mystring + item # Prevent mystring from being garbage collected by adding it to the list created_strings.append(mystring) print("mystring: ", mystring, "ID of mystring: ", id(mystring)) Output mystring: This ID of mystring: 2522900655888 mystring: This That ID of mystring: 2522903930416 mystring: This That This ID of mystring: 2522903930544 mystring: This That This That ID of mystring: 2522902118880 mystring: This That This That This ID of mystring: 2522900546624 mystring: This That This That This That ID of mystring: 2522900546864 mystring: This That This That This That This ID of mystring: 2522902428376 mystring: This That This That This That This That ID of mystring: 2522900907952 Notice that now that memory is not reclaimed, each object has a different id.
type: Answer
answers question: http://stackoverflow.com/q/50576329
score: 2

http://stackoverflow.com/comment/88239551
comment on: http://stackoverflow.com/a/50596763
score: 0
type: AnswerComment
type: Comment
has text: OOOHHH! I didn't get your questions, none of my words have spaces in them. (I use a RNG to choose from a list of about 50 words) This way I will never need to account for spaces in a word.

http://stackoverflow.com/a/50619331
has body: You may try to find all continuous alphabets and print with format: import re if __name__=='__main__': names = ["J. J. Abrams", "J J Abrams", "J.J Abrams", "J.J. Abrams", "J J Abrams", "J J J Abrams"] for name in names: res = re.findall("([a-z]+)", name, re.I) #Find all continuous alphabets res.insert(len(res)-1, " "). #Insert &lt;space&gt; at second last position print("res : %s" % ("".join(map(str, res)))) #Join and display list which is formatted Result: res : JJ Abrams res : JJ Abrams res : JJ Abrams res : JJ Abrams res : JJ Abrams res : JJJ Abrams
score: 0
answers question: http://stackoverflow.com/q/50617691
type: Answer

http://stackoverflow.com/comment/88232038
has text: These array represent property of some known objects. Now I want to save them in a file and when I get an unknown object I want to compare it with my stored list of arrays and If matched return its id or else append it to the list with a unique id.
comment on: http://stackoverflow.com/q/50610993
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88270269
score: 0
type: AnswerComment
type: Comment
has text: Thanks! This worked fine
comment on: http://stackoverflow.com/a/50630112

http://stackoverflow.com/comment/88382696
score: 0
comment on: http://stackoverflow.com/q/50686482
has text: `bool(0) = False`, `bool(1) = True`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88197852
type: Comment
has text: For this case(input_st = "Field1:'abc',Field2:'b:c,d',Field3:'d,b,c'"), it is not working. Sorry, I should have posted this in the question itself.
comment on: http://stackoverflow.com/a/50594325
score: 0
type: AnswerComment

http://stackoverflow.com/q/50655291
has body: I have two questions and both are related to image.py in preprocessing.py 1) The image shift uses alternative dimension to decide tx and ty. why does tx decide the height changes. Should it not be working on width. h, w = x.shape[row_axis], x.shape[col_axis] tx = np.random.uniform(-hrg, hrg) * h ty = np.random.uniform(-wrg, wrg) * w x = apply_affine_transform(x, tx=tx, ty=ty, channel_axis=channel_axis, fill_mode=fill_mode, cval=cval) 2) I tried to use two different methods to extract bottle neck features on flower17 datasets. There are 17 classes and each labels have 80 images.The first approach loads every file and calculate bottleneck features. for i, label in enumerate(train_labels): cur_path = train_path + "/" + label count = 1 for image_path in glob.glob(cur_path + "/*.jpg"): img = image.load_img(image_path, target_size=image_size) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) feature = model.predict(x) flat = feature.flatten() features.append(flat) labels.append(label) print ("[INFO] processed - " + str(count)) count += 1 print ("[INFO] completed label - " + label) The second one uses ImageDataGenerator and flow_from_directory train_datagen = ImageDataGenerator(preprocessing_function = preprocess_input) generator = train_datagen.flow_from_directory( train_path, target_size=image_size, shuffle = "false", class_mode='categorical', batch_size=batchsize) nb_train_samples = len(generator.filenames) num_classes = len(generator.class_indices) predict_size_train = int(math.ceil(nb_train_samples / batchsize)) label_map = (generator.class_indices) label_map = dict((v,k) for k,v in label_map.items()) #flip for i in range(predict_size_train): x, y = next(generator) features.append(model.predict(x)) labels.append(y) features = np.concatenate(features) labels = np.argmax(np.concatenate(labels),axis=1) labels = [label_map[x] for x in labels] Both the above methods use only preprocess_input. I notice there are exactly 80 labels for each cla…
score: 1
type: Question
downvote count: 0
tagged with: keras
tagged with: python
has title: random_shift and flow_from_directory in keras preprocessing
favorite count: 0
answer count: 0
type: UnansweredQuestion
upvote count: 1

http://stackoverflow.com/comment/88104462
type: AnswerComment
comment on: http://stackoverflow.com/a/50544752
type: Comment
has text: I just ran the code from the comments section of the example script I linked to (https://nedbatchelder.com/blog/200712/extracting_jpgs_from_pdfs.html). I was able to get it working on my Windows Machine running Python 3.6. Let me know if you are still having issues.
score: 1

http://stackoverflow.com/q/50608037
linked to: http://stackoverflow.com/q/15602192
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50608125
accepted answer: http://stackoverflow.com/a/50608125
upvote count: 1
has comment: http://stackoverflow.com/comment/88227404
score: 0
has body: How can I set the turtle to a part of the screen so that it starts there. import turtle import random wn = turtle.Screen() #sets the screen wn.screensize(1000,1000) ad = turtle.Turtle() #names the turtle ad.shape("circle") #changes turtles or "ad's" shape ad.speed(98989898989898989898989898989898989898) r = 100 #CHANGES THE SIZE OF THE WRITING x_pos = 1000 - r*2 y_pos = 1000 - r ad.penup() ad.setx(-x_pos) ad.sety(y_pos) ad.pendown()
possible better answer: http://stackoverflow.com/a/50609284
tagged with: python-turtle
favorite count: 0
has comment: http://stackoverflow.com/comment/88225866
tagged with: turtle-graphics
has answer: http://stackoverflow.com/a/50609284
has title: Python turtle screen
has comment: http://stackoverflow.com/comment/88225918
tagged with: python
downvote count: 1
type: AnsweredQuestion

http://stackoverflow.com/comment/131012650
type: Comment
type: QuestionComment
has text: Don't use `from tkinter import *`, it may cause name conflicts. Instead, use `import tkinter as tk`, it is the most used way to import tkinter and everyone understands `tk` means `tkinter` instead of other names.
score: 0
comment on: http://stackoverflow.com/q/50571515

http://stackoverflow.com/q/50695812
has answer: http://stackoverflow.com/a/50695990
has title: how to sort a mathematical expression with a sum sign in python
type: Question
accepted answer: http://stackoverflow.com/a/50696406
answer count: 3
has body: How can I sort a mathematical expression like this: s = "1+3+2+1+4+3+5+16+63+3" to the desired: s = "1+1+2+3+3+3+4+5+16+63" in Python3?
has comment: http://stackoverflow.com/comment/88400954
favorite count: 0
possible better answer: http://stackoverflow.com/a/50696692
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88400884
has answer: http://stackoverflow.com/a/50696692
has comment: http://stackoverflow.com/comment/88400840
tagged with: python
has comment: http://stackoverflow.com/comment/88400800
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50696406
has comment: http://stackoverflow.com/comment/88400850
upvote count: 2
score: 0
downvote count: 2

http://stackoverflow.com/comment/88134695
score: 0
comment on: http://stackoverflow.com/q/50559152
type: Comment
has text: Yes, that's right!
type: QuestionComment

dcgan
tags question: http://stackoverflow.com/q/50683540
type: Tag
tag name: dcgan

http://stackoverflow.com/a/50666042
type: Answer
answers question: http://stackoverflow.com/q/50666014
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/50666014
type: AcceptedAnswer
downvote count: 0
has body: The permissions depend on the user executing the file. sudo -u www-data python main.py might help by executing the main.py program as the www-data user.

http://stackoverflow.com/a/50655598
has body: Solution 1 : # First identify the common SKU's temp = list(set(list(df1.SKU)).intersection(set(list(df2.SKU)))) # Filter df2 using the list of common SKU's df3 = df2[df2.SKU.isin(temp)] print(df3) SKU Sales 0 A 400 1 B 300 2 C 900 Solution 2 : One Line solution df3 = df2[df2.SKU.isin(list(df1.SKU))] EDIT 1 : Solution for the updated question (Not the optimal way of doing it, but answers your question) # reading data for df1 df1= pd.read_clipboard(sep='\\s+') df1 Company SKU Sales 0 Walmart A 100 1 Total A 200 2 Walmart B 200 3 Total B 300 4 Walmart C 400 5 Walmart D 500 # reading data for df2 df2= pd.read_clipboard(sep='\\s+') df2 Company SKU Sales 0 Walmart A 400 1 Total B 300 2 Walmart C 900 3 Walmart F 400 4 Total G 500 # Using intersect and zip to create a list of tuples matching in the data frames temp = list(set(list(zip(df1.Company,df1.SKU))).intersection(set(list(zip(df2.Company,df2.SKU))))) temp [('Walmart', 'A'), ('Walmart', 'C'), ('Total', 'B')] # Creating a helper variable in df2 to lookup in the temp list df2["temp"] = list(zip(df2.Company,df2.SKU)) df2= df2[df2["temp"].isin(temp)] del(df2["temp"]) df2 Company SKU Sales 0 Walmart A 400 1 Total B 300 2 Walmart C 900 Suggestions are welcome to improve this code
score: 3
has comment: http://stackoverflow.com/comment/88322531
has comment: http://stackoverflow.com/comment/88345226
upvote count: 3
answers question: http://stackoverflow.com/q/50655370
has comment: http://stackoverflow.com/comment/88321460
downvote count: 0
has comment: http://stackoverflow.com/comment/88321636
has comment: http://stackoverflow.com/comment/88344947
type: Answer

http://stackoverflow.com/a/50624185
has comment: http://stackoverflow.com/comment/88258748
has comment: http://stackoverflow.com/comment/129071862
upvote count: 3
has comment: http://stackoverflow.com/comment/88260335
answers question: http://stackoverflow.com/q/50624003
score: 3
downvote count: 0
has body: Use server.ehlo() in your code. Code Snippet: server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() For authentication error: http://joequery.me/guides/python-smtp-authenticationerror/ Add following code snippet and run again. try: server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(username,password) server.sendmail(fromaddr, toaddrs, msg) server.close() print 'successfully sent the mail' except: print "failed to send mail"
type: Answer

http://stackoverflow.com/a/50562972
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/50562784
has body: In R, we can substring in the column names, get the unique elements and sort nm1 &lt;- substr(names(dat), 1, nchar(names(dat))-2) sort(unique(nm1))
answers question: http://stackoverflow.com/q/50562784

http://stackoverflow.com/comment/88227026
type: Comment
has text: I tried this shutil.rmtree(), but it delete the actual folder itself, which I dont want. I tried os.remove(), where i get Permission denied error. I wanted to delete only the contents within "Source Zipped files" folder that has unzipped and extracted
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50604954

http://stackoverflow.com/a/50634771
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88313059
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50634751
has body: you can try to follow the steps from "Pycharm anaconda import tensor flow library issue" for solve your issue ("You need to do these following steps:")
accepted answer of: http://stackoverflow.com/q/50634751
type: Answer

http://stackoverflow.com/comment/88399405
has text: Are you passing right value to `fun`. It should be `a = int(raw_input("What's your birth year?(Example: 1980)"))` then `fun(a)`. It should work there is no difference between function and your 1st code
type: Comment
comment on: http://stackoverflow.com/q/50695038
type: QuestionComment
score: 1

http://stackoverflow.com/comment/88355971
has text: Will the delimeter always just be, going backwards, the characters from the $ sign to the first number?
type: Comment
comment on: http://stackoverflow.com/q/50673120
score: 1
type: QuestionComment

swagger
tags question: http://stackoverflow.com/q/50674067
tag name: swagger
tags question: http://stackoverflow.com/q/50597854
tags question: http://stackoverflow.com/q/50684488
type: Tag

http://stackoverflow.com/q/50563661
has comment: http://stackoverflow.com/comment/88137756
has title: Remove all Non-characters, except the numbers, latin letter and Cyrillic letter in python
has comment: http://stackoverflow.com/comment/88138065
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/517923
has body: I want to remove all the punctuation, special letters like "ū","ú","ǔ","ù","ǖ","ǘ","ǚ","ǜ","ü","û", ▬▬▬▬▬▬▬▬◄ and any other chars chars, except the numbers, latin letters and cyrillic . the input string is encoded as utf-8 How to realize this ?
accepted answer: http://stackoverflow.com/a/50564082
type: Question
has answer: http://stackoverflow.com/a/50564082
score: 0
upvote count: 1
downvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/88648039
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50655413
has text: I have already found a workaround for this problem, I used your solution and improvised a little bit to my use case. Thank You.
type: AnswerComment

http://stackoverflow.com/a/50582824
upvote count: 6
has comment: http://stackoverflow.com/comment/88174880
downvote count: 1
has comment: http://stackoverflow.com/comment/88174767
type: Answer
answers question: http://stackoverflow.com/q/50582782
has comment: http://stackoverflow.com/comment/88174859
has comment: http://stackoverflow.com/comment/88175590
has comment: http://stackoverflow.com/comment/88175830
score: 5
has body: You can flatten lists created by split, convert to sets for unique and last to lists: a = list(set([item for sublist in df['fruits'].str.split(', ') for item in sublist])) print (a) ['Pineapple', 'Clementine', 'Apple', 'Banana', 'Apricot', 'Orange', 'Pear'] Or: a = df['fruits'].str.split(', ', expand=True).stack().drop_duplicates().tolist() print (a) ['Apple', 'Apricot', 'Banana', 'Clementine', 'Pear', 'Orange', 'Pineapple'] Thanks @kabanus for alternative: a = list(set(sum(df['fruits'].str.split(', '),[])))

http://stackoverflow.com/a/50584472
has body: I improve your code snippet: from __future__ import division import math def f(t, y): return 5 * t**2 - y/math.e**(t + y) def rk4(t, y, h, i): p = list() p.append(y) for n in range(0, i): g = 11 k1 = round(h * f((t + n * h), y), g) k2 = round(h * f((t + n * h) + (h/2), y + k1/2), g) k3 = round(h * f((t + n * h) + (h/2), y + k2/2), g) k4 = round(h * f((t + n * h) + h, y + k3), g) p.append(p[n] + (1/6) * (k1 + 2 * k2 + 2 * k3 + k4)) print(k1, k2, k3, k4) rk4(0, 1, 0.1, 3) Out: (-0.03678794412, -0.03373778195, -0.03373873966, -0.0282677314) (-0.02828710837, -0.02041047991, -0.02041201684, -0.01011306051) (-0.01011942119, 0.00259988829, 0.0025995445, 0.01774691262)
score: 1
has comment: http://stackoverflow.com/comment/88319350
has comment: http://stackoverflow.com/comment/96147653
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50584182
has comment: http://stackoverflow.com/comment/88178184
answers question: http://stackoverflow.com/q/50584182
type: Answer
upvote count: 1

http://stackoverflow.com/comment/88116802
comment on: http://stackoverflow.com/q/50552896
type: Comment
type: QuestionComment
has text: @YakymPirozhenko, you're so right about it, `np.unique` could `return_inverse`, and that's what I need, however, the numpy array I have is too huge to fully load into memory, so I cannot run `np.unique` over the whole data, and this is why I came up with this dict-mapping idea...
score: 0

http://stackoverflow.com/comment/111172048
type: AnswerComment
comment on: http://stackoverflow.com/a/56611943
type: Comment
has text: **Please read this to avoid wasting a lot of time**. Google Photos API only let you control data you created from your App and not preexisting data. So if you want to move around preexisting pics, update their descriptions or add them to albums .. **you cant**. You can't touch preexisting data in any way. Read this -> https://stackoverflow.com/a/56897605/3443057
score: 20

http://stackoverflow.com/q/50542195
score: 0
has comment: http://stackoverflow.com/comment/88095643
type: UnansweredQuestion
has title: matplotlib syntax error while plotting the data
tagged with: python
has comment: http://stackoverflow.com/comment/88098835
answer count: 0
has comment: http://stackoverflow.com/comment/88095647
type: Question
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/88095727
has body: I am trying to plot to visualize data using matplotlib but I am getting an error. Here is my code: import numpy as np import datetime import time import matplotlib.pyplot as plt import matplotlib.ticker as mticker import matplotlib.dates as mdates data=open('final1.csv','r') date&amp;time,values = np.genfromtxt(data,delimiter=',',unpack=True,converters={0: mdates.bytespdate2num("%d/%m/%Y %H:%M")}) plt.gca().xaxis.set_major_locator(mticker.MaxNLocator(10)) plt.gca().xaxis.set_major_formatter(mdates.DateFormatter(('%d/%m/%Y %H:%M'))) plt.plot(date&amp;time,values,color='red') plt.ylabel('Values') plt.xlabel('Date') plt.gcf().autofmt_xdate() plt.show() I am getting the following error: date&amp;time,values =&gt; np.genfromtxt(data,delimiter=',',unpack=True,converters=0:mdates.bytespdate2num("%d/%m/%Y %H:%M")}) ^ SyntaxError: can't assign to operator my final.csv file looks like this: 3/1/2017 13:00,746.76 3/1/2017 13:30,760.98 3/1/2017 14:00,742.98 3/1/2017 14:30,720.48 3/1/2017 15:00,705.42 3/1/2017 15:30,738.12 3/1/2017 16:00,734.82 3/1/2017 16:30,712.74 3/1/2017 17:00,726.96 3/1/2017 17:30,721.14 3/1/2017 18:00,695.94 3/1/2017 18:30,676.5

http://stackoverflow.com/a/50632272
has body: You can do this using itertools.chain.from_iterable: &gt;&gt;&gt; list(itertools.chain.from_iterable([[i]*3 for i in range(32)])) [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 15, 15, 16, 16, 16, 17, 17, 17, 18, 18, 18, 19, 19, 19, 20, 20, 20, 21, 21, 21, 22, 22, 22, 23, 23, 23, 24, 24, 24, 25, 25, 25, 26, 26, 26, 27, 27, 27, 28, 28, 28, 29, 29, 29, 30, 30, 30, 31, 31, 31]
has comment: http://stackoverflow.com/comment/88275994
answers question: http://stackoverflow.com/q/50632209
has comment: http://stackoverflow.com/comment/88275034
type: Answer
has comment: http://stackoverflow.com/comment/88287634
has comment: http://stackoverflow.com/comment/88274944
has comment: http://stackoverflow.com/comment/88275160
has comment: http://stackoverflow.com/comment/88274993
has comment: http://stackoverflow.com/comment/88275180
has comment: http://stackoverflow.com/comment/88288043
score: 0
has comment: http://stackoverflow.com/comment/88274693
upvote count: 1
has comment: http://stackoverflow.com/comment/88275230
downvote count: 1

http://stackoverflow.com/a/50570988
upvote count: 1
has comment: http://stackoverflow.com/comment/88151928
has body: Change your total_items_price_in_cart function to this: def total_items_price_in_cart(self): items_prices = {k: v['price'] * v['quantity'] for (k, v) in self.items.items()} # items_prices == {'book': 30, 'toothbrush': 40} return sum(items_prices.values()) Output with input data in question: 70
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50570781
has comment: http://stackoverflow.com/comment/88152198

http://stackoverflow.com/q/50630372
tagged with: apache-beam-io
has comment: http://stackoverflow.com/comment/88976062
linked to: http://stackoverflow.com/q/46528343
score: 0
tagged with: java
tagged with: google-cloud-dataflow
has comment: http://stackoverflow.com/comment/88950676
has title: Setting Environment variables in apache beam while creating a datasource for cloudsql/mysql for python apache beam sdk
answer count: 0
tagged with: google-cloud-sql
type: UnansweredQuestion
type: Question
has body: Hi I am trying to create a datasource for apache beam in python. I know with Java you can connect to cloudsql using the JDBC library. Similarly I am trying to create a source for dataflow(apache beam) in Google Cloud Platform. I have inherited from the Bounded source class and used the jaydebeapi library (python wrapper for jdbc library) to connect to the mysql database. Please see code below. # Create new source for Cloud SQL class odbcsource(iobase.BoundedSource): def __init__(self, server=None, driver=None, database=None, username=None, password=None, sql=None, port=None, driver_path=None): self.server = server self.driver = driver self.database = database self.username = username self.password = password self.sql = sql self.port = port self.driver_path = driver_path def read(self): cursor = self._query_mssql() results = [] for row in cursor.fetchall(): results.append(row) def _query_mssql(self): """ Queries mssql and returns a cursor to the results. """ conn = jaydebeapi.connect(self.driver, "jdbc:mysql://"+self.server+":"+self.port+"/"+self.database, {'user': self.username, 'password': self.password}, self.driver_path,) cursor = conn.cursor() cursor.execute(self.sql) return cursor For the .jar file driver I have stored this in google cloud storage in a temp file location. However, python requires the Java Developer Kit to run java code and while running locally on my computer I can set the JAVA_HOME variable and point to the /bin location on my local computer. However when I am running this in dataflow I get an error "NO JVM shared library file found. Try setting the JAVA_HOME environment variable properly.This is because in dataflow I cannot install the Java Developer Kit (JDK) or create an Environmental variable. Is there a way to install the JDK on dataflow and reference environmental variables. Also any thoughts on how to run a python apache beam job to extract data from a cloud sql database this way?
tagged with: python

http://stackoverflow.com/comment/88179459
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50584986
has text: what do you expect `dps = pd.DataFrame(dps.append(results))` to do exactly ? Hint 1: `list.append()` returns `None`. Hint 2: after the first execution of this line, `dps` isn't a `list` anymore.

http://stackoverflow.com/q/50673870
linked to: http://stackoverflow.com/q/40497140
tagged with: python-2.7
score: 0
tagged with: argparse
linked to: http://stackoverflow.com/q/30704631
has body: import argparse parser = argparse.ArgumentParser() parser.add_argument("-v", "--verbosity", action="store_true", help="Pass the first input parameter with either -f or -d and the second parameter should be the path of the output file") parser.add_argument("-o", "--output",help="please give the path of the file") parser.add_argument("-of", "--format",help="provide the output format") args = parser.parse_args() when I issue help on the program like:python arg_parse.py -h,Im getting the following help python arg_parse.py -h usage: arg_parse.py [-h] [-v] [-o OUTPUT] [-of FORMAT] optional arguments: -h, --help show this help message and exit -v, --verbosity Pass the first input parameter with either -f or -d and the second parameter should be the path of the output file -o OUTPUT, --output OUTPUT please give the path of the file -of FORMAT, --format FORMAT provide the output format so if we observe optional arguments in the help message for verbosity and help look same as below: -h, --help -v, --verbosity But for OUTPUT and FORMAT we are getting multiple options which are having redundancy as below: -o OUTPUT, --output OUTPUT -of FORMAT, --format FORMAT so the only difference is I put action parameter in verbosity. Now I need the same options for OUTPUT and FORMAT without action parameter.Please help on this.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88358248
has comment: http://stackoverflow.com/comment/88358454
tagged with: python
answer count: 0
linked to: http://stackoverflow.com/q/18275023
type: Question
linked to: http://stackoverflow.com/q/23936145
has title: why optional arguments help message varying based on the action parameter?

http://stackoverflow.com/q/50660521
favorite count: 0
has answer: http://stackoverflow.com/a/50660566
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/50660587
linked to: http://stackoverflow.com/q/850795
score: 2
type: AnsweredQuestion
tagged with: list
has body: I'm playing with python lists and I want to delete from memory a list when it's not used.(I have large data lists maybe thousands or million of elements..data type-> float) I tried this code to see how deletion works in python(example) import sys array=[[12,34,54],[23,45,54,67]] print(sys.getsizeof(array)) # it gives me result 80 #then del(array[:]) print(sys.getsizeof(array)) #it gives me result 64? why is that happens?shouldn't it be zero? Is there some overhead? just curious
type: Question
has comment: http://stackoverflow.com/comment/88331228
has title: Deleting a list in python, getsizeof() non zero?
accepted answer: http://stackoverflow.com/a/50660587
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/50660566

http://stackoverflow.com/a/50625027
has comment: http://stackoverflow.com/comment/88260249
has comment: http://stackoverflow.com/comment/88260152
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50624255
has body: For this specific case you do not need to set the connection to autocommit since you are only reading from a table. Check whether user has SELECT privileges on the table

http://stackoverflow.com/q/50598220
answer count: 5
tagged with: python
accepted answer: http://stackoverflow.com/a/50600130
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88213723
has answer: http://stackoverflow.com/a/56910741
tagged with: pip
type: Question
tagged with: pipenv
has answer: http://stackoverflow.com/a/67548565
has comment: http://stackoverflow.com/comment/88208521
score: 18
has comment: http://stackoverflow.com/comment/88207139
upvote count: 18
has answer: http://stackoverflow.com/a/63169773
has title: pipenv : how to force virtualenv directory?
has answer: http://stackoverflow.com/a/50600130
downvote count: 0
possible better answer: http://stackoverflow.com/a/54387286
favorite count: 0
has answer: http://stackoverflow.com/a/54387286
has body: Actually, pipenv will install the virtualenv with a path like this : $WORKON_HOME/&lt;base_dir&gt;-&lt;hash&gt; Is it possible to have exactly the path I want, that is without the base_dir and the hash, for exemple : /home/user/myapp_venv
linked to: http://stackoverflow.com/q/55892572
has comment: http://stackoverflow.com/comment/133071040

http://stackoverflow.com/comment/88352918
has text: what do you mean by "that accounts two x values"?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50671566

http://stackoverflow.com/a/50543742
accepted answer of: http://stackoverflow.com/q/50543279
type: AcceptedAnswer
downvote count: 0
has body: If you have a csv, use the csv-module to read it (or read up on pandas, wich will auto-convert your values to suitable types): Create demo file: data = """-0.02872239612042904, -0.19755002856254578, 0.31345692434, -0.0009348573822 -1.02872239612042904, -1.19755002856254578, 1.31345692434, -1.0009348573822 -2.02872239612042904, -2.19755002856254578, 2.31345692434, -2.0009348573822 -3.02872239612042904, -3.19755002856254578, 3.31345692434, -3.0009348573822 apple, prank, 0.23, nothing """ with open("datafile.csv","w") as f: f.write(data) Read demofile back in def safeFloat(text): try: return float(text) except ValueError: # maybe even catchall here return float("nan") data = [] import csv with open("datafile.csv","r") as r: csv = csv.reader(r, delimiter=',') for l in csv: data.append(list(map(safeFloat,l))) # safeFloat to capture errors print(data) If you have non-floats in your data, you may want to use a def safeFloat(text) instead of float inside map to guard against parsing errors some text is not convertable to float. Output: [[-0.02872239612042904, -0.19755002856254578, 0.31345692434, -0.0009348573822], [-1.028722396120429, -1.1975500285625458, 1.31345692434, -1.0009348573822], [-2.028722396120429, -2.1975500285625458, 2.31345692434, -2.0009348573822], [-3.028722396120429, -3.1975500285625458, 3.31345692434, -3.0009348573822], [nan, nan, 0.23, nan]] You could also use regex, but then your pattern needs to allow the optional sign as well as a dot and numbers before/after it: r'[+-]?\d+\.\d+' # would allow for 123.1245 - but not for 123 or .1234 # would allow an optional +- before numbers You can check patterns f.e. at http://regex101.com - this pattern with demo data can be found here: https://regex101.com/r/xSiyO1/1 pandas solution (only valid data): data = """-0.02872239612042904, -0.19755002856254578, 0.31345692434, -0.0009348573822 -1.02872239612042904, -1.19755002856254578, 1.31345692434, -1.0009348573822 -2.02872239612042904, -2.19755002856254578, 2.31345692…
answers question: http://stackoverflow.com/q/50543279
has comment: http://stackoverflow.com/comment/88104858
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/88104532
has comment: http://stackoverflow.com/comment/88105016
has comment: http://stackoverflow.com/comment/88098791
has comment: http://stackoverflow.com/comment/88104956
has comment: http://stackoverflow.com/comment/88104750
score: 1

http://stackoverflow.com/comment/88149724
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50560958
has text: @KamilaAmbro what? How? It's exactly the same as the other answer?

http://stackoverflow.com/comment/88285958
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50637892
has text: While the task queue is not empty: every work thread just picks one task and sends a request to a remote server. In my test, once work thread receives a result then it just simply discards it so I don't think there is a calculation bottleneck here. The response time depends on the server since it has to do something with the data on a big set.

http://stackoverflow.com/q/50581394
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: I am trying to install MySQL-python==1.2.5 in my virtualenv on Mac using pip: pip install MySQL-python==1.2.5 Getting the below error. MySQL-python==1.2.5 Collecting MySQL-python==1.2.5 From cffi callback &lt;function _verify_callback at 0x105e815f0&gt;: Traceback (most recent call last): File "/Users/harshit.jain/Documents/workspace/venv/lib/python2.7/site-packages/OpenSSL/SSL.py", line 309, in wrapper _lib.X509_up_ref(x509) AttributeError: 'module' object has no attribute 'X509_up_ref' Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",),)': /simple/mysql-python/ From cffi callback &lt;function _verify_callback at 0x107798758&gt;: Traceback (most recent call last): File "/Users/harshit.jain/Documents/workspace/venv/lib/python2.7/site-packages/OpenSSL/SSL.py", line 309, in wrapper _lib.X509_up_ref(x509) AttributeError: 'module' object has no attribute 'X509_up_ref' Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",),)': /simple/mysql-python/ From cffi callback &lt;function _verify_callback at 0x1077c9488&gt;: Traceback (most recent call last): File "/Users/harshit.jain/Documents/workspace/venv/lib/python2.7/site-packages/OpenSSL/SSL.py", line 309, in wrapper _lib.X509_up_ref(x509) AttributeError: 'module' object has no attribute 'X509_up_ref' Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",),)': /simple/mysql-python/ From cffi callback &lt;function _verify_callback at 0x1077c95f0&gt;: Traceback (most recent call last): File "/Us…
upvote count: 1
downvote count: 1
type: Question
score: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50581808
has comment: http://stackoverflow.com/comment/88174851
has title: Error in installing MySQL-python==1.2.5

http://stackoverflow.com/q/50604214
type: AnsweredQuestion
has title: How to update the selected source indices programmatically?
score: 1
accepted answer: http://stackoverflow.com/a/52651843
tagged with: bokeh
upvote count: 1
has comment: http://stackoverflow.com/comment/88226419
tagged with: plot
tagged with: selection
possible better answer: http://stackoverflow.com/a/50605781
type: Question
has answer: http://stackoverflow.com/a/50605781
answer count: 2
has body: From the docs, the Selection object says: Selections are typically created by selecting points in a plot with a SelectTool, but can also be programmatically specified. But I do not how to set some selected points programmatically. For example if I want to update the selection by clicking on some button. I can update the element source.selected.indices, but the event is not triggered and the points are not marked as selected from bokeh.io import curdoc from bokeh.models import ColumnDataSource from bokeh.plotting import figure from bokeh.layouts import column from bokeh.models.tools import LassoSelectTool, TapTool from bokeh.models.widgets.buttons import Button source = ColumnDataSource(dict( x=[1, 2, 3, 4, 5, 6], y=[1, 2, 3, 4, 5, 6], )) p = figure( plot_height=300, tools='', ) p.circle( x='x', y='y', size=20, source=source) lasso_select = LassoSelectTool( select_every_mousemove=False, ) tap = TapTool() tools = (lasso_select, tap) p.add_tools(*tools) def update_selection_programmatically(): source.selected.update(indices=[4]) # the indices attribute is updated but the figure is not repainted, some event is not triggered. # So the points are not marked as selected bt = Button( label="Update Selection", button_type="success", width=50 ) bt.on_click(update_selection_programmatically) def update_selection(attr, old, new): print('&gt;&gt; NEW SELECTION: {}'.format(new.indices)) # new.indices = [0] # this works fine here source.on_change('selected', update_selection) curdoc().add_root(column([p, bt])) The indices attribute is updated but the figure is not repainted.
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/52651843

http://stackoverflow.com/a/50583343
has body: I saved your output to a res variable and called res.replace("\n","") and it worked. Try calling this on each of your rows.
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/88187215
answers question: http://stackoverflow.com/q/50583193

http://stackoverflow.com/comment/88218655
has text: try sudo apt-get install chromium-driver
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50603997
score: 1

http://stackoverflow.com/comment/88295371
has text: If it's a one-hot-vector, isn't `print(y_train.shape)` supposed to return (23904,25) ?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50641631
type: QuestionComment

fractions
type: Tag
tags question: http://stackoverflow.com/q/50615330
tag name: fractions

http://stackoverflow.com/q/50556645
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50556729
has title: Extract column names and sort them in Pandas
score: 1
has answer: http://stackoverflow.com/a/50556729
accepted answer: http://stackoverflow.com/a/50556673
type: Question
answer count: 2
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88125295
tagged with: pandas
has comment: http://stackoverflow.com/comment/88124277
tagged with: python
has body: I have a pandas dataframe that looks like the one below: A | B | C | D | E | 1 | 2 | 3.5 | 2.3 | 4.0 | I want to always extract any columns C through E that are greater than 2.5 and sort them in descending order of their values. For the above example: E,C is the output
has answer: http://stackoverflow.com/a/50556673
upvote count: 1

http://stackoverflow.com/a/50666011
score: 20
type: AcceptedAnswer
downvote count: 0
has body: I think the following is what you need: dfcsv = pd.read_csv("/FilePath/MultiIndex_Example.csv", index_col=[0], header=[0,1,2]) Here, index_col will take your first column which is 0 as index and header as 1st and 2nd row as header's which are 0,1,2 as its 0-indexed
has comment: http://stackoverflow.com/comment/88342007
type: Answer
accepted answer of: http://stackoverflow.com/q/50665996
answers question: http://stackoverflow.com/q/50665996
upvote count: 20
has comment: http://stackoverflow.com/comment/88341971

http://stackoverflow.com/q/50638243
has body: I'm new in coding. Let say i got a big python package contains many files and folder structures (contains many module). If i open any random file and found custom functions/modules and want to know what their jobs and purposes. For simple example i found this : value = grabData(var) i want to track this grabdata() , what the definition is or where it's located etc. But sometimes this kind of functions is located on other files (via import). What is the easiest way to track them. Tracking backward using 'import' statement seems not efficient. Any tips ?
tagged with: python
tagged with: module
favorite count: 0
has answer: http://stackoverflow.com/a/50638352
has title: Python : How to easily track the module/function definition in big package
upvote count: 1
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/50638582
has answer: http://stackoverflow.com/a/50638582
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/50638352
downvote count: 0

http://stackoverflow.com/a/50568070
has body: This is a simple application of bincount. Does this do what you want? def freqs(x): counts = np.bincount(x, minlength=6)[1:] return counts/counts.sum() frequencies = np.apply_along_axis(freqs, axis=1, arr=array) If you were wondering about the speed implications of apply_along_axis, this method using tricky indexing is marginally slower in my tests: counts = (array[:, :, None] == values[None, None, :]).sum(axis=1) frequencies2 = counts/counts.sum(axis=1)[:, None]
downvote count: 0
has comment: http://stackoverflow.com/comment/88146483
has comment: http://stackoverflow.com/comment/88147034
type: AcceptedAnswer
score: 4
accepted answer of: http://stackoverflow.com/q/50567706
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/50567706

http://stackoverflow.com/q/50625454
has comment: http://stackoverflow.com/comment/88365496
linked to: http://stackoverflow.com/q/6463863
has comment: http://stackoverflow.com/comment/88270474
score: 15
has comment: http://stackoverflow.com/comment/88272365
linked to: http://stackoverflow.com/q/27038016
has comment: http://stackoverflow.com/comment/88325215
answer count: 1
has comment: http://stackoverflow.com/comment/88268379
has comment: http://stackoverflow.com/comment/88325665
has comment: http://stackoverflow.com/comment/88325691
favorite count: 0
has comment: http://stackoverflow.com/comment/88267277
has title: Django m2m_changed signal is never called
has comment: http://stackoverflow.com/comment/88329808
has comment: http://stackoverflow.com/comment/88366253
tagged with: python
has body: I can't understand why my m2m_changed signal is not triggered. Here is the code: models.py class Badge(TimeStampable, Expirable, Deactivable, SafeDeleteModel): _safedelete_policy = HARD_DELETE owner = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.PROTECT) restaurants = models.ManyToManyField(Restaurant) identifier = models.CharField(max_length=2048) objects = SafeDeleteManager.from_queryset(BadgeQuerySet)() signals.py from django.db.models.signals import m2m_changed from django.dispatch import receiver from .models import Badge @receiver(m2m_changed, sender=Badge.restaurants.through) def my_callback(sender, **kwargs): print("M2M has been changed!") apps.py (this post advised to change this file) from django.apps import AppConfig class BadgesConfig(AppConfig): name = 'badges' def ready(self): import badges.signals When going to a shell: m2m_changed.receivers returns an empty list (it does not work, and the signal can never be received) I found similar post but did not found the answer in it. Why m2m_changed signal does not work? EDIT When opening a shell and importing badges.signals, it works. It means the problem is in apps.py: In [1]: from django.db.models.signals import m2m_changed In [2]: m2m_changed.receivers Out[2]: [] In [3]: import badges.signals In [4]: m2m_changed.receivers Out[4]: [((4551224720, 4520068792), &lt;weakref at 0x10f4da5e8; to 'function' at 0x10f462d90 (check_uniqueness)&gt;)]
upvote count: 15
has comment: http://stackoverflow.com/comment/88267507
tagged with: django-signals
has comment: http://stackoverflow.com/comment/88347016
has answer: http://stackoverflow.com/a/50678945
accepted answer: http://stackoverflow.com/a/50678945
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88329840
downvote count: 0
has comment: http://stackoverflow.com/comment/88269127
has comment: http://stackoverflow.com/comment/88325603
tagged with: django
linked to: http://stackoverflow.com/q/28135029
has comment: http://stackoverflow.com/comment/88330151
type: Question

http://stackoverflow.com/q/50683910
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
type: Question
has title: how to tkinter image to make the top layer
score: 0
answer count: 1
has body: I have a problem with the image. I have a text widget and a picture in the background. That is, the Text picture above the image. When I insert a new picture it becomes Above the text widget. And here I need some function to move the new image to the background and Text was in the foreground. from tkinter import* def listbox(): def image_get(list_): global image_1 if int(list_.curselection()[0]) == 0: #by clicking on the first item listbox image_1 = PhotoImage(file="4.png") lab = Label(root, image = image_1) lab.place(x=0, y=0) #root.attributes("-alpha", 0.5) top = Toplevel(root) list_ = Listbox(top,width=20) list_.insert(END,'image 0','image 1','image 2','image 3','image 4','image 5', 'image 6','image 7','image 8','image 9') list_.pack() list_.bind("&lt;Double-1&gt;", lambda event: image_get(list_) or top.destroy()) root = Tk() root.minsize(1000,555) root.maxsize(1000,555) image_1 = PhotoImage(file="0.png") lab = Label(root, image = image_1) lab.place(x=0, y=0) text=Text(root) text.place(x=0,y=0) king = Menu(root, postcommand=lambda: listbox()) root.config(menu=king) view = Menu(king,tearoff = 0) #view.add_command(label='Background',command=None) king.add_cascade(label="View",menu=view) root.mainloop()
has comment: http://stackoverflow.com/comment/88378836
has comment: http://stackoverflow.com/comment/88379815
has answer: http://stackoverflow.com/a/50685772
accepted answer: http://stackoverflow.com/a/50685772

http://stackoverflow.com/comment/88351739
type: AnswerComment
has text: You may want to short-circuit the second recursive call, since it's not necessary if `left_branch` is not `None`. You could do one long line with `return getNode(treenode.left_child(), key) or getNode(treenode.right_child(), key)`, or you could split it up a bit more, maybe with an `if` statement.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50670990

http://stackoverflow.com/comment/123814816
type: Comment
has text: Which one is the fastest for big type integers?
comment on: http://stackoverflow.com/a/50585643
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88197543
score: 0
comment on: http://stackoverflow.com/q/50594093
type: Comment
type: QuestionComment
has text: If you need a one element list, you will need to do: `[input()]`.

http://stackoverflow.com/q/50676331
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50676395
accepted answer: http://stackoverflow.com/a/50676395
downvote count: 0
linked to: http://stackoverflow.com/q/39579875
type: Question
tagged with: numpy
score: 3
upvote count: 3
answer count: 2
has body: I want to combine monthly data for multiple attributes into a single row consisting of data for the entire year. It is a similar problem to Combine multiple time-series rows into one row with Pandas. The solution in this question would work for me if the months of my years were complete, but for most of my data months are missing from individual years. If there is only data for December, the solution will fill the first column rather then the column 12. For the example, I am only using January to June. Here is an example of my data: ex_df = pd.DataFrame({'year': [1966, 1966, 1966, 1967, 1967, 1967], 'month': [1, 2, 6, 2, 3, 4], 'A': [10, 5, 0, np.nan, 25, 0], 'B': [-100, -80, 100, -120, 0, 60], 'C': [-1, -18, -2, -11, 10, 6]}) Here is the optimal solution: sol_df = pd.DataFrame({'year': [1966, 1967], 'A1': [10, np.nan], 'A2': [5, np.nan],'A3': [np.nan, 25],'A4': [np.nan, 0],'A5': [np.nan, np.nan],'A6': [0, np.nan],'B1': [-100, np.nan], 'B2': [-80, -120], 'B3': [np.nan, 0], 'B4': [np.nan, 60], 'B5': [np.nan, np.nan], 'B6': [100, np.nan],'C1': [-1, np.nan], 'C2': [-18, -11], 'C3': [np.nan, 10], 'C4': [np.nan, 6], 'C5': [np.nan, np.nan], 'C6': [-2, np.nan] }) A, B, C are attributes and the number corresponds to the month.
tagged with: pandas
favorite count: 0
has answer: http://stackoverflow.com/a/50678687
tagged with: python
has title: Convert multiple columns to one row (Pandas/Numpy)
possible better answer: http://stackoverflow.com/a/50678687

http://stackoverflow.com/q/50695226
has body: I want to use hierarchical cluster analysis to get the optimal number (K) of clusters automatically, then apply this K to K-means clustering in python. After studying many article, I know some methods tell us that we can plot the graph to determine K, but have any methods can output a real number automatically in python?
answer count: 2
downvote count: 0
tagged with: cluster-analysis
favorite count: 0
has comment: http://stackoverflow.com/comment/88399986
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88399825
has answer: http://stackoverflow.com/a/74040055
has comment: http://stackoverflow.com/comment/88425631
has comment: http://stackoverflow.com/comment/88400067
has answer: http://stackoverflow.com/a/64558207
upvote count: 7
type: Question
score: 7
has title: How to get the optimal number of clusters using hierarchical cluster analysis automatically in python?
tagged with: hierarchical-clustering

http://stackoverflow.com/a/50653630
accepted answer of: http://stackoverflow.com/q/50653441
has comment: http://stackoverflow.com/comment/88326798
answers question: http://stackoverflow.com/q/50653441
upvote count: 1
has comment: http://stackoverflow.com/comment/88326816
type: AcceptedAnswer
has body: I assume your complete data may look somehow like this: [{'allow_day_and_time': {'day': 'Monday', 'start': 9, 'end': 18}}, {'allow_day_and_time': {'day': 'Tuesday', 'start': 9, 'end': 18}}, {'allow_day_and_time': {'day': 'Wednesday', 'start': 9, 'end': 18}}, {'allow_day_and_time': {'day': 'Thursday', 'start': 9, 'end': 18}}, {'allow_day_and_time': {'day': 'Friday', 'start': 9, 'end': 18}}, {'allow_day_and_time': {'day': 'Monday', 'start': 13, 'end': 21}}, {'allow_day_and_time': {'day': 'Tuesday', 'start': 13, 'end': 21}}, {'allow_day_and_time': {'day': 'Wednesday', 'start': 13, 'end': 21}}, {'allow_day_and_time': {'day': 'Thursday', 'start': 13, 'end': 21}}, {'allow_day_and_time': {'day': 'Friday', 'start': 13, 'end': 21}}] Since your data is a list of dictionary items, you can access the dictionary simply by supplying the key within [] bracket, or, you can retrieve the key and value using dictionary.iteritems() Iterating with dictionary.iteritems() In [ ]: index = 0 ...: while index &lt; len(availability_constraints): ...: for key, value in availability_constraints[index].iteritems(): ...: print(key, value) ...: index += 1 ...: ('allow_day_and_time', {'start': 9, 'end': 18, 'day': 'Monday'}) ('allow_day_and_time', {'start': 9, 'end': 18, 'day': 'Tuesday'}) ('allow_day_and_time', {'start': 9, 'end': 18, 'day': 'Wednesday'}) ('allow_day_and_time', {'start': 9, 'end': 18, 'day': 'Thursday'}) ('allow_day_and_time', {'start': 9, 'end': 18, 'day': 'Friday'}) ('allow_day_and_time', {'start': 13, 'end': 21, 'day': 'Monday'}) ('allow_day_and_time', {'start': 13, 'end': 21, 'day': 'Tuesday'}) ('allow_day_and_time', {'start': 13, 'end': 21, 'day': 'Wednesday'}) ('allow_day_and_time', {'start': 13, 'end': 21, 'day': 'Thursday'}) ('allow_day_and_time', {'start': 13, 'end': 21, 'day': 'Friday'}) Let's say you are querying the start of Monday, you can use if and == operator to check if the value of that particular element of the list is referring to Monday: In [ ]: index = 0 ...:…
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/50559208
has comment: http://stackoverflow.com/comment/88128939
has comment: http://stackoverflow.com/comment/88129227
type: Question
has comment: http://stackoverflow.com/comment/88128975
tagged with: printing
has comment: http://stackoverflow.com/comment/88129289
tagged with: counter
has comment: http://stackoverflow.com/comment/88130528
has comment: http://stackoverflow.com/comment/88129693
has comment: http://stackoverflow.com/comment/88129448
has comment: http://stackoverflow.com/comment/88129100
score: 0
has comment: http://stackoverflow.com/comment/88129138
has comment: http://stackoverflow.com/comment/88129130
has comment: http://stackoverflow.com/comment/88129158
linked to: http://stackoverflow.com/q/50444881
tagged with: python
has comment: http://stackoverflow.com/comment/88129255
has body: lines = Counter({'you': 29, 'i': 24, 'my': 17, 'more': 13, 'one': 12, 'night': 12, 'go': 11, 'yeah': 10}) my code is this: word = Counter(lines) from collections import defaultdict reversed_word = defaultdict(list) for value, count in word.most_common(top_words): reversed_word[count].append(value) for key in sorted(reversed_word, reverse= True): print("The following words appeared {} times each: {}".format(key,', '.join(sorted(reversed_word[key])))) if top_words = 5 output: The following words appeared 29 times each: you The following words appeared 24 times each: i The following words appeared 17 times each: my The following words appeared 13 times each: more The following words appeared 12 times each: night, one but with my code i get: The following words appeared 29 times each: you The following words appeared 24 times each: i The following words appeared 17 times each: my The following words appeared 13 times each: more The following words appeared 12 times each: night i get the output I need if I change top_words to 6: The following words appeared 29 times each: you The following words appeared 24 times each: i The following words appeared 17 times each: my The following words appeared 13 times each: more The following words appeared 12 times each: night, one how do I fix this?
has comment: http://stackoverflow.com/comment/88128982
duplicate of: http://stackoverflow.com/q/32796452
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88129080
has comment: http://stackoverflow.com/comment/88129203
has comment: http://stackoverflow.com/comment/88128996
answer count: 0
has comment: http://stackoverflow.com/comment/88129148
type: UnansweredQuestion
has title: counts the word but not the number
has comment: http://stackoverflow.com/comment/88129172
has comment: http://stackoverflow.com/comment/88129020
has comment: http://stackoverflow.com/comment/88129071

peewee
tag name: peewee
type: Tag
tags question: http://stackoverflow.com/q/50616051
tags question: http://stackoverflow.com/q/50673595
tags question: http://stackoverflow.com/q/50658616
tags question: http://stackoverflow.com/q/50583613

http://stackoverflow.com/comment/88304704
has text: Yes, the result of a function applied over an array is an array, so the way you are using `fill_between` works but this is not pointing the problem in the OP.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50646735

http://stackoverflow.com/comment/88151631
type: AnswerComment
comment on: http://stackoverflow.com/a/50570165
type: Comment
score: 1
has text: @PierreCarceller `waitFor()` blocks until the process is complete. The output from the process is already going to be piped out during that time. I'm guessing that you basically "miss all the data" by waiting for the process to finish first, so you end up waiting for data that's never coming.

http://stackoverflow.com/comment/88256365
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50622088
has text: sorry for not including python tag , also its faster than DP solution but same with (Phi^n)/√5 in time . but with this we can get exact number and with (Phi^n)/√5 its approximation

http://stackoverflow.com/comment/88185883
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50587284
type: Comment
has text: There must be something wrong here. You are not working with array vs another array. You just replacing column names according to the dictionary. If there is not dictionary key for a column name then it remains unchanged. In this case length of the array does not matter.

http://stackoverflow.com/comment/88145953
type: QuestionComment
score: 1
has text: Please add more details. You want to do linear classification? Show what your code does for now, and indicate exactly what you need an answer for
comment on: http://stackoverflow.com/q/50567930
type: Comment

http://stackoverflow.com/q/50592769
favorite count: 0
possible better answer: http://stackoverflow.com/a/50593134
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88194927
accepted answer: http://stackoverflow.com/a/50592844
has answer: http://stackoverflow.com/a/50593134
type: Question
has answer: http://stackoverflow.com/a/50592844
answer count: 3
has body: need small help. I have a large file which contains mainly lines from below screen shot. There is empty line(s) between each block that start with string 'zone'. How can I form dictionary so that test_1, test_2 and test_3 are my keys and my values are all lines till empty line? Example of first key key = test_1 values = ['* fcid 0x170024 [pwwn 10:00:00:00:c9:5f:84:93] [xxxx]','* fcid 0x170016 [pwwn 50:06:0e:80:16:60:ef:43] [xxxxxxxxx]'] Any good tip? Thanks in advance Here is the text: zone name test_1 vsan xx * fcid 0x170024 [pwwn 10:00:00:00:c9:5f:84:93] [xxx] * fcid 0x170016 [pwwn 50:06:0e:80:16:60:ef:43] [xxxxxx] zone name test_2 vsan xx * fcid 0x170024 [pwwn 10:00:00:00:c9:5f:84:93] [xx] * fcid 0x170017 [pwwn 50:06:0e:80:16:60:ef:63] [xxx] zone name test_2 vsan yy pwwn 10:00:00:90:fa:81:bb:f2 * fcid 0x0b00c0 [pwwn 50:06:0e:80:07:e6:2e:26]
has answer: http://stackoverflow.com/a/50611161
upvote count: 1
has title: python how to form dict from this file

smtplib
tags question: http://stackoverflow.com/q/50651811
type: Tag
tags question: http://stackoverflow.com/q/50690820
tags question: http://stackoverflow.com/q/50624003
tag name: smtplib
tags question: http://stackoverflow.com/q/50594442

http://stackoverflow.com/comment/88206247
comment on: http://stackoverflow.com/q/50598225
score: 0
type: Comment
type: QuestionComment
has text: @JoeSebin Sorry if I was not clear. But I want to get best parameters. But my problem is randomized search might not give me that and Grid search is taking a lot of time. So, Is there anything I can do to get best parameters within the acceptable time.

http://stackoverflow.com/comment/88176067
type: QuestionComment
comment on: http://stackoverflow.com/q/50582821
score: 0
has text: Possible duplicate of [Generating a list of random numbers, summing to 1](https://stackoverflow.com/questions/18659858/generating-a-list-of-random-numbers-summing-to-1)
type: Comment

http://stackoverflow.com/comment/88402525
score: 0
type: Comment
has text: @GwJones For future reference: If you want people to get a notification, you have to @ them. Exception is the thread owner, who gets automatically a notification.
type: QuestionComment
comment on: http://stackoverflow.com/q/50694219

http://stackoverflow.com/q/50549165
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/88109257
upvote count: 1
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/50549690
has comment: http://stackoverflow.com/comment/88109226
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/88109364
has comment: http://stackoverflow.com/comment/88109324
accepted answer: http://stackoverflow.com/a/50549690
has title: Pandas x-ticks plot not working
has body: Trying to plot a graph and set x ticks but to no avail. Any help would be appreciated thanks! postcodes = ['6000', '6003', '6005', '6006', '6007', '6008', '6009', '6010', '6011', '6012'] ax4 = data9310.plot(title='Population 2011/2016') ax4.set_xticklabels(postcodes, rotation=0) Result: 6003 is in 6000 spot and so on... so each point should have one of the postcodes on the x axis
tagged with: pandas

http://stackoverflow.com/a/50643383
answers question: http://stackoverflow.com/q/50610334
score: 0
type: Answer
has body: I have found a solution for the case double *. First of all, the file fib.pxd is useless. Then we need a new fib.pyx file: # distutils: language = c++ # distutils: sources = fib.cpp import numpy as np cimport numpy as cnp cdef extern from "fib.hpp": double fib(int n) double add (double a, double b) double* mult(double a) def make_mult(double a): cdef double[:] mv = &lt;double[:4]&gt; mult(a) # the 4 stands for return np.asarray(mv) # the dimension of the array defined in fib.cpp In the case of a function which returns a nrows*ncols matrix; such as double* make_mat(int nrows, int ncols) , the second line of the function make_mult has to be rewritten as: cdef double[:,:] mv=&lt;double[:nrows,:ncols]&gt; make_mat(nrows, ncols) Regrettably, If I have a function double** make_mat(int nrows, int ncols) which always returns a matrix, then the previous code rises the error : Pointer base type does not match cython.array base type

http://stackoverflow.com/comment/106296605
comment on: http://stackoverflow.com/a/55629949
type: Comment
score: 0
type: AnswerComment
has text: Not a problem at all. The easier anyone can find the answer the better.

http://stackoverflow.com/comment/88383134
type: QuestionComment
type: Comment
has text: None of these functions look like an entry point into your program. There seems to be a large amount of code still missing.
comment on: http://stackoverflow.com/q/50686671
score: 4

python-unittest
tags question: http://stackoverflow.com/q/50642532
tags question: http://stackoverflow.com/q/50560189
tags question: http://stackoverflow.com/q/50615812
type: Tag
tags question: http://stackoverflow.com/q/50667537
tags question: http://stackoverflow.com/q/50649701
tags question: http://stackoverflow.com/q/50637346
tags question: http://stackoverflow.com/q/50621689
tag name: python-unittest

http://stackoverflow.com/a/50557315
answers question: http://stackoverflow.com/q/50556875
has body: This is not one line but if you want you can try: lst = [(1, "z"), (2, "a"), (3, "b")] first=[] second=[] for i,j in lst: first.append(i) second.append(j) print(list(zip(sorted(second),first)))
score: 0
type: Answer

http://stackoverflow.com/q/50689672
possible better answer: http://stackoverflow.com/a/50689704
downvote count: 0
has answer: http://stackoverflow.com/a/50689702
accepted answer: http://stackoverflow.com/a/50689702
tagged with: string
has comment: http://stackoverflow.com/comment/88389162
linked to: http://stackoverflow.com/q/36885876
favorite count: 0
has title: Concatenating Strings: "Multiplication" of two list of strings
tagged with: cartesian-product
tagged with: python
type: AnsweredQuestion
score: 2
tagged with: list
duplicate of: http://stackoverflow.com/q/533905
has body: For list of strings, define the multiplication operation in as concatenating here: l1 = ['aa', 'bb', 'cc'] l2 = ['11', '22'] l3 = l1 op l2 Expected output: l3 = ['aa11', 'aa22', 'bb11', 'bb22', 'cc11', 'cc22'] Simply we can use for l in l1: for ll in l2: l3.append(l+ll) But I'd be grateful to hear a pythonic solution.
upvote count: 2
has answer: http://stackoverflow.com/a/50689704
linked to: http://stackoverflow.com/q/533905
type: Question
has comment: http://stackoverflow.com/comment/88391865
has comment: http://stackoverflow.com/comment/119825305
has comment: http://stackoverflow.com/comment/109134581
answer count: 2
tagged with: concatenation
has comment: http://stackoverflow.com/comment/88390376

http://stackoverflow.com/a/50682856
type: Answer
has comment: http://stackoverflow.com/comment/88379696
answers question: http://stackoverflow.com/q/50667214
has body: I would look in the atom installed plugins in settings.. you can get here by pressing command + shift + p, then searching for settings. The only reason I suggest this is because, plugins is where I installed swift language usage accessibility through a plugin that manages that in atom. Other words for plugins on atom would be "community packages" Hope this helps.
score: 0
has comment: http://stackoverflow.com/comment/88381640

http://stackoverflow.com/comment/88117101
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50553025
has text: With the examples given, the problem appears to only appear in the last column. Is this the case for all of the data?
type: Comment

enomem
tag name: enomem
tags question: http://stackoverflow.com/q/50673522
type: Tag

http://stackoverflow.com/comment/88129111
type: Comment
comment on: http://stackoverflow.com/a/50555120
score: 0
type: AnswerComment
has text: It seems your matrices are separated by a ' \n', not '\n' - which is not an empty line, but a line with a space. I edited the answer so that it uses a line without ',' to separate the matrices. It should work now, please try it again.

http://stackoverflow.com/q/50584217
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50587074
accepted answer: http://stackoverflow.com/a/50587074
tagged with: anaconda
score: 1
type: Question
has title: Launching Spyder and JupyterNotebook causes importError when image not found
answer count: 1
tagged with: conda
upvote count: 1
tagged with: spyder
tagged with: jupyter-notebook
favorite count: 0
downvote count: 0
tagged with: python
has body: I'm new to python and the virtual environment stuff. I'm facing issues opening jupyter notebook and Spyder after updating conda. Here are some info about the versions I have: $ conda info active environment : None '''is it caused by this ? ''' user config file : /Users/-/.condarc populated config files : /Users/-/.condarc conda version : 4.5.4 conda-build version : 3.0.27 python version : 2.7.14.final.0 base environment : /Users/-/anaconda2 (writable) channel URLs : https://repo.anaconda.com/pkgs/main/osx-64 https://repo.anaconda.com/pkgs/main/noarch https://repo.anaconda.com/pkgs/free/osx-64 https://repo.anaconda.com/pkgs/free/noarch https://repo.anaconda.com/pkgs/r/osx-64 https://repo.anaconda.com/pkgs/r/noarch https://repo.anaconda.com/pkgs/pro/osx-64 https://repo.anaconda.com/pkgs/pro/noarch package cache : /Users/-/anaconda2/pkgs /Users/-/.conda/pkgs envs directories : /Users/-/anaconda2/envs /Users/-/.conda/envs platform : osx-64 user-agent : conda/4.5.4 requests/2.18.4 CPython/2.7.14 Darwin/15.5.0 OSX/10.11.5 UID:GID : 501:20 netrc file : None offline mode : False JupyerNotebook version : 5.5.0 Jupyter version : 4.4.0 Spyder version : 3.2.8 Spyder fails to launch and when trying to launch spyder from anaconda navigator I get this error: /anaconda2/lib/python2.7/site-packages/zmq/backend/cython/init.py", line 6, in from . import (constants, error, message, context, ImportError: dlopen(/Users/-/anaconda2/lib/python2.7/site-packages/zmq/backend/cython/error.so, 2): Library not loaded: @rpath/libsodium.23.dylib Referenced from: /Users/-/anaconda2/lib/libzmq.5.dylib Reason: image not found Trying to launch jupyter notebook from anaconda throws the same image not found error: /anaconda2/lib/python2.7/site-packages/zmq/backend/cython/init.py", line 6, in from . import (constants, error, message, context, ImportError: dlopen(/Users/-/anaconda2/lib/python2.7/site-packages/zmq/backend/cython/error.so, 2): Library not loaded: @rpath/libsodium.23.dylib Referenced from: /…

python-asyncio
tags question: http://stackoverflow.com/q/50698649
tags question: http://stackoverflow.com/q/50564985
tags question: http://stackoverflow.com/q/50592540
tags question: http://stackoverflow.com/q/50661971
tags question: http://stackoverflow.com/q/50546605
tags question: http://stackoverflow.com/q/50678184
tags question: http://stackoverflow.com/q/50624170
tags question: http://stackoverflow.com/q/50634083
tags question: http://stackoverflow.com/q/50548263
tags question: http://stackoverflow.com/q/50605979
tag name: python-asyncio
type: Tag
tags question: http://stackoverflow.com/q/50637159

http://stackoverflow.com/comment/88367805
score: 0
type: Comment
type: QuestionComment
has text: Did you checked this https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html and https://stackoverflow.com/questions/45564130/django-rest-framework-image-upload
comment on: http://stackoverflow.com/q/50678057

http://stackoverflow.com/q/50551827
has answer: http://stackoverflow.com/a/50551868
accepted answer: http://stackoverflow.com/a/50551868
upvote count: 3
tagged with: matrix
possible better answer: http://stackoverflow.com/a/50551891
has answer: http://stackoverflow.com/a/50551905
has body: I have the following arrays: example_array = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]] indexes = [[1,2,3], [2,3], [0,4,2], [1,4,3], [0,4,3], [1,2,3], [1,2]] I would like to replace the elements in the example_array with 1 according to the index in indexes. So, the expected result should be this: example_array = [[0,1,1,1,0],[0,0,1,1,0],[1,0,1,0,1],[0,1,0,1,1],[1,0,0,1,1],[0,1,1,1,0],[0,1,1,0,0]]. I tried different approaches, for example to use pandas, like this: matrix = pd.DataFrame(example_array) for row in matrix: for i in indexes: for j in i: x_u.iloc[x, j] = 1 but it doesn't give me the hoped results! The solution does not need to use pandas library. Thanks for the help!
has title: Replace the elements in list of lists according to the indexes stored in another list
favorite count: 0
has answer: http://stackoverflow.com/a/50551954
has answer: http://stackoverflow.com/a/50551989
tagged with: python
tagged with: indexing
type: AnsweredQuestion
score: 3
downvote count: 0
has answer: http://stackoverflow.com/a/50551891
has answer: http://stackoverflow.com/a/50551990
type: Question
tagged with: numpy
answer count: 6

http://stackoverflow.com/comment/88326176
type: Comment
has text: `a = b()` - did you just assign something different to a class name?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50658013

http://stackoverflow.com/a/66945171
upvote count: 1
has body: class DataHolder: """ Class to hold some data Attributes: batch: Run without GUI debug (bool): Show debug messages name: Object name version: Object version """ batch: bool = False debug: bool = False name: str = 'default' version: int = 0 # INLINE COMMENT for ONE line """ DocString as inline-comment I havent seen that yet. """
downvote count: 4
answers question: http://stackoverflow.com/q/50546154
score: -3
type: Answer
has comment: http://stackoverflow.com/comment/118335468

http://stackoverflow.com/q/50689328
has comment: http://stackoverflow.com/comment/88392128
favorite count: 0
has comment: http://stackoverflow.com/comment/88392069
has comment: http://stackoverflow.com/comment/88388606
answer count: 0
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88392078
has comment: http://stackoverflow.com/comment/88392150
has comment: http://stackoverflow.com/comment/88389200
has comment: http://stackoverflow.com/comment/88388751
score: 1
has body: I am using the Django REST framework package. I have several endpoints that I've already built to return data. I am calling these endpoints within Ajax to retrieve data. However, if a user does not have JavaScript enabled and presses let's say a subscribe button or a follow button for example, the action would be handled in the views.py file for that specific POST request. Would it be better to handle the request manually by doing a simple query in the views.py or is it better to just hand it off to the endpoint for that specific request inside the views.py? I know I can use serialization in views.py, but which would be better using serialization or manually writing the queries to add the rows?
has title: Calling REST endpoints in views?
type: Question
has comment: http://stackoverflow.com/comment/88392122
has comment: http://stackoverflow.com/comment/88389247
downvote count: 0
tagged with: django-rest-framework
tagged with: rest
has comment: http://stackoverflow.com/comment/88392089

http://stackoverflow.com/a/50803105
accepted answer of: http://stackoverflow.com/q/50687077
type: AcceptedAnswer
downvote count: 0
has body: It seemed it had something to do with nb_conda. Once I reinstalled nb_conda using the command below, it worked for me. conda install nb_conda
answers question: http://stackoverflow.com/q/50687077
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/a/50637240
answers question: http://stackoverflow.com/q/50637158
score: 2
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88284493
upvote count: 2
has body: you can use min function for O(n) complexity min(my_randoms)

http://stackoverflow.com/comment/88236498
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50613279
has text: Oh I think there might been an missunderstanding here - Basically the Infotext has First name LAst name and so on which is inside my script (Just random names basically and emails) but what I need and wish to do is basically to create new json file where it saves all the data. So everytime I run the script, it creates new json data file with the latest data used in the script.
type: AnswerComment

http://stackoverflow.com/comment/88259934
score: 0
type: Comment
has text: ARIMA is for time series, you could call ARIMA for each column independently.
comment on: http://stackoverflow.com/a/50606184
type: AnswerComment

http://stackoverflow.com/q/50638902
has comment: http://stackoverflow.com/comment/88289083
tagged with: django-models
linked to: http://stackoverflow.com/q/7650448
has body: I have the following data which I want to pass to JsonResponse. coin_amount = [Portfolio.objects.filter(user = request.user, coin = key['coin']).values('amount') for key in coin_sell_options] print(list(coin_amount)) However this returns a ValuesQuerySet, which is not Json serializable: [&lt;QuerySet [{'amount': Decimal('3.0000000')}]&gt;, &lt;QuerySet [{'amount': Decimal('0.1000000')}]&gt;, &lt;QuerySet [{'amount': Decimal('9.0000000')}]&gt;] That's problematic because I need a list that is JSON serializable. So I need to get a list like this from my ValuesQuerySet somehow: ['3.0000000', '0.1000000', '9.0000000']
has title: Django: "Object of type 'QuerySet' is not JSON serializable"
answer count: 1
accepted answer: http://stackoverflow.com/a/50640851
has comment: http://stackoverflow.com/comment/88288436
has comment: http://stackoverflow.com/comment/88289150
has comment: http://stackoverflow.com/comment/88287736
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/88287767
has comment: http://stackoverflow.com/comment/88289952
type: Question
has answer: http://stackoverflow.com/a/50640851

http://stackoverflow.com/comment/88339570
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50664601
score: 0
has text: Use [**`pprint`**](https://docs.python.org/3/library/pprint.html#pprint.pprint) to pretty-print the contents of the list.

http://stackoverflow.com/comment/88356059
has text: @jedwards Thanks for providing a more efficient alternative. I wonder why is `join` more efficient than loops?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50673089
type: AnswerComment

http://stackoverflow.com/comment/88354422
has text: if you want to keep the decimals, change the regex to `r'(\d+(,\d+)?)`. This way, it can cover both integers and decimals. Afterwards, you may replace the ',' with '.'
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50672228
type: Comment

http://stackoverflow.com/q/50648096
has title: Python3 Date Validation
upvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88307185
has comment: http://stackoverflow.com/comment/88307834
has comment: http://stackoverflow.com/comment/88306884
has comment: http://stackoverflow.com/comment/88307946
downvote count: 3
has comment: http://stackoverflow.com/comment/88306912
type: Question
has answer: http://stackoverflow.com/a/50648153
score: -2
has comment: http://stackoverflow.com/comment/88307250
accepted answer: http://stackoverflow.com/a/50648153
has body: How can I validate this date time in python 3 - 2018-05-30-16-54-00 ? When I pass this date text to below method , an error is returned. def validate(date_text): try: datetime.datetime.strptime(date_text, '%d-%b-%Y-%H-%M-%S') except ValueError: raise ValueError("Incorrect data format, should be YYYY-MM-DD-HH-MI-SS")
answer count: 1
tagged with: python
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88306844
has comment: http://stackoverflow.com/comment/88307222

http://stackoverflow.com/a/50618954
type: Answer
score: 1
has body: I think need filter columns by subset and call join per rows: df['new'] = df[myList_groupby].apply('_'.join, axis=1)
upvote count: 1
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50618889
answers question: http://stackoverflow.com/q/50618889

http://stackoverflow.com/q/50671495
has title: Matplotlib polar projection scrambles data order (Excel plots correctly)
downvote count: 0
tagged with: polar-coordinates
answer count: 1
favorite count: 0
has body: I'm trying to plot a LiDAR trace using Matplotlib polar projection. It seems like the polar projection scrambles my data points in a random order. This is what I have. ax = plt.subplot(111, projection='polar') ax.set_rmax(5000) ax.plot(lidar_bins, lidar_field) plt.show() Where the data is: lidar_bins = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360] …
has answer: http://stackoverflow.com/a/50671538
accepted answer: http://stackoverflow.com/a/50671538
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: matplotlib
type: Question

http://stackoverflow.com/q/50624046
has title: Convert numpy array to pandas dataframe
tagged with: python
score: 13
has answer: http://stackoverflow.com/a/50624072
accepted answer: http://stackoverflow.com/a/50624072
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/99583542
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/50624143
upvote count: 13
has answer: http://stackoverflow.com/a/50624143
has body: I have a numpy array of size 31x36 and i want to transform into pandas dataframe in order to process it. I am trying to convert it using the following code: pd.DataFrame(data=matrix, index=np.array(range(1, 31)), columns=np.array(range(1, 36))) However, I am receiving the following error: ValueError: Shape of passed values is (36, 31), indices imply (35, 30) How can I solve the issue and transform it properly?
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/50624085
favorite count: 0

http://stackoverflow.com/q/50680029
has comment: http://stackoverflow.com/comment/88369496
tagged with: pip
has comment: http://stackoverflow.com/comment/88372170
tagged with: python
has comment: http://stackoverflow.com/comment/88369716
type: AnsweredQuestion
has body: My pip broke after I ran pip install --upgrade pip When I run this command pip -V or any other commands I get Traceback (most recent call last): File "/usr/bin/pip", line 9, in &lt;module&gt; from pip import main ImportError: cannot import name main Why is it breaking? I have python3 installed. I have a solution but I need to understand why it broke after upgrading to the latest version.
upvote count: 3
accepted answer: http://stackoverflow.com/a/50681316
has comment: http://stackoverflow.com/comment/88369789
has title: Why is my pip braking after updating
type: Question
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/43675074
favorite count: 0
has comment: http://stackoverflow.com/comment/88369680
score: 3
has answer: http://stackoverflow.com/a/50681316
tagged with: python-3.x

http://stackoverflow.com/q/50548681
has body: I'm running a python scraper on my server. It needs to scrape lots of urls, so I wanted to make it faster and decided to use multiprocessing. The problem is, that the scraping process takes a really long time and so my borwser connection times out eventually. Thus I get the [Errno 32] Broken pipe error. Is there anything I can do to keep the script running? Can I surpress the error and let the script continue? If I catch it, the script stop nevertheless, right? What are my options here? Or do I have to stop using multiprocessing for time consuming scripts, that run on a server? with Pool(5) as p: p.starmap(download_slick_slide_html, zip(sndLinkList, repeat(mode), repeat(pathToFF),repeat(pathToBinaries), repeat(dateTime), repeat(scrapedSupplier), repeat(logfile))) p.close() p.join() def download_slick_slide_html(f_snd_link_list, f_mode, f_path_to_ff, f_path_to_binaries, f_date_time,f_scraped_supplier, f_log_file): # do some downloading here...
has title: Python multiprocessing failure [Errno 32] Broken pipe
type: Question
tagged with: multiprocessing
downvote count: 0
has comment: http://stackoverflow.com/comment/88108157
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/88108189
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/92661377
tagged with: broken-pipe

http://stackoverflow.com/a/50560574
type: AcceptedAnswer
downvote count: 0
has body: Use a negative lookbehind to avoid splitting when dot comes after Mt. re.split('(?&lt;!Mt)\. ', s) Code: &gt;&gt;&gt; s = "Mt. Everest is the highest peak in the world. It's height is 8848 m." &gt;&gt;&gt; re.split('(?&lt;!Mt)\. ', s) ['Mt. Everest is the highest peak in the world', "It's height is 8848 m"]
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50560495
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50560495

quicksort
tags question: http://stackoverflow.com/q/50587433
tags question: http://stackoverflow.com/q/50611358
tag name: quicksort
tags question: http://stackoverflow.com/q/50692161
type: Tag

http://stackoverflow.com/comment/88163008
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50565136
has text: Thank you so much. It Worked :-)
score: 0

pythonnet
type: Tag
tag name: pythonnet
tags question: http://stackoverflow.com/q/50664853

http://stackoverflow.com/q/50649171
has comment: http://stackoverflow.com/comment/88309735
has answer: http://stackoverflow.com/a/50649789
tagged with: lxml
upvote count: 1
answer count: 1
has title: Scraper throws an error even if right xpath is used
favorite count: 0
tagged with: python-3.x
has body: I've written a script in python in combination with lxml libary to parse some price (80 and 100 in this case) out of a chunk of html elements. I used xpaths to do the job. When I go for using .fromstring() then both the xpaths I've used within my below scraper work flwlessly. However, when I choose to go with HTML imported from lxml.etree then the xpath containig contains() expression fails. Turns out that when I use multiple class names within the scraper, it works but when choose a single class name out of compound class names then it throws an error. How can I handle such situation without using compound class names;rather, using a single class name following .contains() pattern or something? This is my try: from lxml.etree import HTML elements =\ """ 80.00 100.00 """ root = HTML(elements) for item in root.findall(".//*[@class='ProductPrice']"): # regular = item.find('.//span[@class="Regular Price"]').text regular = item.find('.//span[contains(@class,"Regular")]').text print(regular) Btw, the commented out xpath used within above script is working fine. But can't go fo .contains() expression which throws the following error: Traceback (most recent call last): File "C:\Users\WCS\AppData\Local\Programs\Python\Python36-32\SO.py", line 15, in <module> regular = item.find('.//span[contains(@class,"Regular")]').text File "src\lxml\etree.pyx", line 1526, in lxml.etree._Element.find File "src\lxml\_elementpath.py", line 311, in lxml._elementpath.find File "src\lxml\_elementpath.py", line 300, in lxml._elementpath.iterfind File "src\lxml\_elementpath.py", line 283, in lxml._elementpath._build_path_iterator File "src\lxml\_elementpath.py", line 229, in lxml._elementpath.prepare_predicate SyntaxError: invalid predicate One last thing: I do not wish to use compound class names cause few websites produce them dynamically. Thanks.
tagged with: python
has comment: http://stackoverflow.com/comment/88310035
tagged with: xpath
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: web-scraping
accepted answer: http://stackoverflow.com/a/50649789
type: Question

http://stackoverflow.com/comment/88248920
score: 0
has text: Yes, you can try that, but again, I don't think its possible since Google's word2vec model was built with the C toolkit. You won't be able to get any similar embeddings for missing words since the model vocab never had these words to train on.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50618993

http://stackoverflow.com/comment/88176379
comment on: http://stackoverflow.com/a/50583418
has text: I really don't like reloading a module. Depending on the use case this can also turn out very buggy. Does your case involve using `set_floatx` and then load an already created model? Then it would make sense that the layers already have a specific float type which overwrites the default floatx type.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/50572526
accepted answer of: http://stackoverflow.com/q/50572348
type: Answer
answers question: http://stackoverflow.com/q/50572348
downvote count: 0
has body: urlopen() does not return an object (HTTPResponse) you can send to ZipFile(). You can read() the response and use io.BytesIO() to do what you need: In []: from io import BytesIO z = urlopen('http://databank.worldbank.org/data/download/WGI_csv.zip') myzip = ZipFile(BytesIO(z.read())).extract('WGIData.csv') pd.read_csv(myzip) Out[]: Country Name Country Code Indicator Name Indicator Code 1996 \ 0 Anguilla AIA Control of Corruption: Estimate CC.EST NaN 1 Anguilla AIA Control of Corruption: Number of Sources CC.NO.SRC NaN 2 Anguilla AIA Control of Corruption: Percentile Rank CC.PER.RNK NaN 3 Anguilla AIA Control of Corruption: Percentile Rank, Lower ... CC.PER.RNK.LOWER NaN 4 Anguilla AIA Control of Corruption: Percentile Rank, Upper ... CC.PER.RNK.UPPER NaN 5 Anguilla AIA Control of Corruption: Standard Error CC.STD.ERR NaN ...
has comment: http://stackoverflow.com/comment/118195261
score: 7
upvote count: 7
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/118188351

http://stackoverflow.com/q/50615293
accepted answer: http://stackoverflow.com/a/50615331
answer count: 1
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/88240608
has comment: http://stackoverflow.com/comment/88241306
has comment: http://stackoverflow.com/comment/88240511
tagged with: python
has title: How to get python to 'except' each line of code within a chunk, rather than as a whole?
downvote count: 1
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/88240626
has comment: http://stackoverflow.com/comment/88240586
has comment: http://stackoverflow.com/comment/88240666
type: Question
tagged with: try-catch
has answer: http://stackoverflow.com/a/50615331
upvote count: 0
has body: I've been working on some python code, and messed around with lists to create a matrix and have been working on a way of filling elements and those surrounding those elements with values. I encountered the 'index out of range errors' as if I loop through each element and reach the far side of the matrix, and try add further, it falls out of the list. Despite it being bad practice I decided to use the "try...except..pass" method so that my code looks like this: https://i.sstatic.net/fMYCF.png The issue is however, once it passes one error, it returns straight to the start of the loop and fails to add the remaining values to the surrounding elements. Is there a way to get the "try" command to apply individually to each command or does it have to be to each line individually?

nlp
tags question: http://stackoverflow.com/q/50659889
tags question: http://stackoverflow.com/q/50675795
tags question: http://stackoverflow.com/q/50598129
tags question: http://stackoverflow.com/q/50570511
tags question: http://stackoverflow.com/q/50591856
tags question: http://stackoverflow.com/q/50644702
tags question: http://stackoverflow.com/q/50659994
tags question: http://stackoverflow.com/q/50689935
tags question: http://stackoverflow.com/q/50586166
tags question: http://stackoverflow.com/q/50655203
tags question: http://stackoverflow.com/q/50545596
tags question: http://stackoverflow.com/q/50643196
tags question: http://stackoverflow.com/q/50571493
tags question: http://stackoverflow.com/q/50631147
tags question: http://stackoverflow.com/q/50575957
tags question: http://stackoverflow.com/q/50547021
tag name: nlp
type: Tag
tags question: http://stackoverflow.com/q/50697092
tags question: http://stackoverflow.com/q/50658576
tags question: http://stackoverflow.com/q/50567108
tags question: http://stackoverflow.com/q/50580262
tags question: http://stackoverflow.com/q/50555303

http://stackoverflow.com/q/50609009
has comment: http://stackoverflow.com/comment/88228144
tagged with: mysql
type: AnsweredQuestion
tagged with: sql
accepted answer: http://stackoverflow.com/a/50609616
has title: How to limit list in python to show N records for each unique row?
tagged with: pymysql
favorite count: 0
has comment: http://stackoverflow.com/comment/88227850
type: Question
has comment: http://stackoverflow.com/comment/88227751
has body: I am trying to limit mysql output of query to show only Top N records for each genre. This is my code : def selectTopNactors(n): # Create a new connection con=connection() # Create a cursor on the connection cur=con.cursor() #execute query int(n) sql ="""SELECT g.genre_name, a.actor_id,COUNT(mg.genre_id) as num_mov FROM actor as a, role as r,movie as m,genre as g, movie_has_genre as mg WHERE a.actor_id = r.actor_id AND m.movie_id = r.movie_id AND m.movie_id = mg.movie_id AND g.genre_id = mg.genre_id AND (g.genre_id, m.movie_id) IN (SELECT g.genre_id, m.movie_id FROM movie as m, genre as g, movie_has_genre as mg WHERE m.movie_id = mg.movie_id AND mg.genre_id = g.genre_id ORDER BY g.genre_id) GROUP BY g.genre_name, a.actor_id ORDER BY g.genre_name, COUNT(*) desc """ cur.execute(sql) results = cur.fetchall() listab = [] listac = [] for row in results: lista = [] lista.append(row[0]) lista.append(row[1]) lista.append(row[2]) listab = tuple(lista) listac.append(listab) head = ("genreName","actorId","numberOfMovies") listac.insert(0,head) print (n) con.commit() return listac And the list which is returning it is huge (6000+) records, So I want to show only N records for each genre. returned list is here
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88228045
score: 0
has answer: http://stackoverflow.com/a/50609616
upvote count: 1
answer count: 1
downvote count: 1

http://stackoverflow.com/q/50689598
answer count: 1
accepted answer: http://stackoverflow.com/a/50689990
tagged with: raspberry-pi3
tagged with: event-handling
favorite count: 0
score: 0
has title: Event Coding Keyboard Input
tagged with: python
tagged with: pygame
upvote count: 1
downvote count: 1
has body: I am coding with python on my raspberry pi. Python isn't my best language so bear with me. I need a simple code that responds to key strokes on my keyboard. I'd doing this so I can set the Pulse Width Modulation, but I don't need that code, I already have it. My main concern is I am struggling to understand the pygame functionality required for my task. I would like to be able to type a key, such as "up arrow" ↑ and have the program output "up pressed" for every millisecond the up arrow is pressed. The pseudo-code would look like: double x = 1 while x == 1: if input.key == K_UP: print("Up Arrow Pressed") if input.key == K_q x = 2 wait 1ms pygame.quit() Again I have no clue what to import or call due to not knowing the syntax.
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50689990
tagged with: raspberry-pi

http://stackoverflow.com/a/60098820
type: Answer
upvote count: 1
score: -7
has body: If you are using vscode then you can go to settings: python.linting.pylintEnabled = False It will fix the problem. If you aren't using vscode then you can go the command prompt and manually uninstall pylint with the command pip uninstall pylint.
answers question: http://stackoverflow.com/q/50569453
downvote count: 8

http://stackoverflow.com/comment/88150788
has text: it seems like a good idea, but I need to scroll down the table to load more items on the list and expand the search radius. i know how to search elements but no how to scroll down the table, becouse if i do the scroll down with driver it scrolls the webpage
type: Comment
comment on: http://stackoverflow.com/a/50570338
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88326841
has text: Your code will never ever be against the REST principles, it is just related to method, url and action on resource. But never to how you implement it.
comment on: http://stackoverflow.com/q/50658118
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88110525
type: Comment
comment on: http://stackoverflow.com/q/50549859
score: 3
type: QuestionComment
has text: Using `numpy.reshape`

http://stackoverflow.com/a/50644132
has body: Something that people often forget with in-place operators is that their use always involves an assignment. You can see this intuitively in Alpha.content (or any int or str really): integers are immutable, but the operation works. It's much easier to forget about this step for something like Alpha or list, where the in-place operator just returns self. Just remember that the operator can return anything at all, and the result has to be bound to the original name. What's happening here is basically this: x = beta.value x = operator.iadd(x, 2) # Totally fine beta.value = x # You can imagine how this would be a problem... A direct consequence of this is that you'll see the changes in beta.value despite the error. You're always welcome to bypass the reassignment by first assigning to a temporary variable, i.e., running the first two lines shown above explicitly. Just remember that while in your case Alpha is mutable and really modifies itself in-place, that's not a requirement for the general case: x = beta.value x += 2 works as intended. However, x = beta.value.content x += 2 does not, since int.__iadd__ inevitably returns a new reference.
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50643742
type: Answer
upvote count: 1

http://stackoverflow.com/comment/88214230
has text: Thanks for the quick answer. As metioned above, I also got dependencies as `underthesea` and `sumy` that are not packed with pyinstaller.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50600823
type: Comment

http://stackoverflow.com/comment/88300783
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50642820
has text: thanks, that was my thought too, I was able to combine plot_results and sent_to_s3 tasks together by chaining them dynamically in python, then calling it eventually as a task.

http://stackoverflow.com/comment/88274678
comment on: http://stackoverflow.com/a/50628945
has text: At the bottom of my question I updated what my page and my base template looks like now.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50555069
type: AnsweredQuestion
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/50555129
tagged with: python-2.7
answer count: 2
downvote count: 0
has body: Is there an option to disable a file download option over python API. I have looked for the different option under the API URL, But have not found any option. https://developers.google.com/drive/api/v2/reference/permissions/list But google drive web UI have an option to disable a file download.
has answer: http://stackoverflow.com/a/68681251
possible better answer: http://stackoverflow.com/a/68681251
tagged with: python
favorite count: 0
tagged with: google-drive-api
has answer: http://stackoverflow.com/a/50555129
has title: Disable download option for google drive file by python
tagged with: centos7
upvote count: 1

http://stackoverflow.com/a/50667201
upvote count: 5
has comment: http://stackoverflow.com/comment/88427544
score: 5
has body: The error message answers your question. Wagtail 2.1 requires Python 3.4 or above. You need to install Python 3.4 or above and try again. Note you might use virtualenv to install packages per project. Eg: $ virtualenv env -p python3 $ source env/bin/activate $ pip install wagtail $ env/bin/wagtail start projectname
downvote count: 0
has comment: http://stackoverflow.com/comment/88435130
answers question: http://stackoverflow.com/q/50660798
type: Answer

http://stackoverflow.com/q/50591076
has body: I have 2 dataframes Dataframe 1 annualGrammy Dataframe2 annualGrammy Song I would like to get the index of Dataframe 1 in Dataframe 2 as a new column if annualGrammy matches. Do I need to merge?
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50591216
downvote count: 2
type: Question
score: -2
has answer: http://stackoverflow.com/a/50591713
tagged with: dataframe
answer count: 2
tagged with: pandas
upvote count: 0
has title: Get Index of dataframe 1 to dataframe 2

http://stackoverflow.com/comment/88226419
comment on: http://stackoverflow.com/q/50604214
has text: Seems like a bug, I would suggest a GH issue
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50693541
has answer: http://stackoverflow.com/a/50693791
answer count: 2
favorite count: 0
tagged with: python-3.x
has title: How do we create an dictionary with month keys and value 0 in python?
type: UnansweredQuestion
score: -3
tagged with: datetime
tagged with: python
tagged with: dictionary
has body: For last three months - { 'June':0, 'May':0, 'April':0 } I don't want to hardcode the data, but rather create the dictionary for last n months.
has answer: http://stackoverflow.com/a/50693615
downvote count: 3
type: Question
upvote count: 0

http://stackoverflow.com/q/50685689
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50685940
accepted answer: http://stackoverflow.com/a/50685940
tagged with: number-formatting
favorite count: 0
has body: I have an AstroPy Table of data: &gt;&gt;&gt; data ra dec redshift ... yMeanPSFMag yMeanPSFMagErr ------------ ------------ -------- ... ----------------- -------------------- 0.34011348 26.83588138 5.75 ... 19.49519920349121 0.03307399898767471 0.66411726 25.84304425 5.82 ... 19.45319938659668 0.04351300001144409 1.4680833 -0.1154999 5.85 ... 20.118600845336914 0.18635299801826477 2.10739 -6.43456 5.93 ... 20.439899444580078 0.16982899606227875 and I'd simply like to output this in a control formatted way: &gt;&gt;&gt; df = data['ra', 'dec'] &gt;&gt;&gt; ascii.write(df, 'temp.dat', overwrite=True, formats="{df['ra']:%3.1f, df['dec']:%8.3f}") and I get a: TypeError: string indices must be integers I had a look at this package but can't see anything directly useful.
tagged with: python
has answer: http://stackoverflow.com/a/50688270
score: 2
upvote count: 3
downvote count: 1
type: AnsweredQuestion
tagged with: dataframe
tagged with: astropy
tagged with: formatting
has title: Formatting with astropy.io.ascii
possible better answer: http://stackoverflow.com/a/50688270

http://stackoverflow.com/comment/88406157
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50599390
has text: Still the same issue .
score: 0

http://stackoverflow.com/a/50694627
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/88399767
has body: This is just a solution for storing the matched values to a new file melanoma.csv. Your code can be further improved and optimized. import numpy as np import pandas as pd import glob # Create a dictionary object d={} for img in glob.glob('*.jpg'): dataFrame = pd.read_csv('allcsv.csv') name = dataFrame['name'] for i in name: #print(i) if(i+'.jpg' == img): # update dictionary d everytime a match is found with all the required values d['name'] = i d['age']= dataFrame['age'] d['sex'] = dataFrame['sex'] # convert dictionary d to dataframe df = pd.DataFrame(d, columns=d.keys()) #Save dataframe to csv df.to_csv('--file path--/melanoma.csv')
has comment: http://stackoverflow.com/comment/88399437
has comment: http://stackoverflow.com/comment/88400612
answers question: http://stackoverflow.com/q/50693966

http://stackoverflow.com/q/50562554
tagged with: deployment
has body: When pushing my Django app to Heroku, I am receiving this warning remote: -----&gt; Python app detected remote: ! The latest version of Python 3 is python-3.6.5 (you are using python-3.6.4, which is unsupported). remote: ! We recommend upgrading by specifying the latest version (python-3.6.5). remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes But I am getting an error when trying to update the python version. In my local environment, it is already python 3.6.5, so I just update my runtime.txt file switching python-3.6.4 to python-3.6.5. However, this is raising an error when pushing the app. Strange enough, the error is not always the same. One example: remote: Building source: remote: remote: -----&gt; Python app detected remote: -----&gt; Found python-3.6.4, removing remote: -----&gt; Installing python-3.6.5 remote: -----&gt; Installing pip remote: -----&gt; Installing dependencies with Pipenv 11.8.2… remote: Installing dependencies from Pipfile… remote: An error occurred while installing pysocks==1.6.5! Will try again. remote: An error occurred while installing pytz==2017.2! Will try again. remote: An error occurred while installing pyyaml==3.12! Will try again. remote: An error occurred while installing requests==2.12.4! Will try again. remote: An error occurred while installing rq-dashboard==0.3.8! Will try again. remote: An error occurred while installing selenium==3.0.2! Will try again. remote: An error occurred while installing static3==0.7.0! Will try again. remote: An error occurred while installing urllib3==1.19.1! Will try again. remote: An error occurred while installing user-agents==1.0.1! Will try again. remote: An error occurred while installing werkzeug==0.12.2! Will try again. remote: An error occurred while installing whitenoise! Will try again. remote: An error occurred while installing xmltodict==0.11.0! Will try again. remote: Installing initially–failed dependencies… remote: Success installing pysocks==1.6.5! remote: Su…
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/36665889
type: Question
tagged with: heroku
has title: Django app push rejected on Heroku when upgrading to python 3.6.5
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52218363
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/comment/88354663
type: AnswerComment
has text: I got this: `X 133054720 Y 135947904 Z 13`
comment on: http://stackoverflow.com/a/50672420
type: Comment
score: 1

http://stackoverflow.com/q/50632435
has title: Python Pandas: Aggregate data by hour and display it instead of the index
has answer: http://stackoverflow.com/a/50632510
tagged with: date
type: Question
tagged with: numpy
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/50632517
has answer: http://stackoverflow.com/a/50632517
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50632510
tagged with: python
favorite count: 0
upvote count: 3
type: AnsweredQuestion
score: 3
has body: I would like to aggregate some data by hour using pandas and display the date instead of an index. The code I have right now is the following: import pandas as pd import numpy as np dates = pd.date_range('1/1/2011', periods=20, freq='25min') data = pd.Series(np.random.randint(100, size=20), index=dates) result = data.groupby(data.index.hour).sum().reset_index(name='Sum') print(result) Which displays something along the lines of: index Sum 0 0 131 1 1 116 2 2 180 3 3 62 4 4 95 5 5 107 6 6 89 7 7 169 The problem is that instead of index I want to display the date associated with that hour. The result I'm trying to achieve is the following: index Sum 0 2011-01-01 01:00:00 131 1 2011-01-01 02:00:00 116 2 2011-01-01 03:00:00 180 3 2011-01-01 04:00:00 62 4 2011-01-01 05:00:00 95 5 2011-01-01 06:00:00 107 6 2011-01-01 07:00:00 89 7 2011-01-01 08:00:00 169 Is there any way I can do that easily using pandas?

http://stackoverflow.com/comment/88114842
score: 0
type: Comment
has text: I do not connect to the database myself. Django is doing so. I put the credentials in the settings file and django connects itself.
type: AnswerComment
comment on: http://stackoverflow.com/a/50552012

http://stackoverflow.com/comment/88111542
comment on: http://stackoverflow.com/q/50550227
has text: @cdarke I was wondering about that. I could use it to replace the None variable in `self.front = self.back = self.current = None` so that it isn't wasted.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88313491
type: QuestionComment
has text: With SWIG my answer to: https://stackoverflow.com/a/10531844/168175 pretty much applies here, even though you're talking Python not Java, because the tricky bit is working out what to write in the .i file.
comment on: http://stackoverflow.com/q/50614576
score: 0
type: Comment

http://stackoverflow.com/q/50646101
answer count: 1
accepted answer: http://stackoverflow.com/a/50646896
has comment: http://stackoverflow.com/comment/88302815
tagged with: discord
favorite count: 0
has comment: http://stackoverflow.com/comment/88302682
tagged with: python-3.x
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88302895
has title: Python Bot error message
has body: This is my code and I added error handling, but it's not working. I'm getting an error in bash when the command is executed by a non-admin. Below command if I type ?hello with admin role it works, but when a non-admin types that commands, they receive You don't have permission to use this command. token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" prefix = "?" import discord from discord.ext import commands bot = commands.Bot(command_prefix=prefix) bot.remove_command("help") @bot.event async def on_ready(): print('Logged in as') print(bot.user.name) print(bot.user.id) print('------') @bot.command(pass_context=True) async def on_command_error(self, exception, ctx): if isinstance(exception, CheckFailure): print("{0} does not have permission to run `{1}`".format(ctx.message.author, ctx.command.name)) elif isinstance(exception, CommandNotFound): # This is handled in CustomCommands pass else: print(exception) await self.on_error("on_command_error", exception, ctx) @bot.command(pass_context=True) @commands.has_any_role("Admin", "Moderator") async def hello(ctx): msg = 'Hello... {0.author.mention}'.format(ctx.message) await bot.say(msg) bot.run(token)
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88302916
downvote count: 1
has answer: http://stackoverflow.com/a/50646896
type: Question
tagged with: discord.py
has comment: http://stackoverflow.com/comment/88303770
score: 0

http://stackoverflow.com/comment/88103612
comment on: http://stackoverflow.com/q/50546451
score: 0
type: Comment
type: QuestionComment
has text: I‘ve used the list module thing from Python. They’re there

argparse
tags question: http://stackoverflow.com/q/50662953
tags question: http://stackoverflow.com/q/50682466
tags question: http://stackoverflow.com/q/50673870
tags question: http://stackoverflow.com/q/50543820
tags question: http://stackoverflow.com/q/50655038
tags question: http://stackoverflow.com/q/50591605
tags question: http://stackoverflow.com/q/50664888
tag name: argparse
tags question: http://stackoverflow.com/q/50629307
tags question: http://stackoverflow.com/q/50635854
tags question: http://stackoverflow.com/q/50621922
type: Tag
tags question: http://stackoverflow.com/q/50635941
tags question: http://stackoverflow.com/q/50642064

http://stackoverflow.com/q/50548640
score: 1
has title: Installing ploty
type: Question
has comment: http://stackoverflow.com/comment/88108852
downvote count: 0
has comment: http://stackoverflow.com/comment/88108089
upvote count: 1
favorite count: 0
has body: I've just started to learn Python and have installed the redistribution WinPython. When I open the WinPython cmd and attempt to install the module ploty (pip install ploty), I get the following error: "Could not find a version that satisfies the requirement ploty (from version : ) No matching distribution found for ploty" What does this mean?
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88111373
tagged with: python

http://stackoverflow.com/q/50622133
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50674510
has title: Django tag detail page with taggit
favorite count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88291075
linked to: http://stackoverflow.com/q/40371598
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50674510
has body: I've a very similar problem like this post. Long story short, I've got a django blog, and for tags I'm using django-taggit which is working nice on the admin page. AdminScreen My main problem is that if I like to filter to a tag by an url address I still receive a 404 error although I red the documentation and couple of stackoverflow post: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8080/tag/sample/ views.py from django.utils import timezone from .models import Post from django.shortcuts import render, get_object_or_404 from taggit.models import Tag def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) def tag_detail(request, tag): tag = get_object_or_404(Tag, tag=tag) return render(request, 'blog/tag_detail.html', {'tag': tag}) urls.py(app) from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.post_list, name='post_list'), url(r'^post/(?P&lt;pk&gt;[0-9]+)/$', views.post_detail, name='post_detail'), url(r'^tag/(?P&lt;tag&gt;[-/w]+)/$', views.tag_detail, name='tag_detail'), ] models.py from django.db import models from django.utils import timezone from taggit.managers import TaggableManager class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) tags = TaggableManager() def ttags(self): return [t.name for t in self.tags.all()] def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title class Tag(models.Model): name = models.CharField(max_length=200) def __unicode__(self): return self.name I'm …
tagged with: django-taggit

http://stackoverflow.com/q/50607956
score: 0
has comment: http://stackoverflow.com/comment/88228297
tagged with: flask-sqlalchemy
has comment: http://stackoverflow.com/comment/88226714
type: UnansweredQuestion
has title: Could not execute multiprocessing in python SQLAlchemy
tagged with: multithreading
tagged with: python
has comment: http://stackoverflow.com/comment/107646908
linked to: http://stackoverflow.com/q/41279157
answer count: 0
tagged with: sqlalchemy
tagged with: python-multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/88228443
has body: With below simple code snippet, I tried to get thread multiprocessing up and running. import multiprocessing import os from app.PD.models import PAST_DUE from app.LoanContract.models import LOAN_CONTRACT def doPDDate(n): print("Worker process id for {0}: {1}".format(n.ID, os.getpid())) LoanID = n.LoanID LC = LOAN_CONTRACT.query.filter_by(ID=LoanID) for row in LC: print row.ID return n.ID if __name__ == "__main__": # input list # mylist = [1,2,3,4,5] PD = PAST_DUE.query.all() # creating a pool object p = multiprocessing.Pool() # map list to target function result = p.map(doPDDate, PD) Yet, on a half way while doPDDate() was running, I got wired error message: Traceback (most recent call last): File "test.py", line 26, in result = p.map(doPDDate, PD) File "/usr/lib/python2.7/multiprocessing/pool.py", line 253, in map return self.map_async(func, iterable, chunksize).get() File "/usr/lib/python2.7/multiprocessing/pool.py", line 572, in get raise self._value sqlalchemy.exc.OperationalError: (OperationalError) SSL error: decryption failed or bad record mac Before that function continued executing. The whole Trackback is as below: Worker process id for PDM0000003326: 10658 Worker process id for PDM0000002726: 10659 Worker process id for PD18032300232: 10660 Worker process id for PD18012400045: 10661 Worker process id for PDM0000002445: 10665 Worker process id for PDM0000002715: 10666 Worker process id for PD17122600008: 10662 Worker process id for PDM0000002927: 10668 Worker process id for PDM0000001153: 10663 Worker process id for PDM0000003183: 10670 Worker process id for PDM0000003057: 10665 Worker process id for PDM0000001209: 10664 Worker process id for PDM0000003277: 10658 Worker process id for PDM0000003263: 10666 Worker process id for PDM0000002796: 10667 Traceback (most recent call last): File "test.py", line 26, in &lt;module&gt; result = p.map(doPDDate, PD) File "/usr/lib/python2.7/multiprocessing/pool.py", line 253, in map return self.map_async(func, iterable, …

http://stackoverflow.com/q/50543265
has answer: http://stackoverflow.com/a/50543312
type: Question
tagged with: arrays
answer count: 6
has body: I'm trying to run a program that finds the index of the number that is at least two times larger than all other number in the array. Here's my code def dominantIndex(self, nums): max_num = max(nums) max_i =nums.index(max_num) if len(nums) == 1: return nums.index(max_num) for num in nums: if max_num &gt;= 2*num: return num.index(max_num) return -1 However , it doesn't work perfectly for all inputs. Could someone please fix it and check for inputs like : [1,0] [0,3,4,8] [0,3,5,2]
has answer: http://stackoverflow.com/a/50543362
has answer: http://stackoverflow.com/a/50543601
downvote count: 0
has answer: http://stackoverflow.com/a/50543479
favorite count: 0
has answer: http://stackoverflow.com/a/50543557
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50543327
has comment: http://stackoverflow.com/comment/88103273
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88097631
tagged with: list
score: 1
has title: Find whether the largest element in the array is at least twice as much as every other number in the array?

http://stackoverflow.com/q/50655132
has comment: http://stackoverflow.com/comment/88320620
score: 0
upvote count: 1
downvote count: 1
has body: &gt;&gt;&gt; a=['k','l'] &gt;&gt;&gt; b=a &gt;&gt;&gt; b[0]='M' &gt;&gt;&gt; b ['M', 'l'] &gt;&gt;&gt; a ['M', 'l'] Can any one please explain why index value 0 in a getting changed and also how to avoid this ?
linked to: http://stackoverflow.com/q/2612802
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88321110
has comment: http://stackoverflow.com/comment/88320767
has title: List index value changed against original variable
has comment: http://stackoverflow.com/comment/88320844
answer count: 0
has comment: http://stackoverflow.com/comment/88320814
favorite count: 0
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/2612802
type: Question
has comment: http://stackoverflow.com/comment/88321131
tagged with: python

http://stackoverflow.com/comment/88191451
has text: That being said - `json.dumps(z.json())` looks suspiciously like double-encoding. If `z.json()` returns JSON, then you should not feed it through `json.dumps()` once more. If `z.json()` does not return JSON then it should get a better name.
comment on: http://stackoverflow.com/q/50590861
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/57157264
has comment: http://stackoverflow.com/comment/140135618
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50557234
upvote count: 1
type: Answer
has body: I trie to resolve this error and finally install PyMySQL instead of MySQL library. And it's working properly.

apache
tag name: apache
tags question: http://stackoverflow.com/q/50694576
tags question: http://stackoverflow.com/q/50681968
tags question: http://stackoverflow.com/q/50573742
tags question: http://stackoverflow.com/q/50665914
type: Tag
tags question: http://stackoverflow.com/q/50600788
tags question: http://stackoverflow.com/q/50634594
tags question: http://stackoverflow.com/q/50693527
tags question: http://stackoverflow.com/q/50557795
tags question: http://stackoverflow.com/q/50636155

http://stackoverflow.com/q/50583251
answer count: 1
score: 1
favorite count: 0
tagged with: tkinter
upvote count: 2
has answer: http://stackoverflow.com/a/50583790
tagged with: python
has body: I am running a simple clock program that I made and while editing it I had a problem. The clock worked on its own with a print statement and the tinter window also worked on its own but together it doesn't work. I recreated it with importing the tkinter library first then later added the time import and I stopped working. What can I do? Here is my code. (I am running python v3.6.5)` import time from tkinter import* hours = int(input("what hour is it?")) minutes = int(input("what minute is it?")) seconds = int(input("what second is it?")) window = Tk() texthours = Text(window, width=1, height=1) textminutes = Text(window, width=1, height=1) textseconds = Text(window, width=1, height=1) textseconds.pack() textminutes.pack() texthours.pack() while 1==2-1: time.sleep(1) texthours.delete(0.0, END) textminutes.delete(0.0, END) textseconds.delete(0.0, END) texthours.insert(END, hours) textminutes.insert(END, minutes) textseconds.insert(END, seconds) seconds = seconds + 1 if seconds == 60: minutes = minutes + 1 seconds = 0 if minutes == 60: hours = hours + 1 minutes = 0 if hours == 24: hours = 0 `
has comment: http://stackoverflow.com/comment/88175959
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88179414
has comment: http://stackoverflow.com/comment/88178922
has title: Tkinter window not opening when importing time
linked to: http://stackoverflow.com/q/37508720
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50583790
linked to: http://stackoverflow.com/q/41075756

http://stackoverflow.com/a/50595086
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88199562
has comment: http://stackoverflow.com/comment/88199503
has body: You need to escape the \. e.g. .replace('\\n', ' ') If you try to replace \n, it will try to replace a new line, however, by escaping the \, it will try to replace the string \n.
downvote count: 0
answers question: http://stackoverflow.com/q/50595072
has comment: http://stackoverflow.com/comment/88199514
has comment: http://stackoverflow.com/comment/88200334

http://stackoverflow.com/a/50661547
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50628321
answers question: http://stackoverflow.com/q/50628321
type: Answer
score: 0
has body: self.request.resolver_match.namespace

http://stackoverflow.com/comment/88183547
type: Comment
has text: I just realized it, the header array is missing an element. thank you
comment on: http://stackoverflow.com/a/50587105
type: AnswerComment
score: 0

http://stackoverflow.com/q/50544571
tagged with: sql
tagged with: cx-oracle
has body: I want to update a table(TEMP): value = 100 * 0.9 statement = 'update temp set tax = :1 where name = :2' cur.execute(statement, ('value', 'emp1')) con.commit() Is there any other way to update the table dynamically?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88100350
has comment: http://stackoverflow.com/comment/88100255
has answer: http://stackoverflow.com/a/50544898
has title: dynamically Updating the table through python
type: Question
has answer: http://stackoverflow.com/a/50544980
has answer: http://stackoverflow.com/a/50559072
score: 0
has comment: http://stackoverflow.com/comment/88100509
answer count: 3

http://stackoverflow.com/q/50567404
favorite count: 0
score: 8
tagged with: reference
upvote count: 8
has title: The pythonic way to access a class attribute within the class
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50567528
type: Question
has comment: http://stackoverflow.com/comment/88144834
answer count: 2
downvote count: 0
tagged with: class-attribute
has answer: http://stackoverflow.com/a/50567513
linked to: http://stackoverflow.com/q/25577578
has body: I was wondering how do you think is the way to access a class attribute from a function within the class. I haven't found a reference in PEP8 or a popular question about it. e.g. class MyClass(object): BAR = 1 def foo(self): # Way A: print(self.BAR) # Way B: print(MyClass.BAR) Accessing via ´self´ seems reasonable as the attribute is owned by the same class, close reference for obvious same-class reference. On the other hand, accessing via the class name itself is clear as it is static and makes the origin of the use clear and also could be more clear as it is paired with the class' name.
tagged with: python
has comment: http://stackoverflow.com/comment/88144773

http://stackoverflow.com/q/50556352
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88124549
has comment: http://stackoverflow.com/comment/88123769
tagged with: python
has body: I am trying to figure out how change the rotation of dates on the x-axis of my chart. See below the image. I have examples of how to do it, but they don't match well as I have twin y axis's. Can you help change the rotation of the dates? Here is my code: fig, ax1 = plt.subplots() fig = plt.figure(figsize=(8,6)) t = df['date'] s1 = df['msft'] ax1.plot(t, s1, 'b-') ax1.set_xlabel('Dates') ax1.legend(loc=0) ax1.grid() # Make the y-axis label, ticks and tick labels match the line color. ax1.set_ylabel('Price', color='b') ax1.tick_params('y', colors='b') ax2 = ax1.twinx() s2 = df['amzn'] ax2.plot(t, s2, 'r-') ax2.set_ylabel('amzn', color='r') ax2.tick_params('date', colors='r') ax2.legend(loc=0) fig.tight_layout() plt.show()
tagged with: matplotlib
type: Question
has comment: http://stackoverflow.com/comment/88129892
has comment: http://stackoverflow.com/comment/88123643
score: 0
has title: How to change the diagonal rotation of a x-axis label on chart?
answer count: 1
has answer: http://stackoverflow.com/a/50559725
tagged with: axis-labels

http://stackoverflow.com/q/50621902
score: 1
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88254658
tagged with: pandas
has comment: http://stackoverflow.com/comment/88254440
downvote count: 0
has title: Cater for Dates greater than 2261 i.e. 9999-12-31 00:00:00
favorite count: 0
has comment: http://stackoverflow.com/comment/88254342
has comment: http://stackoverflow.com/comment/88282940
tagged with: python
has comment: http://stackoverflow.com/comment/88282619
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88282720
upvote count: 1
has comment: http://stackoverflow.com/comment/88254948
type: Question
has comment: http://stackoverflow.com/comment/88254201
has comment: http://stackoverflow.com/comment/88255038
has body: I have switched my data source from a CSV to a SQL query. Previously I would successfully convert all maturity_date to 2261 if they were greater than this year via (@jezrael): df_With_NaN = pd.read_sql(strSql, pyodbc.connect(connstr)) m = df_With_NaN['maturity_date'].str[:4].astype(float) &gt; 2261 df_With_NaN['maturity_date'] = df_With_NaN['maturity_date'].mask(m, '2261' + df_With_NaN['maturity_date'].str[4:]) But now I get the error on this line: df_With_NaN['maturity_date'] = pd.to_datetime(df_With_NaN['maturity_date']) OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 9999-12-31 00:00:00 Data Type: maturity_date 460862 non-null object Is there additional conversion required to cater for SQL Server to Pandas?

http://stackoverflow.com/q/50678194
score: 0
has title: Delete pixel with value 0 255 in np array
has answer: http://stackoverflow.com/a/50682042
has comment: http://stackoverflow.com/comment/88367381
has comment: http://stackoverflow.com/comment/88366452
answer count: 1
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88366951
has comment: http://stackoverflow.com/comment/88366166
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/88366283
has body: I am using Opencv and python 3.6 I have an image with this dimensions: depth = depth[0:240, 96:320] So an image of (240,224). The image is in grayscale, and I don't want consider the 2 extreme values 0 / 255 of the pixels intensity. I already have a loop in my script. I think that I have to add a line where I take off these pixels like this: for b in depth: #cicle already existing if b &lt; 255 and b &gt; 0: #added line a = a+1 if a &lt;= 121 and a &gt;= 118: for f in range(25, 223): #print((x+b)%33) soundArr[int((f-25)/6)] = soundArr[int((f-25)/6)]+b[f] but I obtain the error: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() So how do I delete those pixels?
has comment: http://stackoverflow.com/comment/88365921

http://stackoverflow.com/comment/88313394
type: Comment
type: QuestionComment
has text: Also, why have you tagged this with both -3.x and -2.7? Do you actually need code that works in both?
score: 1
comment on: http://stackoverflow.com/q/50651216

http://stackoverflow.com/comment/88159575
has text: I understand the issue here because it can only be used in a day interval not with differing from several days right?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50575123

http://stackoverflow.com/a/50686150
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/92730918
has body: The problem here was a misunderstanding of the conv2d function which is not simply a 2-dimensional convolution. It is a batched 2-d convolution of multiple channels. So while you might expect a *2d function to accept 2-dimensional tensors, the input should actually 4 dimensions (batch_size, height, width, channels) and the filter should also be 4 dimensions (filter_height, filter_width, input_channels, output_channels). Details can be found in the TF docs
has comment: http://stackoverflow.com/comment/92750833
score: 4
accepted answer of: http://stackoverflow.com/q/50652209
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50652209
type: Answer

http://stackoverflow.com/comment/88226777
type: QuestionComment
has text: Same thing. No change.
comment on: http://stackoverflow.com/q/50608129
score: 0
type: Comment

http://stackoverflow.com/q/50573457
accepted answer: http://stackoverflow.com/a/50573508
favorite count: 0
has title: Pandas equivalent of SQL non-equi JOIN
tagged with: pandas
upvote count: 9
tagged with: python
tagged with: merge
type: AnsweredQuestion
downvote count: 0
tagged with: join
possible better answer: http://stackoverflow.com/a/50573581
tagged with: dataframe
has body: So I've got 2 data-frames I'd like to merge together. I'm merging on 3 columns, 2 is an easy join. joined_df = pd.merge(df1, df2, how='left', on=['name', 'city']) I want this to be using a third column, but it's going to be a comparison, something like this: joined_df = pd.merge(df1, df2, how='left', on=['name', 'city', 'df1.year' &gt;= 'df2.year_min']) Not sure what the right syntax is here. If it was SQL, it would be easy for me. SELECT * FROM df1 JOIN df2 on (df1.name = df2.name and df1.year = df2.year and df1.year &gt; df2.year_min) Any assistance?
score: 9
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50573581
has answer: http://stackoverflow.com/a/50573508

http://stackoverflow.com/q/50608944
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/88264246
has comment: http://stackoverflow.com/comment/88227839
favorite count: 0
accepted answer: http://stackoverflow.com/a/50627981
has comment: http://stackoverflow.com/comment/88235549
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/88264832
has answer: http://stackoverflow.com/a/50627981
has title: Pip installs outdated libraries when I create a new Docker container
has comment: http://stackoverflow.com/comment/88264268
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88264082
tagged with: python-requests
has comment: http://stackoverflow.com/comment/88229085
type: Question
has body: I need to test a Docker named bibbox/app-galakasio debugging purposes (link goes to Github repository). It is very similar to another docker available fikipollo/galaksio with the important distinction that only the second one works due to issues with dependencies. The code for installing dependencies are as far as I can tell identical #INSTALL THE DEPENDENCIES RUN apt-get update \ &amp;&amp; apt-get install --no-install-recommends -y wget libapache2-mod-wsgi python-flask python-requests unzip python-pip \ &amp;&amp; apt-get clean \ &amp;&amp; pip install bioblend \ &amp;&amp; pip install fpdf fikipollo/galaksio installs Bioblend 0.10.0 which is outdated but contains a snippet to solve a bug in python-requests while bibbox/app-galaksio installs Bioblend 0.11.0 which has removed the snippet as it is no longer needed. Both dockers however installs requests 2.4.3 which is old (and contains the bug). So downgrading bibbox/app-galaksio to 0.10.0 makes it work but what I want to do is to make sure that both dockers run up to date packages. But so far I've been unable to make pip upgrade to up-to-date versions of python requests which is what I need help with.
tagged with: docker

http://stackoverflow.com/comment/97182355
comment on: http://stackoverflow.com/q/50612559
score: 0
type: QuestionComment
has text: I just reported this issue in https://github.com/timothycrosley/hug/issues/744
type: Comment

http://stackoverflow.com/q/50656074
has comment: http://stackoverflow.com/comment/88322194
has title: Find/Test for unadorned string literals (no b" or u") in Python
accepted answer: http://stackoverflow.com/a/50656862
tagged with: python-2to3
answer count: 1
favorite count: 0
tagged with: string-literals
tagged with: python
has body: As part of an effort to write code that works consistently on both Python 2 and 3, I would like to test for any unadorned string literals (any opening " or ' not preceded by a b or u). I'm fine with writing test cases, so I just need a function that returns all unadorned string literals across my .py files. As an example, say I have Python code containing the following: example_byte_string = b'This is a string of ASCII text or bytes' example_unicode_string = u"This is a Unicode string" example_unadorned_string = 'This string was not marked either way and would be treated as bytes in Python 2, but Unicode in Python 3' example_unadorned_string2 = "This is what they call a 'string'!" example_unadorned_string3 = 'John said "Is it really?" very loudly' I want to find all of the strings that are not explicitly marked, like example_unadorned_string, so that I can mark them properly and therefore make them behave the same way when run in Python 2 and 3. It would also be good to accommodate quotes within strings, like example_unadorned_string2 and 3, as these shouldn't have u/b added to the internal quotes. Obviously long term we will drop Python 2 support and only Bytes will need explicit marking. This aligns with the approach recommended by python-future.org: http://python-future.org/automatic_conversion.html#separating-text-from-bytes I can think of ways to do this with grep that are pretty nasty. AST looks potentially helpful, too. But I feel like somebody must have already solved this problem before, so thought I'd ask.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50656862
upvote count: 2
score: 1
downvote count: 1
type: Question
tagged with: testing
has comment: http://stackoverflow.com/comment/88322814

http://stackoverflow.com/a/50621880
answers question: http://stackoverflow.com/q/50621281
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: You don't "loop over a json file" - this makes no sense actually. You create a json string representation of a Python object - usually a dict - and eventually write it to a file (or send it as HTTP response content etc), or create a Python object from a json string: &gt;&gt;&gt; import json &gt;&gt;&gt; addr = ["10.1.1.{}".format(i) for i in range(12)] &gt;&gt;&gt; print(repr(json.dumps(addr))) '["10.1.1.0", "10.1.1.1", "10.1.1.2", "10.1.1.3", "10.1.1.4", "10.1.1.5", "10.1.1.6", "10.1.1.7", "10.1.1.8", "10.1.1.9", "10.1.1.10", "10.1.1.11"]' &gt;&gt;&gt; print(repr(json.dumps({"addr": addr}))) '{"addr": ["10.1.1.0", "10.1.1.1", "10.1.1.2", "10.1.1.3", "10.1.1.4", "10.1.1.5", "10.1.1.6", "10.1.1.7", "10.1.1.8", "10.1.1.9", "10.1.1.10", "10.1.1.11"]}' If you have an existing json string (from a file or any other source) and want to update it, you just parse it (with json.loads) to a Python object, update the python object, and dump it back to json. Assuming you have the following json string (either from a file, http response or whatever, doesn't matter): &gt;&gt;&gt; source = '{"foo": "bar", "addr": ["10.1.1.0", "10.1.1.1", "10.1.1.2"]}' and you want to change "foo"'s value to "baaz", add addresses up to 10.1.1.11 and add a "frobnicate: true" key=>value pair: &gt;&gt;&gt; import json &gt;&gt;&gt; data = json.loads(source) &gt;&gt;&gt; data["foo"] = "baaz" &gt;&gt;&gt; for i in range(12): ... ip = "10.1.1.{}".format(i) ... if ip not in data["addr"]: ... data["addr"].append(ip) ... &gt;&gt;&gt; data["frobnicate"] = True &gt;&gt;&gt; updated_json = json.dumps(data) &gt;&gt;&gt; print(repr(updated_json)) '{"foo": "baaz", "addr": ["10.1.1.0", "10.1.1.1", "10.1.1.2", "10.1.1.3", "10.1.1.4", "10.1.1.5", "10.1.1.6", "10.1.1.7", "10.1.1.8", "10.1.1.9", "10.1.1.10", "10.1.1.11"], "frobnicate": true}' &gt;&gt;&gt;

statsmodels
tags question: http://stackoverflow.com/q/50666953
tags question: http://stackoverflow.com/q/50656274
tags question: http://stackoverflow.com/q/50641585
tags question: http://stackoverflow.com/q/50623216
tags question: http://stackoverflow.com/q/50603091
tags question: http://stackoverflow.com/q/50553054
type: Tag
tags question: http://stackoverflow.com/q/50681946
tag name: statsmodels
tags question: http://stackoverflow.com/q/50617044

http://stackoverflow.com/a/50621287
score: 1
accepted answer of: http://stackoverflow.com/q/50619237
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: As per my knowledge, storage engine of MySQL can't be set using df.to_sql or engine = create_engine('mysql+pymy....://x@y/z'). MySQL storage engine can be added to table structure once it is created. executing an alter table command over the engine connection, you can modify the table storage engine. Example: with engine.begin() as conn: conn.execute("ALTER TABLE table_name ENGINE = MYISAM") Documentation: Working with Engines and Connections execute(object, *multiparams, **params) Executes a SQL statement construct and returns a ResultProxy
upvote count: 1
answers question: http://stackoverflow.com/q/50619237

python-sphinx
tags question: http://stackoverflow.com/q/50546154
tag name: python-sphinx
tags question: http://stackoverflow.com/q/50641147
tags question: http://stackoverflow.com/q/50585305
tags question: http://stackoverflow.com/q/50577024
type: Tag

http://stackoverflow.com/q/50688997
answer count: 3
tagged with: pandas
linked to: http://stackoverflow.com/q/38933071
tagged with: grouping
linked to: http://stackoverflow.com/q/31649669
tagged with: python
has answer: http://stackoverflow.com/a/50689084
downvote count: 0
type: UnansweredQuestion
has body: I have a DataFrame that looks like this: data = pd.DataFrame({'id' : ['a1', 'a1', 'a1', 'a2','a2','a3','a3','a3'], 'label' : ['0','0','1','0','1','0','1','1']}) My goal is to group by id and to do some arithmetics: to calculate the number of occurrence of '0' and '1' in each group, add 1000 to each number and, finally, to divide these numbers by each other. For example, for group 'a1': '0' occurs twice, '1' occurs once, then, 2 * 1000 / 1 * 1000 = 2. The desired DataFrame should look like this: id number a1 2 a2 1 a3 0,5 These SO questions helped me a lot: Group by two columns and count the occurrences of each combination in pandas pandas groupby count string occurrence over column I've tried it out in different variations but still didn't reach the desired output. Any help would be very approciated.
type: Question
score: 1
has answer: http://stackoverflow.com/a/50689105
upvote count: 1
has title: Group by column, calculate number of occurrence of value in another column and divide these numbers
has answer: http://stackoverflow.com/a/50689403
favorite count: 0

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/50551399
tags question: http://stackoverflow.com/q/50626626
tags question: http://stackoverflow.com/q/50656576
tags question: http://stackoverflow.com/q/50557796
tags question: http://stackoverflow.com/q/50552150
tags question: http://stackoverflow.com/q/50686866
tags question: http://stackoverflow.com/q/50557840
tags question: http://stackoverflow.com/q/50568495
tags question: http://stackoverflow.com/q/50664029
tags question: http://stackoverflow.com/q/50656365
tags question: http://stackoverflow.com/q/50563462
tags question: http://stackoverflow.com/q/50680951
tags question: http://stackoverflow.com/q/50628302
tags question: http://stackoverflow.com/q/50555630
tags question: http://stackoverflow.com/q/50630464
tags question: http://stackoverflow.com/q/50568043
tags question: http://stackoverflow.com/q/50685356
tags question: http://stackoverflow.com/q/50544703
tags question: http://stackoverflow.com/q/50576516
type: Tag
tags question: http://stackoverflow.com/q/50668795
tags question: http://stackoverflow.com/q/50546689
tags question: http://stackoverflow.com/q/50629261
tags question: http://stackoverflow.com/q/50665045
tags question: http://stackoverflow.com/q/50662206
tags question: http://stackoverflow.com/q/50627310
tags question: http://stackoverflow.com/q/50573276
tags question: http://stackoverflow.com/q/50556752
tags question: http://stackoverflow.com/q/50666852
tags question: http://stackoverflow.com/q/50548962
tags question: http://stackoverflow.com/q/50622856
tags question: http://stackoverflow.com/q/50566031
tags question: http://stackoverflow.com/q/50577444
tags question: http://stackoverflow.com/q/50692333
tags question: http://stackoverflow.com/q/50589205
tags question: http://stackoverflow.com/q/50575865
tags question: http://stackoverflow.com/q/50641312
tags question: http://stackoverflow.com/q/50661441
tags question: http://stackoverflow.com/q/50660786
tags question: http://stackoverflow.com/q/50647914
tags question: http://stackoverflow.com/q/50607130
tags question: http://stackoverflow.com/q/50675518
tags question: http://stackoverflow.com/q/50606468
tags question: http://stackoverflow.com/q/50636661
tags question: http://stackoverflow.com/q/50644215
tags question: http://stackoverflow.com/q/50568534
tags question: http://stackoverflow.com/q/50670769
tags question: http://stackoverflow.com/q/50628068
tags question: http://stackoverflow.com/q/50651652
tags question: http://stackoverflow.com/q/50693527
tags question: http://stackoverflow.com/q/50657309
tags question: http://stackoverflow.com/q/50568330
tags question: http://stackoverflow.com/q/50666427
tags question: http://stackoverflow.com/q/50667997
tag name: html
tags question: http://stackoverflow.com/q/50557914
tags question: http://stackoverflow.com/q/50637081
tags question: http://stackoverflow.com/q/50688323
tags question: http://stackoverflow.com/q/50589989
tags question: http://stackoverflow.com/q/50649510
tags question: http://stackoverflow.com/q/50581958
tags question: http://stackoverflow.com/q/50641495
tags question: http://stackoverflow.com/q/50670548
tags question: http://stackoverflow.com/q/50544754
tags question: http://stackoverflow.com/q/50596612

http://stackoverflow.com/comment/88095643
comment on: http://stackoverflow.com/q/50542195
has text: Do you try to give a variable the name `date&time`? [`&` is a bitwise operator in Python.](https://www.tutorialspoint.com/python3/python_basic_operators.htm)
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/88372907
type: QuestionComment
type: Comment
score: 1
has text: Could you post a minimal input file with the correct format?
comment on: http://stackoverflow.com/q/50681710

http://stackoverflow.com/comment/88349637
comment on: http://stackoverflow.com/q/50648920
score: 1
type: QuestionComment
type: Comment
has text: Did you attach an elastic GPU or something? t2.micro definitely doesn't have a GPU by default.

http://stackoverflow.com/q/50614920
has comment: http://stackoverflow.com/comment/88240193
has comment: http://stackoverflow.com/comment/88239848
tagged with: python
has comment: http://stackoverflow.com/comment/88267067
tagged with: tkinter
answer count: 0
tagged with: subprocess
has body: I'm trying to search through all the file in all sub-directories of my root directory to output lines that contain "key_phrases" that the user input. My current code can find and output lines for most files in my sub directories, but I cannot seem to find lines in certain files of the folder, almost as if they are invisible to the search. Below is my code for the python function and Tkinter GUI for the user to input the directory and key phrases. The Tkinter GUI is just for reference, I believe the problem is in the for loop of my Python function. My Python Function import os def searchandOutput(rootdir, keyPhrases): path = rootdir # Enter the root directory you want to search from key_phrases = [keyPhrases] # Enter here the key phrases in the lines you hope to find key_phrases = [i.replace('\n','') for i in key_phrases] #In case an "\n" is added to the end of the string when the parameter is passed to the function # This for loop allows all sub directories and files to be searched for (path, subdirs, files) in os.walk(path): files = [f for f in os.listdir(path) if f.endswith('.txt') or f.endswith('.log')] # Specify here the format of files you hope to search from (ex: ".txt" or ".log") #files = [f for f in files if f.endswith('.txt') or f.endswith('.log')] files.sort() # file is sorted list files = [os.path.join(path, name) for name in files] # Joins the path and the name, so the files can be opened and scanned by the open() function # The following for loop searches all files with the selected format for filename in files: # Opens the individual files and to read their lines with open(filename) as f: f = f.readlines() # The following loop scans for the key phrases entered by the user in every line of the files searched, and stores the lines that match into the "important" array for line in f: for phrase in key_phrases: if phrase in line: print(line) break print("The end of the directory has been reached, if no lines are printed then that means the key phrase does …
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/88239814
has comment: http://stackoverflow.com/comment/88267669
type: Question
has title: "Invisible Files" That Cannot Be Found Using Python For Loop
has comment: http://stackoverflow.com/comment/88267615
tagged with: user-interface
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/50685077
has body: I'm having trouble trying to make a regular expression to match a string ka toki.* (for example ka toki or ka toki knfjk), but not match if the first symbol after toki is a. So in other words I'm trying to match these: ka toki ka toki sadbkhbhd habsd ka tokijhvkhsd But not these: ka tokia ka tokia asdibasd ka tokiaasdgjkn
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/88379917
accepted answer: http://stackoverflow.com/a/50685142
has comment: http://stackoverflow.com/comment/88380004
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/88379838
type: AnsweredQuestion
has title: A regular expression to match a string and if that string ends with specific character, then don't match
downvote count: 1
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/88379868
has answer: http://stackoverflow.com/a/50685142
has answer: http://stackoverflow.com/a/50685204
answer count: 2
possible better answer: http://stackoverflow.com/a/50685204

http://stackoverflow.com/a/50551164
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50550654
type: AcceptedAnswer
downvote count: 0
has body: You can use the concept of flood fill algorithm for this problem. In your input image notice how the 'walls' are distinct and are neighbored by black pixels (path). When you initialize the algorithm at any one pixel within this 'wall' they will be separated from the rest of the image. Code: path = r'C:\Users\Desktop' filename = 'input.png' img = cv2.imread(os.path.join(path, filename)) cv2.imshow('Original', img) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(gray, 100, 255,cv2.THRESH_BINARY_INV) cv2.imshow('thresh1', thresh) im_floodfill = thresh.copy() h, w = thresh.shape[:2] mask = np.zeros((h+2, w+2), np.uint8) cv2.floodFill(im_floodfill, mask, (0,0), 255) cv2.imshow('im_floodfill', im_floodfill) cv2.imshow('fin', cv2.bitwise_not(cv2.bitwise_not(im_floodfill) + thresh)) There is another example detailing this function on THIS POST
answers question: http://stackoverflow.com/q/50550654
type: Answer
score: 3

http://stackoverflow.com/q/50670643
has title: TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()'
linked to: http://stackoverflow.com/q/34547185
has comment: http://stackoverflow.com/comment/119373157
downvote count: 0
favorite count: 0
upvote count: 11
type: Question
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/117850888
answer count: 1
has answer: http://stackoverflow.com/a/67536529
type: UnansweredQuestion
has body: I've created a custom user model in Django and everything went fine, but when I try to create a new user it gives me an error. Here are my files : models.py, where I created the user table: class UserModelManager(BaseUserManager): def create_user(self, email, password, pseudo): user = self.model() user.name = name user.email = self.normalize_email(email=email) user.set_password(password) user.save() return user def create_superuser(self, email, password): ''' Used for: python manage.py createsuperuser ''' user = self.model() user.name = 'admin-yeah' user.email = self.normalize_email(email=email) user.set_password(password) user.is_staff = True user.is_superuser = True user.save() return user class UserModel(AbstractBaseUser, PermissionsMixin): ## Personnal fields. email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=16) ## [...] ## Django manage fields. date_joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELD = ['email', 'name'] objects = UserModelManager() def __str__(self): return self.email def get_short_name(self): return self.name[:2].upper() def get_full_name(self): return self.name forms.py, where I created the signup form: class SignUpForm(UserCreationForm): email = forms.CharField(required=True, help_text='البريد الإلكترونى الخاص بك - يجب ان يكون حقيقى (يستخدم لتسجيل الدخول) ') name = forms.CharField(required=True, help_text='إسمك الحقيقى - سيظهر كأسم البائع') password1 = forms.CharField(widget=forms.PasswordInput, help_text='كلمة المرور - حاول ان تكون سهلة التذكر بالنسبة لك') password2 = forms.CharField(widget=forms.PasswordInput, help_text='تأكيد كلمة المرور - إكتب نفس كلمة المرور السابقة مرة أخرى') class Meta: model = UserModel fields = ('email','name', 'password1', 'password2', ) labels = { 'name': 'إسمك الحقيقى - سيظهر كأسم البائع', 'email': 'البربد الإلكترونى Email', 'password1': 'كلمة ال…
score: 11
has comment: http://stackoverflow.com/comment/118350879

http://stackoverflow.com/q/50618621
tagged with: http://stackoverflow.com/tag/csv
linked to: http://stackoverflow.com/q/23668427
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has body: I have two csv files that i created with python from an unstructured data but i don't want my script to output two files once i run the script on a json. So lets say i have a file A with columns as follows: File 1: feats ID A B C E AA 123 3343 234 2342 112 BB 121 3342 237 2642 213`` CC 122 3341 232 2352 912 DD 123 3343 233 5342 12 EE 121 3345 235 2442 2112 ...and so on with lets say, 10000 rows of different values and 6 columns. Now I want to check these values of column "ID" against file 2 and merge on the values of ID. File 2: Char_Name ID Cosmic Awareness Uatu 123 3.4 Galan 121 4.5 `` Norrin Radd 122 1.6 Shalla-bal 124 0.3 Nova 125 1.2 This file 2 has only 5 rows for 5 different values for b and lets say 23 column values. I can do this easily with map or apply in pandas but i'm dealing with 1000's of files and don't wanna do that. Is their any way like mapping the file 2 values (name and cosmic awareness columns) to File 1 by adding new columns titled 'name' and 'cosmic' (from file 2) by matching the values with corresponding ID values on File 1 and File 2. The expected output should be somewhat like this. Final File: feats ID A B C E Char_Name Cosmic Awareness AA 123 3343 234 2342 112 Uatu 3.4 BB 121 3342 237 2642 213`` Galan 4.5 CC 122 3341 232 2352 912 Norrin Radd 1.6 DD 123 3343 233 5342 12 Uatu 3.4 EE 121 3345 235 2442 2112 Galan 4.5 Thanks in advance and if their is any way to improve this question, the suggestions are welcome. I will incorporate them here. I have added the expected outcome above.
tagged with: mapping
has comment: http://stackoverflow.com/comment/88247902
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/50619258
type: Question
has comment: http://stackoverflow.com/comment/88248032
has answer: http://stackoverflow.com/a/50619258
tagged with: pandas
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/88247737
favorite count: 0
has comment: http://stackoverflow.com/comment/88247682
has title: CSV value mapping from 2 files like map in pandas

http://stackoverflow.com/q/50609193
favorite count: 0
has body: I have a simple Python implementation of Knuth's shuffling algorithm: def knuth_shuffle(ar): num = len(ar) for i in range(num): index = random.randint(0, i) ar[i], ar[index] = ar[index], ar[i] return ar How is it possible to test (using scipy or whatever other package) that the shuffling is indeed uniform? I have found a couple of related posts (1, 2) but they don't answer my question. It would be great to understand how to perform such checks in general.
answer count: 3
tagged with: python
score: 4
type: AnsweredQuestion
tagged with: shuffle
has answer: http://stackoverflow.com/a/50610374
has answer: http://stackoverflow.com/a/50609899
has comment: http://stackoverflow.com/comment/88230677
type: Question
possible better answer: http://stackoverflow.com/a/50611446
tagged with: algorithm
has answer: http://stackoverflow.com/a/50611446
has title: How to verify that a shuffling algorithm is uniform?
has comment: http://stackoverflow.com/comment/88228217
has comment: http://stackoverflow.com/comment/88228405
upvote count: 4
accepted answer: http://stackoverflow.com/a/50609899
downvote count: 0

http://stackoverflow.com/a/61561659
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50552404
has body: I was facing the same issue from hours and this time I tried to the zip file in reference from where I downloaded the Dataset and it works- df=pd.read_csv(r'C:\Users\ADMIN\news.csv')-Initializing from file failed df=pd.read_csv(r'C:\Users\ADMIN\news.zip')-Worked nicely!!

http://stackoverflow.com/comment/88144403
comment on: http://stackoverflow.com/q/50562965
type: QuestionComment
type: Comment
has text: I tried to be clearer, I edited the original post
score: 0

http://stackoverflow.com/q/50562280
has body: I want to select rows where values in 90% columns are less than a specified threshold. df = pd.DataFrame(np.random.randint(5, 15, (10, 11)), columns=list('abcdefghijk')) I can select rows where the value is less than the threshold (5) for all columns using the following syntax, df[(df[list('abcdefghijk')] &gt; 5).all(axis=1)] How to do this if the value for >90% columns instead of all? Thanks
has title: Pandas select rows with value less than in 90% columns
has answer: http://stackoverflow.com/a/50562300
tagged with: dataframe
upvote count: 2
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
score: 2
accepted answer: http://stackoverflow.com/a/50562300
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/88113076
comment on: http://stackoverflow.com/q/50550801
has text: Since all of the three RGB layers are the same, you can extract your original mask with `arr[:, :, 0]`, with `arr` being the mask loaded by `imread`. You can also convert it back to a Boolean array `a[:, :, 0].astype(bool)`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50683802
score: 2
upvote count: 3
downvote count: 1
has body: Just capitalize the first character of the first word: L = ["IBM", "announced", "the", "acquisition."] L[0] = L[0][0].upper() + L[0][1:] #Capitalizes first letter of first word L = " ".join(L) print(L) &gt;&gt;&gt;'IBM announced the acquisition.'
answers question: http://stackoverflow.com/q/50683716
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50683716
type: Answer

http://stackoverflow.com/comment/88313187
type: QuestionComment
has text: If the code in question is in a web2py controller, then it is running in response to an HTTP request, and therefore `db.commit()` is not necessary, as the framework calls it automatically at the end of HTTP request handling. Is the code really in a controller, or in a module? Or are you running the code via the web2py shell?
comment on: http://stackoverflow.com/q/50641849
score: 0
type: Comment

http://stackoverflow.com/comment/88155987
comment on: http://stackoverflow.com/a/50573038
score: 0
type: AnswerComment
has text: You are completely right! thank you very much for your time
type: Comment

http://stackoverflow.com/comment/88141727
comment on: http://stackoverflow.com/a/50564753
type: Comment
has text: Thanks! I haven't specified (my bad) that the first value of each key is unique. But the solution is working, so thank you!
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88186089
type: Comment
has text: You need to use a raw string (`r"..."`), otherwise some of the escapes will be interpreted wrongly.
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50587886

http://stackoverflow.com/comment/88136281
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50562759
type: AnswerComment
has text: @S.Benten Dude change dict keyword to your dict name, this one also works fine.

http://stackoverflow.com/comment/88392057
type: QuestionComment
comment on: http://stackoverflow.com/q/50691053
score: 0
has text: Probably the pictures. I removed those. By the way, you may want to add a line or two more about what you've tried.
type: Comment

http://stackoverflow.com/q/50632258
tagged with: android
tagged with: python
has answer: http://stackoverflow.com/a/50652415
has title: How to restore Tensorflow model from .pb file in python?
tagged with: tensorflow
type: Question
linked to: http://stackoverflow.com/q/58470251
type: AnsweredQuestion
has body: I have an tensorflow .pb file which I would like to load into python DNN, restore the graph and get the predictions. I am doing this to test out whether the .pb file created can make the predictions similar to the normal Saver.save() model. My basic problem is am getting a very different value of predictions when I make them on Android using the above mentioned .pb file My .pb file creation code: frozen_graph = tf.graph_util.convert_variables_to_constants( session, session.graph_def, ['outputLayer/Softmax'] ) with open('frozen_model.pb', 'wb') as f: f.write(frozen_graph.SerializeToString()) So I have two major concerns: How can I load the above mentioned .pb file to python Tensorflow model ? Why am I getting completely different values of prediction in python and android ?
score: 26
upvote count: 26
answer count: 2
accepted answer: http://stackoverflow.com/a/50652415
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/61656928
has answer: http://stackoverflow.com/a/61656928

http://stackoverflow.com/q/50584119
has title: CParserError when using github to store CSVs
score: 0
tagged with: pandas
tagged with: github
has body: My script loads panda-written-CSVs for analysis and charting and it works well when the files are stored locally. I loaded the csvs to my github but when trying to load them, I'm getting: ParserError: Error tokenizing data. C error: Expected 1 fields in line 31, saw 3 I'm aware of the read csv parsing issue as here and tried the solutions proposed, but again, the problem is specific to the use of github to store the files. Any ideas?? dir_path='https://github.com/ronyarmon/SFO/tree/master/Data/questions/' data_dfs_dict={} questions=['Airport as a whole', 'Signs &amp; directions inside SFO','Accessing &amp; using free WiFi','Restaurants', 'Retail shops &amp; concessions', 'Information on screens/monitors','Escalators/Elevators/Moving walkways', 'Information booths-Baggage claim','Information booths-Departure area','AirTrain', 'Signs &amp; directions-Roadways','Airport parking facilities','Long term parking lot shuttle', 'Airport rental car center','Artwork and exhibitions'] question_files_names=['ALL','SIGN','WIFI','FOOD','STORE','SCREENS','WALKWAYS', 'INFODOWN','INFOUP', 'AIRTRAIN','ROADS','PARK','LTPARKING','RENTAL','ART'] for index,value in enumerate(question_files_names): file_name=value+'.csv' file_path=dir_path+file_name print (index, value) data_dfs_dict[questions[index]]=pd.read_csv(file_path) #data_dfs_dict[questions[index]]=pd.read_csv(file_path,error_bad_lines=False) options_list=data_dfs_dict.keys()
has comment: http://stackoverflow.com/comment/88177376
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88186518
tagged with: python
answer count: 0
type: Question

http://stackoverflow.com/q/50634434
score: 1
type: Question
has comment: http://stackoverflow.com/comment/88279029
answer count: 1
downvote count: 0
has title: Using numba.jit on a user input string
has answer: http://stackoverflow.com/a/50634537
has comment: http://stackoverflow.com/comment/88279194
accepted answer: http://stackoverflow.com/a/50634537
tagged with: python
favorite count: 0
has body: I'm trying to write a program that takes in a user input function as a string and does a number of calculations using that function. These calculations are done using numba.jit, and the code works if I hardcode my function, but I'm having trouble figuring out how to parse the string in such a way that I can turn it into a jitted function with nopython=True. For example, my code runs with the function @jit(nopython=True) def f(x): return x*x but I want to, instead, take the user input string 'x*x' and create the same function. I've tried using SymPy, but I couldn't make it play nicely with jit. Any ideas?
tagged with: numba
upvote count: 1
type: AnsweredQuestion

http://stackoverflow.com/a/50610110
type: Answer
has comment: http://stackoverflow.com/comment/88230945
has comment: http://stackoverflow.com/comment/88230022
has comment: http://stackoverflow.com/comment/88230104
has comment: http://stackoverflow.com/comment/88230455
answers question: http://stackoverflow.com/q/50610012
has comment: http://stackoverflow.com/comment/88230872
has body: You need: df.set_index(pd.to_datetime(df['date'])).loc['2018-01-01':'2018-01-31'].reset_index(drop=True) Output: date payment 0 01.01.18 32 1 01.01.18 8 2 01.01.18 12 3 01.01.18 77 You can keep using your original dateformat as well with below code and achive same output: import datetime as dt start = dt.datetime.strptime('01.01.18', '%d.%m.%y').strftime('%Y-%m-%d') end = dt.datetime.strptime('31.01.18', '%d.%m.%y').strftime('%Y-%m-%d') df.set_index(pd.to_datetime(df['date'])).loc[start:end].reset_index(drop=True)
has comment: http://stackoverflow.com/comment/88231175
has comment: http://stackoverflow.com/comment/88231234
score: 0
has comment: http://stackoverflow.com/comment/88230272

http://stackoverflow.com/a/50638040
has comment: http://stackoverflow.com/comment/88295877
has comment: http://stackoverflow.com/comment/88286093
has comment: http://stackoverflow.com/comment/88286476
has comment: http://stackoverflow.com/comment/88287230
has comment: http://stackoverflow.com/comment/88287255
has body: Yes it will: you will have to wait for an iPython 3.7 distribution, and install it. In all likeliness, it will be published shortly after the python 3.7 final version, which is due around mid of June
has comment: http://stackoverflow.com/comment/88287075
accepted answer of: http://stackoverflow.com/q/50637990
has comment: http://stackoverflow.com/comment/88286915
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88286414
answers question: http://stackoverflow.com/q/50637990
has comment: http://stackoverflow.com/comment/88296013
has comment: http://stackoverflow.com/comment/88287177
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/88297785
score: 2
has comment: http://stackoverflow.com/comment/88286043
has comment: http://stackoverflow.com/comment/88286841
has comment: http://stackoverflow.com/comment/88286266
has comment: http://stackoverflow.com/comment/88286672

http://stackoverflow.com/a/50601829
has body: The first form you use if you want to split instances with features (X) and labels (y). The second form you use if you only want to split features (X). X_train, X_test, y_train, y_test= train_test_split(data, y, test_size=0.3, random_state=42) The reason why it didn' t work for you was because you didn't prodide the label data in your train_test_split() function. The above should work well. Just replace y with your label/target data.
score: 1
upvote count: 2
downvote count: 1
answers question: http://stackoverflow.com/q/50601713
type: Answer

http://stackoverflow.com/q/50618855
answer count: 1
downvote count: 0
has title: How to download file using django-storage sftp?
tagged with: django-rest-framework
favorite count: 0
has body: I'm using django storage module to store file in a location using sftp and now we need to download same file from sftp. Any suggestions? models.py from storages.backends.sftpstorage import SFTPStorage SFS = SFTPStorage() class Configurations(BaseModel): name = models.CharField(max_length=150, unique=True) file = models.FileField(upload_to='configurations', storage=SFS) descriptions = models.TextField(null=True, blank=True) settings.py DEFAULT_FILE_STORAGE = 'storages.backends.sftpstorage.SFTPStorage' SFTP_STORAGE_HOST = '127.0.0.1' SFTP_STORAGE_ROOT = '/var/www/media/' SFTP_STORAGE_PARAMS = { 'username': 'root', 'password': 'password', 'allow_agent': False, 'look_for_keys': False, } # SFTP_KNOWN_HOST_FILE = '~/.ssh/known_hosts' SFTP_STORAGE_INTERACTIVE = False views.py from django.http import Http404 from rest_framework import viewsets from rest_framework.parsers import MultiPartParser, FormParser from .models import (CustomConfigurations) from .serializers import (CustomConfigurationsSerializers) class ToolCustomConfigurationsViewSet(viewsets.ModelViewSet): queryset = CustomConfigurations.objects.all() parser_classes = (FormParser, MultiPartParser,) serializer_class = CustomConfigurationsSerializers def get_queryset(self): queryset = self.queryset.all().order_by('-id') return queryset serializer.py class CustomConfigurationsSerializers(serializers.ModelSerializer): class Meta: model = CustomConfigurations fields = '__all__'
accepted answer: http://stackoverflow.com/a/50622500
tagged with: sftp
tagged with: python
type: AnsweredQuestion
upvote count: 3
tagged with: django
type: Question
score: 3
has answer: http://stackoverflow.com/a/50622500

http://stackoverflow.com/q/50615734
upvote count: 1
has body: I have a big array of allowed integer values, and I want to figure out the entries' value by finding their corresponding index in a different array containing all possible values. It is the same problem that can be solved with np.where() with individual numbers: E.g. my_val = 3 possible_val_array = np.array([-1, 2, 3]) idx = np.where(my_val==possible_val_array)[0][0] This returns: idx 2 Now I want to do this with a whole array of values all at once. I know this can be done with np.searchsorted() and some other functions when my arrays are 1D. However, I would like to do this with a multidimensional array: E.g. my_val_array = np.array([(-1,2,3),(3,-1,-1)]) possible_val_array = np.array([-1, 2, 3]) idx = np.where(my_val_array==possible_val_array) This would return: idx array([[0, 1, 2], [2, 0, 0]]) Is there any way to do this without reshaping my array to be 1D?
type: Question
tagged with: numpy
duplicate of: http://stackoverflow.com/q/33678543
tagged with: arrays
has title: Search indexes where values in my array match a value in a different array (python)
downvote count: 0
linked to: http://stackoverflow.com/q/33678543
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1

http://stackoverflow.com/q/50645707
tagged with: django
type: Question
has title: Can't run Django project
has answer: http://stackoverflow.com/a/50645856
has comment: http://stackoverflow.com/comment/88303884
score: 0
has comment: http://stackoverflow.com/comment/88302023
has comment: http://stackoverflow.com/comment/96452614
answer count: 1
has body: I wanted to run official Django tutorial. I've installed Django using pip, and started the project. And when I run python manage.py runserver the console shows the same thing as in tutorial, but when I open the page http://127.0.0.1:8000/ or localhost:8000 I only see 404 not found.
has comment: http://stackoverflow.com/comment/88301938
has comment: http://stackoverflow.com/comment/88302012
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/50640038
tagged with: python
has comment: http://stackoverflow.com/comment/88291693
has comment: http://stackoverflow.com/comment/88291841
type: Question
has title: Replace a subset of rows of dataframe A with rows of dataframe B in python pandas
tagged with: dataframe
has answer: http://stackoverflow.com/a/50640969
score: 0
tagged with: pandas
has body: I'm trying to replace the values in the rows 500 to 750 in column col1 in dataframe df_A with the values column col1 of dataframe df_B (with altogether 250 rows) in Python Pandas. I tried doing it like this df_A.col1.iloc[500:750] = df_B.col1 But this yields the notorious A value is trying to be set on a copy of a slice from a DataFrame and the values in df_A.col1.iloc[500:750] get replaced by NaNs . So how can I do this kind of replacement of several rows with rows from another dataframe in Pandas without using a for-loop?
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/q/50569113
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50577787
tagged with: python
has answer: http://stackoverflow.com/a/50570338
linked to: http://stackoverflow.com/q/20986631
score: 2
tagged with: bots
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88149046
tagged with: selenium
has title: Scroll down a table selenium python
type: Question
has body: I'm trying to write a program for scrolling down to a specific item in an html ul. I tried to use driver.execute_script("window.scrollBy(0,2000)") but it doesn't do anything. I also tried the following: elem = driver.find_element_by_css_selector("._p4iax") segui = driver.find_element_by_css_selector ("._qv64e._gexxb._4tgw8._njrw0") elem.execute_script("arguments[0].scrollIntoView(true);", segui) And that gave me this error: AttributeError: 'WebElement' object has no attribute 'execute_script' The element that i'm trying to scroll down to is this: all the elements that i tried to target have the same error. What am I doing wrong? it's the instagram table of the followers on chrome Follower officialj0ny___ Jny_Hussein Segui già stefanopalmieri33 Stefano❤ Segui hypewearesell HypeWeaResell Segui già boumybabyfootwear Boumy Segui già enrico_lavaroni Enrico Lavaroni Segui già theov87 Theo V Segui già vctorfdez '' VIC '' Segui già michele.m.cristini Michele Cristini Segui già jaco_sanson jacopo sanson Segui già chasingsuccesstwin Twin Segui già thy.dunhill Jeffrëy Dûnhîll Segui già _chico_alex_ Alex 2003 Segui già Chiudi
has comment: http://stackoverflow.com/comment/88151258
upvote count: 2
answer count: 2

http://stackoverflow.com/q/50640122
has comment: http://stackoverflow.com/comment/88348634
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88290336
score: 1
has answer: http://stackoverflow.com/a/50640396
has comment: http://stackoverflow.com/comment/88290620
has answer: http://stackoverflow.com/a/50640176
accepted answer: http://stackoverflow.com/a/50640176
type: Question
has comment: http://stackoverflow.com/comment/88290305
downvote count: 0
has answer: http://stackoverflow.com/a/50640411
has answer: http://stackoverflow.com/a/50640734
has body: I'd like to initialise a variable inside a function (so that the final print statement in my example outputs 10): def init_param(param): param = 10 n = 1 init_param(n) print n # prints 1 Is this doable in python?
has title: How to assign value to function parameter in python
upvote count: 1
has comment: http://stackoverflow.com/comment/88290477
possible better answer: http://stackoverflow.com/a/50640396
answer count: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/88290362
has comment: http://stackoverflow.com/comment/88290399
tagged with: python

http://stackoverflow.com/a/50598578
answers question: http://stackoverflow.com/q/50598524
has comment: http://stackoverflow.com/comment/88206678
has body: Use the following to force inference of those values as floats on read: import pandas import numpy as np pandas.read_csv(filepath[0], header=None, delim_whitespace=True, lineterminator='\r', dtype=np.float64) This works with upper case 'E'. Example pd.DataFrame({'a':['5.64E-4', '0.1259', '3.556E-4'], 'b':['a', 'b', 'c']}, dtype=np.float64) Output a b 0 0.000564 a 1 0.125900 b 2 0.000356 c
has comment: http://stackoverflow.com/comment/88206589
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/88207121

http://stackoverflow.com/comment/88268666
has text: When i requested the same using the hello function it worked fine. But not able to do it with temperature function. Please help me with this.
type: AnswerComment
comment on: http://stackoverflow.com/a/50613463
type: Comment
score: 0

http://stackoverflow.com/comment/88332806
type: Comment
has text: I guess I could have phrased it better. We "add" a random column temporarily. We then solve for `x` that is orthogonal to all of the original columns but _not_ the random column. In particular, `x` is not zero. So x would correspond to a_{d+1} in your terminology. BTW `np.dot(O.T, O) = I` would imply that the vectors are orthonormal. Orthogonal vectors would lead to a diagonal matrix.
comment on: http://stackoverflow.com/a/50661011
type: AnswerComment
score: 0

pre-trained-model
tags question: http://stackoverflow.com/q/50669990
type: Tag
tag name: pre-trained-model

http://stackoverflow.com/comment/106598068
has text: Does this answer your question? [ValueError: "color kwarg must have one color per dataset" matplotlib seaborn](https://stackoverflow.com/questions/58329965/valueerror-color-kwarg-must-have-one-color-per-dataset-matplotlib-seaborn)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50559775

http://stackoverflow.com/comment/88188401
has text: Thanks for the information!
score: 0
comment on: http://stackoverflow.com/q/50589489
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50696069
has answer: http://stackoverflow.com/a/50696141
downvote count: 0
answer count: 1
has title: The `get_context_data` of attribute of class object
linked to: http://stackoverflow.com/q/533631
favorite count: 0
accepted answer: http://stackoverflow.com/a/50696141
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
tagged with: django
type: Question
has body: The get_context_data of attribute of class object. I encounter PasswordContextMixin in django/contrib/auth/views.py class PasswordContextMixin: extra_context = None def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update({ 'title': self.title, **(self.extra_context or {}) }) return context I am confused with context = super().get_context_data(**kwargs), because it equals to context = object.get_context_data(**kwargs) In [15]: getattr(object, 'get_context_data') AttributeError: type object 'object' has no attribute 'get_context_data' How to understand this?

http://stackoverflow.com/comment/88136841
score: 0
type: Comment
type: QuestionComment
has text: Okay, so I found the problem. The above thing works for some weird reason when instantiated and then shown/hidden, whereas a newly instantiated progress bar only chooses to display above a certain limit, as QProgressDialog has a `minimumDuration()`.
comment on: http://stackoverflow.com/q/50562433

http://stackoverflow.com/q/50648154
has title: Microsecond Time Stamps in PySpark
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/88309958
tagged with: apache-spark-sql
tagged with: pyspark
tagged with: apache-spark
score: 2
downvote count: 0
favorite count: 0
has body: I am trying to convert a microsecond string to timestamp using the following syntax in pyspark. However, I seem to be getting a null when I convert. I am using Spark 2.2 My string looks like 20180503-07:05:00.008288 I'm using the following code to convert to Timestamp df = df.withColumn("my_time_timestamp",to_timestamp("my_time", "yyyyMMdd-hh:mm:ss.SSSSSS")) Can anyone tell me what is missing here?
upvote count: 2
has comment: http://stackoverflow.com/comment/88310933
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88307245
tagged with: python

http://stackoverflow.com/a/59000283
score: -1
answers question: http://stackoverflow.com/q/50569453
has body: I found a solution, modifying the most voted answer: "python.linting.pylintArgs": [ "--extension-pkg-whitelist=pygame" ] Replaced the "lxml" with "pygame".
type: Answer
upvote count: 2
downvote count: 3

azure-iot-hub
type: Tag
tag name: azure-iot-hub
tags question: http://stackoverflow.com/q/50651390

http://stackoverflow.com/comment/88204051
has text: the excepted output: Counter list: [ 8, 5, 5]
comment on: http://stackoverflow.com/q/50596895
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88152642
type: Comment
type: QuestionComment
has text: I mean using a 100000 x 5000 x 3 array
comment on: http://stackoverflow.com/q/50571381
score: 0

http://stackoverflow.com/q/50645044
has body: Just curious if anybody knows why this happens. I have python code that triggers and runs a macro in a workbook. The macro can take several hours to run. If I run the macro without the use of Python, my workbook is open and for the time it takes the macro to run I am unable to use excel until the macro is completed. What I noticed when I run the macro via Python, the sheet doesn't open and not only that but I am able at the same time python runs the excel macro I can actually open up other workbooks. How does this happen? and where is the python triggered workbook macro run from? It doesn't even pop up in the Task Manager? If anybody knows how this happens I would love to know! Regards, T
downvote count: 1
tagged with: excel
type: AnsweredQuestion
has title: Running Macro through Python and still able open new excel sheets
score: -1
type: Question
answer count: 1
tagged with: vba
favorite count: 0
tagged with: python
upvote count: 0
has answer: http://stackoverflow.com/a/50645464
accepted answer: http://stackoverflow.com/a/50645464

http://stackoverflow.com/comment/88274470
score: 0
comment on: http://stackoverflow.com/a/50610328
has text: ValueError: cannot convert float NaN to integer I get this error while running your suggested code can you please help me out
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88279655
has text: While, humorous, this doesn't really answer the question further than "yes" and should just be an edit to the original question.
score: 1
comment on: http://stackoverflow.com/a/50631635
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50627285
type: Question
score: -2
has body: Say I have 2 dataframes. first: 100K rows columns: ID, ch1,ch2...ch10, binary values second 1000K rows columns: ID, CH. say I wanna add to DF2 the values of DF1, in 1 column that it will fit the ID&amp;chan. I tried to do it with a simple for-loop but it took a few minutes just to get past the first 10K rows.. I wonder how it can be done effectively - as if I've done it with numpy, it'd work faster. just to clarify, the IDs can be shuffled in DF2.. so I can't predict it's location based on DF1. thanks in advance!
has comment: http://stackoverflow.com/comment/88264699
has comment: http://stackoverflow.com/comment/88339083
has comment: http://stackoverflow.com/comment/88264729
downvote count: 2
tagged with: pandas
answer count: 1
favorite count: 0
has title: how to change panda data-frame values effectively
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50628060
upvote count: 0

http://stackoverflow.com/q/50666335
tagged with: subclass
has answer: http://stackoverflow.com/a/50666602
tagged with: python
has comment: http://stackoverflow.com/comment/88342588
type: AnsweredQuestion
has title: Python classes and types
type: Question
answer count: 2
has body: I think I'm misusing the concept of subclass. I'm working on a hobby project with Grids and Cells. What I have, is the implementation of a Cell class, and its subclass HexCell which basically redefines many of the attributes/methods like so: class Cell: def __init__(self, row_loc, col_loc): self.row = row_loc self.col = col_loc self.links = set() self.neighbors = 4*[None] def __repr__(self): return f'Cell @({self.row},{self.col})' def link(self, other, bidir = True): self.links.add(other) if bidir: other.links.add(self) Then I have a subclass that is the HexGrid which follows a similar structure with new parameters. class HexCell(Cell): def __init__(self, r_out, th_around): # I'm indexing Hex cells around a center cell # instead of by rows and columns; Prefixed hex # as they follow the hexagon, and not regular polar coordinates. self.hex_r = r_out self.hex_th = th_around self.neighbors = 6*[None] self.links = set() def __repr__(self): return f"HexCell @[{self.hex_r}, {self.hex_th}]" def bind(self, other, to_dir): to_dir = to_dir % 6 if (self.neighbors[to_dir] is None): self.neighbors[to_dir] = other other.neighbors[to_dir - 3] = self # Hexagonal grids share neighbors. other_1 = other.neighbors[to_dir - 2] if (self.neighbors[to_dir - 1] is None) &amp; (other_1 is not None): self.bind(other_1, to_dir - 1) other_5 = other.neighbors[to_dir - 4] if (self.neighbors[to_dir - 5] is None) &amp; (other_5 is not None): self.bind(other_5, to_dir - 5) In this case, the method self.link(other) is shared, but other attributes change from rectangular grid to hexagonal like the locaion from (row, col) to (hex_r, hex_th), or neighbors as a 4-list or 6-list. Thus I'd like these attributes to be dependent on a another cell-type attribute and transferred down to the subclass.
tagged with: class
score: 0
accepted answer: http://stackoverflow.com/a/50666529
possible better answer: http://stackoverflow.com/a/50666602
has answer: http://stackoverflow.com/a/50666529

http://stackoverflow.com/comment/88411177
type: AnswerComment
comment on: http://stackoverflow.com/a/50700776
type: Comment
has text: If you see the given picture clearly, you will get it's Windows OS ( first picture , upper right corner ) and it's Python 3.6 ( first picture upper left corner ). And which i didn't mention is version of Spyder IDE , which is 3.2.8.
score: 2

http://stackoverflow.com/a/56053192
downvote count: 0
answers question: http://stackoverflow.com/q/50686388
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/99278671
has body: Open Command Prompt and type in; pip install discord.py or; pip install discord.py==1.0.1 and then if you want voice do; pip install discord.py[voice]

http://stackoverflow.com/comment/88117254
score: 0
has text: That completely depends on your jobs and your programs. Only you or the author of the program can know what your program can or cannot compute.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50546037

http://stackoverflow.com/comment/88178890
type: QuestionComment
comment on: http://stackoverflow.com/q/50551480
has text: try cleaning by issuing: sudo mn -c
score: 0
type: Comment

dialogflow-es
tag name: dialogflow-es
tags question: http://stackoverflow.com/q/50674199
tags question: http://stackoverflow.com/q/50643873
type: Tag

http://stackoverflow.com/q/50685860
has answer: http://stackoverflow.com/a/50686050
score: -2
has comment: http://stackoverflow.com/comment/88381536
has comment: http://stackoverflow.com/comment/88381631
answer count: 1
accepted answer: http://stackoverflow.com/a/50686050
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88381779
has comment: http://stackoverflow.com/comment/88381456
upvote count: 1
tagged with: python
type: AnsweredQuestion
has title: Index of a local maximum in a list
downvote count: 3
has comment: http://stackoverflow.com/comment/88381599
has comment: http://stackoverflow.com/comment/88381694
has comment: http://stackoverflow.com/comment/88381604
type: Question
has body: I know that there's a similar problem which was already has answered, but mine is just a little bit different (because it returns the index of the local maximum in a list, instead of the number). So, I do just need an explanation about how should I start my code, since I have no idea about where to start. (Sorry for my English). Thanks. def maxloc(xs): while True: for i in range(len(xs)): if xs[i] &gt; xs[i-1] and xs[i] &gt; xs[i+1]: big = xs[i] return [i] -x- I've tried again, but the problem now is different. I changed some of my code and the return is always [ ]. Can't understand why. Can ou help me now that I have some code, please? def maxloc(xs): l1 = [] for i in range(1, len(xs)-1): if xs[i] &gt; xs[i-1] and xs[i] &gt; xs[i+1]: l1.append(i) return [l1] return []
has comment: http://stackoverflow.com/comment/88381611

http://stackoverflow.com/q/50627963
upvote count: 2
has title: LightGBMError: b'No OpenCL device found'
has body: I want to train LightGBM with GPU on my dataset using Google colaboratory (I also select runtime Python3 and GPU). To do this I used follow chunk of code: !apt-get -qq install --no-install-recommends nvidia-375 !apt-get -qq install --no-install-recommends nvidia-opencl-icd-375 nvidia-opencl-dev opencl-headers #!apt-get update !apt-get install --no-install-recommends git cmake build-essential libboost-dev libboost-system-dev libboost-filesystem-dev ocl-icd-libopencl1 ocl-icd-opencl-dev !pip install -qq lightgbm --install-option=--gpu Also in notebook I selected device gpu: clf = LGBMClassifier( n_estimators=10000, learning_rate=0.03, num_leaves=30, colsample_bytree=.8, subsample=.9, max_depth=7, reg_alpha=.1, reg_lambda=.1, min_split_gain=.01, min_child_weight=2, silent=-1, verbose=-1, device = 'gpu' #gpu_platform_id: '0' #gpu_device_id: '0' ) And got this: LightGBMError Traceback (most recent call last) &lt;ipython-input-10-936c00d106e3&gt; in &lt;module&gt;() 50 clf.fit(trn_x, trn_y, 51 eval_set= [(trn_x, trn_y), (val_x, val_y)], ---&gt; 52 eval_metric='auc', verbose=100, early_stopping_rounds=100 #30 53 ) 54 /usr/local/lib/python3.6/dist-packages/lightgbm/sklearn.py in fit(self, X, y, sample_weight, init_score, eval_set, eval_names, eval_sample_weight, eval_class_weight, eval_init_score, eval_metric, early_stopping_rounds, verbose, feature_name, categorical_feature, callbacks) 673 verbose=verbose, feature_name=feature_name, 674 categorical_feature=categorical_feature, --&gt; 675 callbacks=callbacks) 676 return self 677 /usr/local/lib/python3.6/dist-packages/lightgbm/sklearn.py in fit(self, X, y, sample_weight, init_score, group, eval_set, eval_names, eval_sample_weight, eval_class_weight, eval_init_score, eval_group, eval_metric, early_stopping_rounds, verbose, feature_name, categorical_feature, callbacks) 467 verbose_eval=verbose, feature_name=feature_name, 468 categorical_feature=categorical_feature, --&gt; 469 callbacks=callbacks) 470 471 if evals_result: /usr/…
type: Question
tagged with: google-colaboratory
answer count: 2
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/70696847
favorite count: 0
has answer: http://stackoverflow.com/a/58351515
tagged with: lightgbm
tagged with: gpu
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/49606886
tagged with: python

http://stackoverflow.com/q/50615763
type: Question
accepted answer: http://stackoverflow.com/a/50660127
has title: Dictionary key, value pairs of a cell to columns whose name is key and row is value in Pandas
tagged with: pandas
downvote count: 0
answer count: 1
score: 1
has body: I found it very hard to frame the question using the right words.. But I hope I've done a good job.. Here is an example that I artificially created so you can reproduce it in your console. example = pd.DataFrame([['a', [{'a1': 1, 'a2': {'amount': 20, 'currency': 'USD'}, 'a3': 57}, {'a1': 4, 'a2': {'amount': 50, 'currency': 'USD'}}, {'a1': 7, 'a2': {'amount': 80, 'currency': 'USD'}}], 10, 11], ['b', [{'a1': 13, 'a2': {'amount': 140, 'currency': 'USD'}}, {'a1': 2, 'a2': {'amount': 50, 'currency': 'USD'}}, {'a1': 3, 'a2': {'amount': 90, 'currency': 'USD'}}], 16, 17], ['c', [{'a1': 8, 'a2': {'amount': 75, 'currency': 'USD'}}, {'a1': 9, 'a2': {'amount': 90, 'currency': 'USD'}, 'a3': 98}, {'a1': 6, 'a2': {'amount': 10, 'currency': 'USD'}}], 11, 12]]) example.columns = ['column1', 'column2', 'column3', 'column4'] print(example) The DataFrame example's second column is a list of nest dictionary like structure. print(example.loc[[0], ["column2"]].values.tolist()) [[[{'a1': 1, 'a2': {'amount': 20, 'currency': 'USD'}, 'a3': 57}, {'a1': 4, 'a2': {'amount': 50, 'currency': 'USD'}}, {'a1': 7, 'a2': {'amount': 80, 'currency': 'USD'}}]]] This is row 0, column named column2 that I've printed using loc. The print(exampleSolution) statement should give you the Pandas DataFrame I'm looking to get. exampleSolution = pd.DataFrame([['a', 1, 20, 'USD', 57, 10, 11], ['a', 4, 50, 'USD', None, 10, 11], ['a', 7, 80, 'USD', None, 10, 11], ['b', 13, 140, 'USD', None, 16, 17], ['b', 2, 50, 'USD', None, 16, 17], ['b', 3, 90, 'USD', None, 16, 17], ['c', 8, 75, 'USD', None, 11, 12], ['c', 9, 90, 'USD', 98, 11, 12], ['c', 6, 10, 'USD', None, 11, 12]]) exampleSolution.columns = ['column1', 'a1', 'amount', 'currency', 'a3', 'column3', 'column4'] print(exampleSolution) Basically, I want the dictionary inside column2 to be unpacked for each row, I want the dictionary key to be an additional column name, and the value in the row to be the dictionary value corresponding to that key. In case there are certa…
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/50660127
type: AnsweredQuestion
upvote count: 1

http://stackoverflow.com/comment/88385723
type: QuestionComment
has text: @WillemVanOnsem `clean`. My fault.
comment on: http://stackoverflow.com/q/50687879
score: 0
type: Comment

http://stackoverflow.com/comment/88333612
score: 0
type: QuestionComment
has text: you have no way of breaking out of your infinite loop, so a non-cyclic list will run forever.
comment on: http://stackoverflow.com/q/50661733
type: Comment

http://stackoverflow.com/comment/88774422
score: 0
has text: If the answer below solved your problem, please consider clicking the tick next to the post. This let's the community know your question has been answered.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50607465

http://stackoverflow.com/comment/88368857
comment on: http://stackoverflow.com/a/50679741
score: 0
type: AnswerComment
has text: so, how would i modify it to have UTF-8 characters?
type: Comment

http://stackoverflow.com/comment/88387262
type: QuestionComment
type: Comment
has text: You method of writing classes and functions is strange to me. Why are you using `@_create_container`. It is not something I am use to seeing so I would like to know the reason.
comment on: http://stackoverflow.com/q/50686913
score: 0

http://stackoverflow.com/q/50673439
has title: Keep toolbar while changing screens kivy
linked to: http://stackoverflow.com/q/42613955
has answer: http://stackoverflow.com/a/50690230
type: Question
has body: So I have a toolbar and it I want to use it to change between screens, but I want it to stay there while I'm freely changing the screens. If I try to put a GridLayout inside a ScreenManager class it gives me an error, so instead I'm creating a GridLayout and embedding a Screen Manager into it. But it doesn't seems to work the way I want it to. storeapp.py from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.gridlayout import GridLayout class ScreenSwitcher(ScreenManager): def __init__(self, **kwargs): super(ScreenSwitcher, self).__init__(**kwargs) self.add_widget(ScreenOne(name='sone')) self.add_widget(ScreenTwo(name='stwo')) class ScreenOne(Screen): pass class ScreenTwo(Screen): pass class MainScreen(GridLayout): manager = ScreenSwitcher() class StoreApp(App): def build(self): return MainScreen() if __name__ == "__main__": StoreApp().run() store.kv #:kivy 1.10.1 &lt;ToolBar@BoxLayout&gt;: size_hint_y: None height: 35 pos_hint: {'top': 1, 'y': 0} padding: 5,2,5,2 spacing: 5 canvas: Color: rgba: .7, 1, .7, 1 Rectangle: pos: self.pos size: self.size &lt;ToolButton@Button&gt;: color: 0,0,0,1 align: 'center' &lt;ScreenOne&gt;: Label: text: 'SCREEN ONE' font_size:50 &lt;ScreenTwo&gt;: Label: text: 'SCREEN TWO' font_size:50 &lt;MainScreen&gt;: rows: 2 size_hint: 1, 1 ToolBar: ToolButton: text: 'Screen one' on_press: root.manager.current = 'sone' ToolButton: text: 'Screen two' on_press: root.manager.current = 'stwo' ScreenSwitcher: PROBLEM: the two screens are overlapping and pressing the buttons doesn't change anything.
score: 0
answer count: 2
tagged with: toolbar
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50673972
tagged with: python
tagged with: kivy

http://stackoverflow.com/comment/88313538
has text: RafaelC: Thank you. Can we do something similar in list?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50651294
type: Comment

http://stackoverflow.com/comment/88400172
has text: It needs to be random. No fixed logic. However, for every input value 'A20', if the output is 'B2134' then it should always be 'B2134' even when the code is re-run. PS: I've updated the code in question.
comment on: http://stackoverflow.com/a/50682383
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50693203
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/50693563
score: 0
has body: Given a word and a list of words, I have to find the list elements/words that can be built using letters (count of letter matters) of the given word. I have tried to use Counter object from collections and a definition of python 2.7's cmp() function (I'm using 3.6.5). I have since come to realize this approach seems to be bad practice for such a problem (Earlier, I was trying to use counter object-dictionaries to compare). The reason my program doesn't work is because the compare_fn relies on '>','&lt;' operations between lists, which give result based on lexicographical order (referred from here). So even though 'raven' can be made from 'ravenous', the program below will fail because of the order of char in a sorted list. from collections import Counter word = 'ravenous' candidates = ["raven", "mealwheel", "rasputin"] def count_fn(mystr): return sorted(list(Counter(mystr).items())) def compare_fn (c1,c2): return ((c1&gt;c2) - (c1&lt;c2)) list_word = count_fn(word) list_candidates = list(map(count_fn,candidates)) cmp_list = [compare_fn(list_word,i) for i in list_candidates] cmp_list #[-1, -1, -1] #should be [1,-1,-1] So, for below two lists, how can I confirm that list_candidates[0] is a subset of list_word. Please note that the comparison ('a',1) in list_word against ('a',1) in list_candidates[i] could also be ('a',5) in list_word against ('a',1) in list_candidates[i] ; both cases are true. print(list_word) #[('a', 1), ('e', 1), ('n', 1), ('o', 1), ('r', 1), ('s', 1), ('u', 1), ('v', 1)] print(list_candidates[0]) #[('a', 1), ('e', 1), ('n', 1), ('r', 1), ('v', 1)]
has title: Compare list of tuples, confirm subset based on condition?
has comment: http://stackoverflow.com/comment/88396751
tagged with: counter
tagged with: string
has comment: http://stackoverflow.com/comment/88421212
type: AnsweredQuestion
tagged with: python-3.x
linked to: http://stackoverflow.com/q/13052857
has comment: http://stackoverflow.com/comment/88396615
type: Question
has answer: http://stackoverflow.com/a/50693563

http://stackoverflow.com/a/50568224
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88149095
has comment: http://stackoverflow.com/comment/88149874
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50566484
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50566484
has body: The general subject of I/O buffering has been treated many times (including in questions linked from the comments). But to answer your specific questions: By default, when writing to a terminal (“the screen”), a newline causes the text to be flushed up through it. For all files, the buffer is flushed each time it fills. (Large single writes might flush any existing buffer contents and then bypass it.) The buffer has a fixed size and is allocated before any data is written; Python&nbsp;3 doesn’t use stdio, so it chooses its own buffer sizes. (A few kB is typical.) The “disk I/O” (really kernel I/O, which is distinguishable only in certain special circumstances like network/power failure) happens within whatever Python write triggers the flush. Yes, it can hang, if the file is a pipe to a busy process, a socket over a slow network, a special device, or even a regular file mounted from a remote machine.

http://stackoverflow.com/q/50547040
tagged with: python-unicode
tagged with: dataframe
type: UnansweredQuestion
tagged with: pandas
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/88104881
tagged with: python
score: 0
has title: ASCII and UTF problems in dataframe
tagged with: urllib
linked to: http://stackoverflow.com/q/26592988
has body: I have a dataframe where I have symbols such as %22 and I am trying to replace them using urllib. For other files this code worked perfectly but for some reason I am getting this error. Any ideas how I can fix this. As far as I know I am using utf-8. df = pd.read_csv('Data\Genres\cleanedGenreArtistSong.csv',engine = 'python', encoding = 'utf-8-sig') df['Song'] = df['Song'].apply(lambda x:urllib.unquote(x).decode('utf8') ) The error I am getting is: UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 1: ordinal not in range(128) This is a snapshot of my dataframe: enter image description here
has comment: http://stackoverflow.com/comment/88104927

http://stackoverflow.com/q/50579145
downvote count: 1
type: Question
tagged with: sympy
has answer: http://stackoverflow.com/a/64488257
has title: How do I simplify the sum of sine and cosine in SymPy?
answer count: 2
tagged with: symbolic-math
tagged with: trigonometry
favorite count: 0
has body: How do I simplify a*sin(wt) + b*cos(wt) into c*sin(wt+theta) using SymPy? For example: f = sin(t) + 2*cos(t) = 2.236*sin(t + 1.107) I tried the following: from sympy import * t = symbols('t') f=sin(t)+2*cos(t) trigsimp(f) #Returns sin(t)+2*cos(t) simplify(f) #Returns sin(t)+2*cos(t) f.rewrite(sin) #Returns sin(t)+2*sin(t+Pi/2) PS.: I dont have direct access to a,b and w. Only to f Any suggestion?
upvote count: 2
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50590124
score: 1

http://stackoverflow.com/comment/88388606
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50689328
type: QuestionComment
has text: You could also call the serializer directly from views.py

http://stackoverflow.com/a/50551589
score: 0
type: Answer
has body: You can use the canny edge detector. For to detect the corner of the image.I have given you the link of 2 sources below. Source1 Source2 Code: import cv2 import matplotlib.pyplot as plt im = cv2.imread('boat.png') edges = cv2.Canny(im,25,255,L2gradient=False) plt.imshow(edges,cmap='gray') plt.show()
answers question: http://stackoverflow.com/q/50551439

http://stackoverflow.com/q/50650983
has comment: http://stackoverflow.com/comment/88313569
has comment: http://stackoverflow.com/comment/88312919
linked to: http://stackoverflow.com/q/8265061
linked to: http://stackoverflow.com/q/21978115
type: Question
has comment: http://stackoverflow.com/comment/88312847
has comment: http://stackoverflow.com/comment/88313255
has comment: http://stackoverflow.com/comment/88312903
has title: Is it possible to speed up a web scraper with multiple computers?
has comment: http://stackoverflow.com/comment/88312857
has comment: http://stackoverflow.com/comment/88313357
favorite count: 0
has comment: http://stackoverflow.com/comment/88312993
has comment: http://stackoverflow.com/comment/88312945
score: 0
has comment: http://stackoverflow.com/comment/88313034
has comment: http://stackoverflow.com/comment/88313041
has comment: http://stackoverflow.com/comment/88312931
has comment: http://stackoverflow.com/comment/88313151
tagged with: python-3.x
answer count: 0
tagged with: grequests
linked to: http://stackoverflow.com/q/46205491
type: UnansweredQuestion
tagged with: web-scraping
upvote count: 1
tagged with: python
tagged with: python-requests
has comment: http://stackoverflow.com/comment/88313188
downvote count: 1
has comment: http://stackoverflow.com/comment/88313525
has comment: http://stackoverflow.com/comment/88313036
has body: Is there any way to speed up a web-scraper by having multiple computers contribute to processing a list of urls? Like computer A takes urls 1 - 500 and computer B takes urls 501 - 1000, etc. I am looking for a way to build the fastest possible web scraper with resources available to everyday people. I am already using multiprocessing from the grequests module. Which is gevent + request combined. This scraping does not need to be run constantly, but at a specific time each day in the morning (6 A.M.), and be done near as soon as it starts. I am looking for something quick and punctual. Also I am looking through urls for retail stores (i.e.: target, bestbuy, newegg, etc), and using it to check what items are in stock for the day. This is a code segment for grabbing those urls in the script I'm trying to put together: import datetime import grequests thread_number = 20 nnn = int(len(product_number_list)/100) float_nnn = (len(product_number_list)/100) # Product number list is a list of product numbers, too big for me to include the full list. Here are like three: product_number_list = ['N82E16820232476', 'N82E16820233852', 'N82E16820313777'] base_url = 'https://www.newegg.com/Product/Product.aspx?Item={}' url_list = [] for number in product_number_list: url_list.append(base_url.format(product_number_list)) # The above three lines create a list of urls. results = [] appended_number = 0 for x in range(0, len(product_number_list), thread_number): attempts = 0 while attempts < 10: try: rs = (grequests.get(url, stream=False) for url in url_list[x:x+thread_number]) reqs = grequests.map(rs, stream=False, size=20) append = 'yes' for i in reqs: if i.status_code != 200: append = 'no' print('Bad Status Code. Nothing Appended.') attempts += 1 break if append == 'yes': appended_number += 1 results.extend(reqs) break except: print('Something went Wrong. Try Section Failed.') attempts += 1 time.sleep(5) if appended_number % nnn == 0: now = datetime.datetime.today() print(str(int(20*ap…
has comment: http://stackoverflow.com/comment/88313104
has comment: http://stackoverflow.com/comment/88313053
has comment: http://stackoverflow.com/comment/88313216

http://stackoverflow.com/q/50672579
upvote count: 3
has comment: http://stackoverflow.com/comment/88354934
type: Question
answer count: 2
tagged with: for-loop
downvote count: 0
accepted answer: http://stackoverflow.com/a/50672725
score: 3
has body: When I loop thru a matrix to get the diagonals: a = [[11, 2, 4], [4, 5, 6], [10, 8, -12]] i = 0 o = 0 for a[i] in a: d1 = a[i][o] o += 1 print(d1) the output is like expected 11, 5, -12, but when I print out the matrix again: print(a) the matrix changed [[10, 8, -12], [4, 5, 6], [10, 8, -12]] the first row is no more like it was [11, 2, 4]. I can't figure out why is that happening.
has answer: http://stackoverflow.com/a/50672622
favorite count: 0
has title: Why does the square matrix change when I loop through it?
tagged with: nested-lists
possible better answer: http://stackoverflow.com/a/50672622
tagged with: python
has answer: http://stackoverflow.com/a/50672725
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/comment/88307049
has text: Maybe you are reading file in a wrong way? check encodings..
score: 0
comment on: http://stackoverflow.com/q/50648114
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50547464
has title: Assign a Row to Data Frame Header that Starts with a Specific String from Excel- Pandas
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: I have many excel files that are in different formats. Some of them look like this, which is normal with one header can be read into pandas. # First Column Second Column Address City State Zip 1 House The Clairs 4321 Main Street Chicago IL 54872 2 Restaurant The Monks 6323 East Wing Miluakee WI 45458 and some of them are in various formats with multiple headers, Table 1 Comp ID Info # First Column Second Column Address City State Zip 1 Office The Fairs 1234 Main Street Seattle WA 54872 2 College The Blanks 4523 West Street Madison WI 45875 3 Ground The Brewers 895 Toronto Street Madrid IA 56487 Table2 Comp ID Info # First Column Second Column Address City State Zip 1 College The Banks 568 Old Street Cleveland OH 52125 2 Professional The Circuits 695 New Street Boston MA 36521 This looks like this in Excel (I am pasting the image here to show how it actually looks in excel), As you can see above there are three different levels of headers. For sure every file has a row that starts with First Column. For an individual file like this, I can read like below, which is just fine. xls = pd.ExcelFile(r'mypath\myfile.xlsx') df = pd.read_excel('xls', 'mysheet', header=[2]) However, I need a final data frame like this (Appended with files that have only one header), First Column Second Column Address City State Zip 0 House The Clair 4321 Main Street Chicago IL 54872 1 Restaurant The Monks 6323 East Wing Milwaukee WI 45458 2 Office The Fairs 1234 Main Street Seattle WA 54872 3 College The Blanks 4523 West Street Madison WI 45875 4 Ground The Brewers 895 Toronto Street Madrid IA 56487 5 College The Banks 568 Old Street Cleveland OH 52125 6 Professional The Circuits 695 New Street Boston MA 36521 Since I have many files, I want to read each file in my folder and clean them up by getting only one header from a row. Had I knew the index position of the row, that I need as head, I could simply do something like in this post. However, as some of those files can have Multiple headers …
score: 1
type: Question
has comment: http://stackoverflow.com/comment/88106359
upvote count: 1
downvote count: 0
tagged with: header
favorite count: 0
linked to: http://stackoverflow.com/q/26147180
tagged with: pandas

http://stackoverflow.com/a/50677533
downvote count: 1
has comment: http://stackoverflow.com/comment/88364536
type: Answer
upvote count: 0
has body: df['Value'].apply(lambda x:float(x))
has comment: http://stackoverflow.com/comment/88364527
score: -1
answers question: http://stackoverflow.com/q/50677372

http://stackoverflow.com/comment/88228131
type: Comment
score: 0
type: AnswerComment
has text: This is absolutely perfect! Exactly what I needed to do. Thanks a lot for that. Is there any good read or some samples for this you showed me? You said using `sets()` ?
comment on: http://stackoverflow.com/a/50608938

http://stackoverflow.com/q/50572004
accepted answer: http://stackoverflow.com/a/50572051
favorite count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/88156890
has title: How round (395,-2) works in python 3?
tagged with: python-3.x
upvote count: 2
score: 0
downvote count: 2
has answer: http://stackoverflow.com/a/50572048
tagged with: python
has comment: http://stackoverflow.com/comment/88153603
has answer: http://stackoverflow.com/a/50572051
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50572048
has comment: http://stackoverflow.com/comment/88153621
type: Question
has answer: http://stackoverflow.com/a/50572113
has body: I executed round(395,-2) and it returned 400 as a output.How this thing worked.?

http://stackoverflow.com/comment/88404465
score: 0
has text: It was hard for me, to understand [docs](https://docs.python.org/3/library/typing.html#typing.TypeVar). But now everything clear! Will read it again.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50697467

http://stackoverflow.com/comment/88316869
type: Comment
comment on: http://stackoverflow.com/a/50653144
score: 0
has text: The school's network issues actual DNS-resolvable addresses, so that's some really good work on the part of their network team. Most internal networks don't. You just get something like `192.168.2.11` and deal with it through NAT. You may be on a different network, or your configuration is overriding the name assignment. Windows, Linux and macOS handle this differently.
type: AnswerComment

http://stackoverflow.com/comment/88181734
has text: @jpp Thank you for getting back to me so quickly. When I try adding [0] I get "KeyError: 0". Update: If I take the drop_duplicates out your suggestion works perfectly, thank you again!
type: AnswerComment
comment on: http://stackoverflow.com/a/50578985
score: 0
type: Comment

http://stackoverflow.com/q/50616031
has title: Python taking arguments
has answer: http://stackoverflow.com/a/50616084
has comment: http://stackoverflow.com/comment/88242220
tagged with: file-io
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50616084
has comment: http://stackoverflow.com/comment/88241980
has comment: http://stackoverflow.com/comment/88242096
type: Question
tagged with: sys
has body: I am trying to deal with optional command line input files, and based on whether or not there is a file to read in, set values to either what is in the file or default values. How do I set up Python to check to see if there is an argument to take in from command line? I have what is below, but the problem is is when I run my program with "python myPythonScript.py", it still evaluates as if there is a file to read in, when I never piped in a file. import sys value1 = 0 value2 = 0 if len(sys.argv) &gt;= 1): with open("test.txt", "r") as f: //file opens here and I take the contents and set values 1 and 2 //based on the input else: //values are set to default values that I define here
tagged with: python
answer count: 1
score: 0

http://stackoverflow.com/comment/88401616
score: 2
comment on: http://stackoverflow.com/a/50696141
type: AnswerComment
has text: @Nakajima https://stackoverflow.com/questions/533631/what-is-a-mixin-and-why-are-they-useful
type: Comment

http://stackoverflow.com/comment/88243430
comment on: http://stackoverflow.com/q/50614109
score: 0
type: Comment
has text: @jasonharper would I be needing 2 python scripts for this to work, then? One for the actual code I want to execute and one for this?
type: QuestionComment

http://stackoverflow.com/comment/88136725
comment on: http://stackoverflow.com/q/50563064
has text: How is `aaaa = Result1`? Could you explain your output? How is this output related to sqlite db table?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50607992
answers question: http://stackoverflow.com/q/50607534
has body: Your date and time are separated by a comma, which you are splitting on, so you are getting incorrect results. You should pre-format your file to remove that first comma: data = [] with open('test.txt') as f: for line in f: data.append(line.replace(',', ' ', 1)) with open('test.txt', 'w') as outf: outf.write(''.join(data)) # 2018.05.01 01:15,1.206870,1.206920,1.206870,1.206920,0 # 2018.05.01 01:16,1.206910,1.206910,1.206810,1.206820,0 Make sure you only run this once or else more commas will be removed. Which can then easily be parsed into a time using pandas (which you're already using): df = pd.read_csv('test.txt', header=None) pd.to_datetime(df[0]) 0 2018-05-01 01:15:00 1 2018-05-01 01:16:00 Name: 0, dtype: datetime64[ns]
score: 0
type: Answer

http://stackoverflow.com/comment/88311344
type: Comment
type: QuestionComment
has text: My exact problem.
comment on: http://stackoverflow.com/q/50623935
score: 0

http://stackoverflow.com/a/50691641
has comment: http://stackoverflow.com/comment/88418951
accepted answer of: http://stackoverflow.com/q/50691577
has body: You'll want to use enumerate to get the index in order to set the value in the list to zero: for i, x in enumerate(df[col1]): matches = [j for j, y in enumerate(df[col2].isin([x])) if y is True] if len(matches) == 0: continue df[col1][i] = 0 k = matches[0] df[col2][k] = 0 If an element in df[col1] appears in df[col2] multiple times, this will only set the first occurrence to 0. If you want to remove all occurrences, you could use this code: for i, x in enumerate(df[col1]): matches = [j for j, y in enumerate(df[col2].isin([x])) if y is True] if len(matches) == 0: continue df[col1][i] = 0 for k in matches: df[col2][k] = 0
has comment: http://stackoverflow.com/comment/88419107
has comment: http://stackoverflow.com/comment/88394740
answers question: http://stackoverflow.com/q/50691577
has comment: http://stackoverflow.com/comment/88419173
has comment: http://stackoverflow.com/comment/88394674
has comment: http://stackoverflow.com/comment/88418879
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88393173
type: Answer
has comment: http://stackoverflow.com/comment/88419283
has comment: http://stackoverflow.com/comment/88393180
has comment: http://stackoverflow.com/comment/88393496
downvote count: 0
score: 1

http://stackoverflow.com/q/50613156
has comment: http://stackoverflow.com/comment/88236446
tagged with: dataframe
has answer: http://stackoverflow.com/a/50614547
answer count: 2
tagged with: pandas
has title: Save skip rows in pandas read csv
favorite count: 0
has comment: http://stackoverflow.com/comment/88236289
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/50613233
accepted answer: http://stackoverflow.com/a/50613233
possible better answer: http://stackoverflow.com/a/50614547
upvote count: 3
has body: I have a list of skip rows ( say [1,5,10] --> row numbers) and when I passed this to pandas read_csv, it ignores those rows. But, I need to save these skipped rows in a different text file. I went through pandas read_csv documentation and few other articles, but have no idea how to save this into a text file. Example : Input file : a,b,c # Some Junk to Skip 1 4,5,6 # Some junk to skip 2 9,20,9 2,3,4 5,6,7 Code : skiprows = [1,3] df = pandas.read_csv(file, skip_rows = skiprows) Now output.txt : # Some junk to skip 1 # Some junk to skip 2 Thanks in advance!
downvote count: 1
type: Question
tagged with: numpy

http://stackoverflow.com/a/50673596
upvote count: 0
answers question: http://stackoverflow.com/q/50673501
type: Answer
has body: for row in yyy: if yyy &gt; y1: plt.scatter(xxx, yyy, c='r') else: plt.scatter(xxx, yyy, c='b') Needs to look like that
downvote count: 1
score: -1

http://stackoverflow.com/q/50671524
upvote count: 5
has body: I have an array of tuples: a = [(375, 193) (364, 113) (277, 20) (271, 16) (52, 106) (133, 266) (289, 296) (372, 282)] How to draw lines between points in OpenCV? Here is my code that isn't working: for index, item in enumerate(a): print (item[index]) #cv2.line(image, item[index], item[index + 1], [0, 255, 0], 2)
has comment: http://stackoverflow.com/comment/88353329
has comment: http://stackoverflow.com/comment/88353372
score: 4
has comment: http://stackoverflow.com/comment/88353249
has answer: http://stackoverflow.com/a/50671901
answer count: 2
has answer: http://stackoverflow.com/a/50672796
tagged with: contour
linked to: http://stackoverflow.com/q/66923488
accepted answer: http://stackoverflow.com/a/50671901
favorite count: 0
possible better answer: http://stackoverflow.com/a/50672796
has comment: http://stackoverflow.com/comment/88352887
tagged with: python
has comment: http://stackoverflow.com/comment/88353407
type: AnsweredQuestion
has title: How to draw lines between points in OpenCV?
has comment: http://stackoverflow.com/comment/88352876
downvote count: 1
type: Question
tagged with: opencv

http://stackoverflow.com/a/50707477
has body: The Django model admin provides a special method for this: has_change_permission. In your case it would be something as: class PersonAdmin(admin.ModelAdmin): list_display = ["Name", "LastJob", "CurrentJob", "status"] list_editable = ["CurrentJob"] class Meta: model = Person def has_change_permission(request, obj=None): if obj: return obj.status != 'dead' admin.site.register(Person, PersonAdmin)
score: 0
answers question: http://stackoverflow.com/q/50696371
type: Answer

http://stackoverflow.com/comment/88170975
type: Comment
score: 0
type: AnswerComment
has text: And your calculation is correct, the last_traded_price column starts at 88th byte.
comment on: http://stackoverflow.com/a/50580254

http://stackoverflow.com/comment/88401492
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50659354
has text: I just found a new example that starts like "are small brain cells with a life-long division. The types of glial cells are astrocytes,". The above re takes everything but it would be better if it takes only the beginning of a new sentence so from "The types of glial cells are astrocytes," on. How could I modify the above expression to tell it to look for patterns that start with capital letter?

http://stackoverflow.com/a/50625174
has comment: http://stackoverflow.com/comment/88261057
accepted answer of: http://stackoverflow.com/q/50624596
has comment: http://stackoverflow.com/comment/88261454
has comment: http://stackoverflow.com/comment/88261761
answers question: http://stackoverflow.com/q/50624596
has comment: http://stackoverflow.com/comment/88263359
has comment: http://stackoverflow.com/comment/88300594
has comment: http://stackoverflow.com/comment/88260726
has comment: http://stackoverflow.com/comment/88261310
has comment: http://stackoverflow.com/comment/88264132
has comment: http://stackoverflow.com/comment/88260615
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88261633
has body: The misunderstanding doesn't come from K.max() or K.argmax(), but from tensor.eval(). Everytime you call tensor.eval(), you launch a new run through the graph, so everytime your pseudo-randomly defined tensors get populated with new values as their random seeds are also incremented (using seed=1 for tf.random_normal() doesn't fix the values, it fixes the sequence of pseudo-random values to be generated each run, see doc for details). In other words, xxx.eval(), aaa.eval() and bbb.eval() give you the results for 3 different runs with 3 different random values below. If you evaluate xxx, aaa and bbb all at once in a single run (test_a.run([xxx, aaa, bbb])), you will get the results you were expecting. with tf.Session() as test_a: box_confidence = tf.random_normal([3, 4, 5, 1], mean=1, stddev=4, seed=1) boxes = tf.random_normal([3,4, 5, 4], mean=1, stddev=4, seed=1) box_class_probs = tf.random_normal([3, 4, 5, 3], mean=1, stddev=4, seed=1) # note: `seed=1` fixes the seed value and thus the sequence of pseudo-random values. # the PSNR will still yield new values each run, only in a predefined manner. xxx = box_confidence * box_class_probs aaa = K.argmax(xxx, axis=-1) bbb = K.max(xxx, axis=-1, keepdims=False) # First run: res_xxx, res_aaa, res_bbb = test_a.run([xxx, aaa, bbb]) print(res_aaa[0, 0]) # &gt; [0 2 0 2 0] # ^ the result you were expecting # Second run: res_xxx, res_aaa, res_bbb = test_a.run([xxx, aaa, bbb]) print(res_aaa[0, 0]) # &gt; [1 1 1 2 1] # ^ new result, as new pseudo-random values have been picked inside, # from the sequence predefined by the seeds.
has comment: http://stackoverflow.com/comment/88263141
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/88261804
has comment: http://stackoverflow.com/comment/88262103
has comment: http://stackoverflow.com/comment/88264671
upvote count: 1
has comment: http://stackoverflow.com/comment/88261263
has comment: http://stackoverflow.com/comment/88262505

http://stackoverflow.com/a/58243297
type: Answer
has body: For smaller sample sizes I find that the python 3.6 function, random.choices, is faster. In the script below, the break-even is at a sample size of 99, and random.choices becomes increasingly faster than 'numpy.random.choice' as the sample size decreases. With no weights, the break-even number is slightly higher at 120. However, for a population size of 1000, random.choices is about 3 times slower with weights, and 7 times slower without weights. import numpy as np import time import random SIZE = 98 def numpy_choice(): for count in range(10000): resampled_indices = np.random.choice(a=population_array, size=SIZE, replace=True, p=weights) return def python_choices(): for count in range(10000): resampled_indices = random.choices(population_list, weights=weights, k=SIZE) return if __name__ == '__main__': weights = [1/SIZE for i in range(SIZE)] population_array = np.arange(SIZE) population_list = list(population_array) start_time = time.time() numpy_choice() end_time = time.time() print('numpy.choice time:', end_time-start_time) # gave 0.299 start_time = time.time() python_choices() end_time = time.time() print('python random.choices time:', end_time-start_time) # gave 0.296
score: 0
answers question: http://stackoverflow.com/q/50548775

sphinx-napoleon
tag name: sphinx-napoleon
type: Tag
tags question: http://stackoverflow.com/q/50546154

http://stackoverflow.com/q/50684496
has title: Run tensorflow remotely on google cloud and then get back accuracy/predictions
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88378762
tagged with: neural-network
has answer: http://stackoverflow.com/a/50694887
score: 0
tagged with: google-cloud-platform
has answer: http://stackoverflow.com/a/68280996
tagged with: python-3.x
type: UnansweredQuestion
has body: I am trying to create a gui in python where the user choses training data, and then by pressing the train button trains a neural network.Then the user can get the test accuracy or use the model to predict something. The problem is that I cant train a neural network in my pc because of not enough gpu. I want to upload training files in Google Cloud and then run remotely a python script that trains a model in google cloud and and then gets back the training accuracy , or gives for example a picture in google cloud storage and runs something like predict.py remotely that predicts the label of the picture using the previously trained model (that I have saved for example in google cloud storage) So far I have found how to access google bucket from python remotely but I don't know how to run a python script remotely (for example using google.cloud lirbaries?) and then take back the output. Any ideas on how can that be done ? Thank you !
tagged with: python

http://stackoverflow.com/a/50590524
has comment: http://stackoverflow.com/comment/88190655
score: 2
has comment: http://stackoverflow.com/comment/88190556
upvote count: 2
answers question: http://stackoverflow.com/q/50590449
has body: you can try (as user abarnert also points out) a = 10 b, a = -a, a+1 to write it in 1 line. and the code is much more clear in its intent
has comment: http://stackoverflow.com/comment/88190828
downvote count: 0
type: Answer

http://stackoverflow.com/comment/129090862
has text: Thank you! Only this helped me. I use: pytesseract, jupyter notebook, conda env with only ipykernel installed (jupyter not installed in this env), ubuntu.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/56605161
type: AnswerComment

http://stackoverflow.com/comment/88119909
comment on: http://stackoverflow.com/q/50554405
has text: @RoryDaulton done
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88112441
has text: As @Aran-Fey mentioned: add a minimal working example. What is `y`? Where is it defined? Very difficult to answer the question in its current form.
score: 0
comment on: http://stackoverflow.com/q/50550643
type: Comment
type: QuestionComment

dicom
tag name: dicom
type: Tag
tags question: http://stackoverflow.com/q/50649726
tags question: http://stackoverflow.com/q/50685384

http://stackoverflow.com/comment/88349481
has text: What is siteTest ?
comment on: http://stackoverflow.com/q/50669307
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50676733
has title: Python : Compare CSV files and save the difference with first row(Column Names)
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/50676813
type: AnsweredQuestion
tagged with: pycharm
has body: I have two CSV files as shown below: File 1: June_01_2018.csv File 2: June_02_2018.csv Note: I want to find the difference between these two file and store it into the third file with the column headers. My try: with open('June_01_2018.csv', 'r') as f1: file1 = f1.readlines() with open('June_02_2018.csv', 'r') as f2: file2 = f2.readlines() with open('June_Updates.csv', 'w') as outFile: for line in file2: if line not in file1: outFile.write(line) But unable to store the column headers into the third file.
type: Question
linked to: http://stackoverflow.com/q/9932278
score: 0
has answer: http://stackoverflow.com/a/50676813
answer count: 1

http://stackoverflow.com/a/50687267
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50683637
has body: To display the href, the title and the span text, you could do the following: import bs4 as bs html = 'title text' soup = bs.BeautifulSoup(html, 'lxml') for link in soup.findAll('a', class_='js-pop', href=True, title=True): print(link['href']) print(link['title']) print(link.text) This would display: VIDEO HREF title title text By adding href=True and title=True, it tells the find to only return elements which actually contain both of those attributes.
type: Answer
accepted answer of: http://stackoverflow.com/q/50683637
upvote count: 1

http://stackoverflow.com/a/50629465
downvote count: 0
has body: python (added cat without a known size) from flask import Flask, render_template, request app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): cats = [{'name': 'fluffy', 'size': 'big'}, {'name': 'smelly', 'size': 'small'}, {'name': 'Mr Meow', 'size': None}] if request.method == 'GET': return render_template('test.html', cats=cats) elif request.method == 'POST': return "thanks" if __name__ == "__main__": app.run(debug=True, host="0.0.0.0") js: {% for cat in cats %} {{ cat['name'] }} {% endfor %} So the trick is to have a event listener in your select menu, which is executed when your cat is changed. Afterwards, it will look up the size of the selected cat, and then update the input with the size of the selected cat. If the size is None, it sets the size to an empty string. The function is also executed when loading the page, so it will also load the first cat in the select box. It's a bit ugly, because a python None is not really conferted to a javascript null, but it will do the job. For jquery, change the code to: function changeSizeInput() { var size = $('#catSelect option:selected').attr('size') if (size == 'None') { size = '' } $('#catSize').val(size); } changeSizeInput()
answers question: http://stackoverflow.com/q/50628302
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50628302
type: AcceptedAnswer

http://stackoverflow.com/comment/88115086
has text: In the `groupby` operation, for each group, a new dataframe is created with all the combinations of writers. If there are 10 combinations, for example, the new dataframe will have index `[0,...,9]`. After the function is applied across the whole dataframe, the final output has a multi-index consisting of both the song names and the per-group integer indexes. `drop('level_1', axis=1)` just drops the per-group integer indexes, because they aren't important to us and what we really care about is the song names.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50551495
type: AnswerComment

http://stackoverflow.com/q/50678758
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/50975064
tagged with: django
has body: I have Django with Django Cachalot and I need know what is cached with cachalot in my server? I want to use CACHALOT_UNCACHABLE_TABLES parameter and I need to know if this works and certain tables are not cached. I hope that somebody can help me, thank you. I initialized the parameter like this: CACHALOT_UNCACHABLE_TABLES = frozenset(('django_migrations', 'company_company', 'customers_customer, 'auth_user'))
tagged with: python
type: AnsweredQuestion
upvote count: 2
type: Question
has answer: http://stackoverflow.com/a/50975064
tagged with: caching
has title: How can I know what is cached with django cachalot on my server?
score: 2

http://stackoverflow.com/q/50616680
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50616822
has body: I'm using a simple two layer network, and instead of it being densely connected I wanted to "kill" 70% of the connections. In my researches on the subject, i was told to multiply the weights variable by an array of zeros and ones, but how can i know that these weights aren't going to be updated, even if they where initially zero?
accepted answer: http://stackoverflow.com/a/50616822
tagged with: tensorflow
type: Question
has title: How to stop using weights on a tensorflow network?
tagged with: neural-network
has comment: http://stackoverflow.com/comment/88243168
score: 0
answer count: 1

http://stackoverflow.com/a/50577309
score: 0
answers question: http://stackoverflow.com/q/50576803
type: Answer
has comment: http://stackoverflow.com/comment/88164503
has body: I'm pretty sure you should be using input_shape=(None,None,None,3) instead of input_shape=Input(shape = (None,None,None,3)) Also, you cannot use any function that demands the presence of data in the call method. You're using K.shape and K.eval, both will bring you errors in compilation. If you need information about the input shape, you have to do it in the def build(self, input_shape): method.
has comment: http://stackoverflow.com/comment/88175105

http://stackoverflow.com/a/50642573
has body: This is called a namespace and is supposed to be in front. You can simply remove the namespace by splitting your string at {}
has comment: http://stackoverflow.com/comment/88299925
has comment: http://stackoverflow.com/comment/88299548
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50641625
score: 1
upvote count: 1

http://stackoverflow.com/comment/88211328
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50600841
has text: try this `''.join([str for group in my_list for str in group])`
score: 0

http://stackoverflow.com/q/50630877
tagged with: python
has comment: http://stackoverflow.com/comment/88271856
has title: Unable to use modify_account with pjsua
has comment: http://stackoverflow.com/comment/88567593
answer count: 0
type: Question
has body: I am attempting to create an account using pjsua and then modify that account, but it complains that an integer is required even when I use an integer. Here is my test code: lib = pj.Lib() lib.init() lib.create_transport(pj.TransportType.UDP, pj.TransportConfig(0)) lib.create_account(pj.AccountConfig('127.0.0.1', '1234')) mailbox = 5678 lib.modify_account('acc.info().uri', pj.AccountConfig('127.0.0.1', '%d' % int(mailbox))) Here is the error: Traceback (most recent call last): File ./test.py, line 29, in lib.modify_account('acc.info().uri', pj.AccountConfig('127.0.0.1', '%d' % int(mailbox))) File /usr/local/lib/python2.7/dist-packages/pjsua.py, line 2354, in modify_account err = _pjsua.acc_modify(acc_id, acc_config._cvt_to_pjsua()) TypeError: an integer is required Exception AttributeError: "'NoneType' object has no attribute 'destroy'" in > ignored
score: 0
tagged with: pjsip
type: UnansweredQuestion

http://stackoverflow.com/comment/88385720
comment on: http://stackoverflow.com/q/50687892
has text: I would suggest not including the file operations in the question as it is irrelevant. The question should be simplified to use `start_string = "whatever"` instead of loading it from a file. It would also be easier for you and us to test it that way.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88221240
type: Comment
has text: In your case (and most cases), the line `sum += digit ** power` is equivalent to `sum = sum + digit ** power`.
type: QuestionComment
comment on: http://stackoverflow.com/q/50605865
score: 4

http://stackoverflow.com/a/50659514
has comment: http://stackoverflow.com/comment/88430367
type: AcceptedAnswer
score: 0
answers question: http://stackoverflow.com/q/50654531
type: Answer
has comment: http://stackoverflow.com/comment/88430029
has comment: http://stackoverflow.com/comment/88430217
has comment: http://stackoverflow.com/comment/88430876
has comment: http://stackoverflow.com/comment/88429353
has body: All you need is just a groupby() and then probably a list of excluded/included unique items in column 'D': df = pd.DataFrame(data=d) df['C'] = pd.to_timedelta(df['C'], errors="coerce").dt.total_seconds() places = ['Home','Away','Shops'] for d, dfg in df[df['D'].isin(places)].groupby('D'): # print out the processing place print('group:{}\n{}'.format(d, dfg)) # do whatever you want on `dfg` and `d` # In your example, when d is 'Home', dfg is df.loc[df['D'] == 'Home'] # below your code, just change `df` to `dfg` #Return start-stop times Stop = dfg.loc[df['B'] == 'Stop'].reset_index()['C'] Start = dfg.loc[df['B'] == 'Start'].reset_index()['C'] Res = dfg.loc[df['B'] == 'Res'].reset_index()['C'] #return difference Start_diff = Start - Stop Res_diff = Res - Start
has comment: http://stackoverflow.com/comment/88429725
accepted answer of: http://stackoverflow.com/q/50654531

http://stackoverflow.com/a/50544803
has body: For both conditions to be true if condition1 and condition2: For one of the conditions to be true if condition1 or condition2:
score: 1
upvote count: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/50544763

http://stackoverflow.com/comment/88333573
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50661107
score: 3
has text: PyLint in this case is just wrong. `cv2` does indeed have a function `CascadeClassifier`, I just checked. IDLE knows about it, even if PyLint doesn't. This appears to be a known problem: for example https://stackoverflow.com/questions/31907762/pylint-to-show-only-warnings-and-errors

dragonboard
tag name: dragonboard
tags question: http://stackoverflow.com/q/50560161
type: Tag

http://stackoverflow.com/comment/88249072
type: AnswerComment
score: 0
has text: Thanks for the help. Sad that SO doesn't mention age along with the name.:)
type: Comment
comment on: http://stackoverflow.com/a/50619142

http://stackoverflow.com/comment/88231607
score: 2
comment on: http://stackoverflow.com/q/50610838
has text: What are you expecting this code to do? What it actually does is `((sv != 0.000002)) and 0.00003) and 0.00004 …`, so in the end, the result will be False if `sv == 0.000002`, and `0.0000003` otherwise.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88366219
has text: All of the codes you tried worked for me
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50678319

http://stackoverflow.com/q/50575665
has title: Trying to convert to numbers with try except
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50575677
answer count: 5
tagged with: python
has body: I'm trying to convert the items in a list of multiple types to floats, so that L = ["29.3", "tea", "1", None, 3.14] would become D = [29.3, "tea", 1, None, 3.14] My attempt is as follows: L = ["29.3", "tea", "1", None, 3.14] D = [] for item in L: try: float(item) D.append(item) except ValueError: D.append(item) print(D) This throws up a line 5, in &lt;module&gt; float(item) TypeError: float() argument must be a string or a number, not 'NoneType'` error. If I change the None item to a string as in "None", it generates a list D identical to L. So... How do I skip over the None item? Do I have to use an if item == None: pass statement, or is there a better way? Why is the type conversion not working even if I change None to "None"?
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/88160574
has answer: http://stackoverflow.com/a/50575756
accepted answer: http://stackoverflow.com/a/50575756
has comment: http://stackoverflow.com/comment/88160505
has answer: http://stackoverflow.com/a/50575809
type: Question
has answer: http://stackoverflow.com/a/50575677
has answer: http://stackoverflow.com/a/50575773
score: -1
tagged with: type-conversion
has answer: http://stackoverflow.com/a/50575772
tagged with: try-except
tagged with: types
downvote count: 1

http://stackoverflow.com/comment/88344838
has text: The date I wrote was taken from the database and this is what I get when I print the date of the first article in django shell : datetime.datetime(2018,5,21,11,12,3,868542,tzinfo=(UTC))
type: Comment
comment on: http://stackoverflow.com/a/50667339
score: 0
type: AnswerComment

http://stackoverflow.com/a/78530135
score: 0
has body: try: from tkinter import * root = Tk() root.geometry("100x100") my_frame = Frame(root) some_label = Label(my_frame,text="some text") some_label.pack() my_frame['borderwidth'] = 5 my_frame['relief'] = 'solid' my_frame.pack() root.mainloop() more info: frame tkinter tutorial
type: Answer
answers question: http://stackoverflow.com/q/50691267

http://stackoverflow.com/comment/88400366
type: Comment
has text: Makes sense. But if the machine can really turn around several times in a 400 second window (6.6 minutes), then reduce the window to e.g. 10 samples. You can also take a moving average, not disjoint slices, so that you have more data points but less jiggle between them.
comment on: http://stackoverflow.com/a/50681035
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88239913
type: Comment
has text: I think it is something OP should clarify, I understood it in the other way as " if a file exists in folder2 then don't read the file". In any case I will modify the code then It will work either way.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50614910

hough-transform
tags question: http://stackoverflow.com/q/50616986
tag name: hough-transform
type: Tag

http://stackoverflow.com/a/50689688
has comment: http://stackoverflow.com/comment/88392862
has comment: http://stackoverflow.com/comment/88390810
type: Answer
has comment: http://stackoverflow.com/comment/88390700
has body: Yes, that is expected. The first thing you must be aware of: dot-product is the working horse of the numpy-version, here for slightly smaller arrays: &gt;&gt;&gt; def only_dot(x1, x2): return - 2*np.dot(x1, x2.T) &gt;&gt;&gt; a = np.zeros((1000,512), dtype=np.float32) &gt;&gt;&gt; b = np.zeros((100, 512), dtype=np.float32) &gt;&gt;&gt; %timeit(euclidean_distance_square_einsum(a,b)) 6.08 ms ± 312 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) &gt;&gt;&gt; %timeit(euclidean_only_dot(a,b)) 5.25 ms ± 330 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) i.e. 85% of the time are spent in it. When you look at your numba-code, that looks like a somewhat strange/unusual/more complicated version of matrix-matrix-multiplication - one could see for example the same three loops. So basically, you are trying to beat one of the best optimized algorithms out there. Here is for example somebody trying to do it and failing. My installation uses Intel's MKL-version, which must be more sophisticated than the default-implementation, which can be found here. Sometimes, after the whole fun one had, one has to admit that the own "reinvented wheel" is not as good as the state-of-the-art wheel... but only then one can truly appreciate its performance.
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/88392766
downvote count: 0
answers question: http://stackoverflow.com/q/50675705

http://stackoverflow.com/comment/88336795
score: 0
has text: looks like this : 2016-10-07 09:19:00
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50663334

http://stackoverflow.com/comment/88263520
score: 0
type: Comment
has text: `if not skip` just checks if `skip` is equal to 0 or not, and if it is, prints the line otherwise skips the line
comment on: http://stackoverflow.com/a/50625892
type: AnswerComment

http://stackoverflow.com/a/50584045
type: Answer
downvote count: 0
score: 6
has body: If you dynamically generate variable names, you don't know what names exist, and you can't use them in code. globals()[some_unknown_name] = Foo() Well, now what? You can't safely do this: eric.bar() Because you don't know whether eric exists. You'll end up having to test for eric's existence using dictionaries/lists anyway: if 'eric' in globals(): ... So just store your objects in a dictionary or list to begin with: people = {} people['eric'] = Foo() This way you can also safely iterate one data structure to access all your grouped objects without needing to sort them from other global variables.
accepted answer of: http://stackoverflow.com/q/50583955
answers question: http://stackoverflow.com/q/50583955
has comment: http://stackoverflow.com/comment/88177598
type: AcceptedAnswer
upvote count: 6

http://stackoverflow.com/comment/88132706
comment on: http://stackoverflow.com/q/50561040
has text: It is installed by `pillow` but imported by `PIL`.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/50633408
type: Question
upvote count: 0
score: -2
answer count: 1
tagged with: neural-network
has title: Striding a 2D model over an image to produce image of labels (NOT convolution)
favorite count: 0
accepted answer: http://stackoverflow.com/a/50634134
tagged with: python
downvote count: 2
has body: I have a model trained from RGB image samples that take a 31x31 pixel region as input and produces a single classification for the center pixel. I'd like to apply this model over an entire image to recover effectively a new image of classifications for each pixel. Since this isn't a convolution, I'm not sure what the preferred way to do this is in TensorFlow. I know this is possible by exploding the image for inference into a ton of smaller tensors but this seems like a colossal waste since each pixel will be duplicated 961 times. Is there a way around this?
tagged with: machine-learning
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88277694
has answer: http://stackoverflow.com/a/50634134
tagged with: tensorflow

http://stackoverflow.com/comment/88111679
type: AnswerComment
has text: But we can send texts to phone numbers which are not saved using the above WhatsApp API. It's ok leave it. We will find another way
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50549922

http://stackoverflow.com/a/50679354
type: Answer
has body: The @receiver(Signal,...) decorator is a shortcut for Signal.connect(...), so you indeed register your create_new_patient handler twice (once thru @receiver when importing your signals module, the second time with pre_save.connect(). Solution : in your App.ready() method, you should just import your app's signal.py module. This will trigger the registration of the handlers decorated with @receiver.
upvote count: 1
has comment: http://stackoverflow.com/comment/88368196
answers question: http://stackoverflow.com/q/50678954
score: 1
has comment: http://stackoverflow.com/comment/88369244
downvote count: 0

http://stackoverflow.com/comment/91806471
type: AnswerComment
comment on: http://stackoverflow.com/a/51002659
has text: How do your steps show how "you can install pipenv within a conda environment initialized with Python 3"? That seems to imply running something like `pip install pipenv` within the environment, but your instructions assume pipenv is already available after activation.
type: Comment
score: 5

http://stackoverflow.com/a/50600441
accepted answer of: http://stackoverflow.com/q/50598432
type: AcceptedAnswer
has body: mongo.db.collectionsNames.find() returns a cursor: print(mongo.db.collectionsNames.find()) gives &lt;pymongo.cursor.Cursor object at 0x7fd3854d5710&gt;. To make it easy (but kind of wrong) a cursor is a specific kind of instance that fetch data from the database chunk by chunk so if you want the 1 000 000 first items in db you don't actually store 1M items in RAM, you iterate 100 by 100 items (for example). Cursor handle that in a magic way. Whatever, you cannot loop several time on the same cursor and you should never caste a cursor to list like list(cursor_instance) (because if your query ask for 1M product, doing this add all these products in RAM). So, now, how can you handle this. Most of time I would say it's better to call the method when you need it, twice if needed. But here you are in a Jinja environment and if I'm right calling methods within a Jinja template is impossible. A way to do that is to use properties. class LazyCollection(object): @property def collections_names(self): return mongo.db.collectionsNames.find() lazycoll = LazyCollection() return render_template('index.html', collectionsNames=lazycoll) Then, in your template: {% for asd in collectionsNames.collections_names %} &lt;p&gt;{{ asd.foo }}&lt;/p&gt; {% endfor %}
type: Answer
has comment: http://stackoverflow.com/comment/88211421
score: 0
has comment: http://stackoverflow.com/comment/88211589
answers question: http://stackoverflow.com/q/50598432

documentation
tags question: http://stackoverflow.com/q/50663920
tag name: documentation
type: Tag

http://stackoverflow.com/a/50565838
has body: Try adding the name and the float to a new dictionary the name as the key the float as the value then get the key that has the largest value: rank = {} u = ['river: 0.3'] v = ['spread: 0.04'] s = ['idaho: 0.5'] for i in u+v+s: rank[i.split(': ')[0]] = float(i.split(': ')[-1]) print("the largest value is {[0]}".format([i for i in rank.keys() if rank[i] == max(rank.values())])) Output: the largest value is idaho
score: 0
answers question: http://stackoverflow.com/q/50565371
type: Answer

http://stackoverflow.com/comment/88269405
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50629625
has text: What you were expecting isn’t “like a string”, it’s like four strings’ representations with spaces between them. Python will never insert `' '` into the middle of any object’s representation (unless you explicitly write a really weird `__repr__` method to force it to do so). And, again, the quotes aren’t actually part of each string, they’re part of its representation.
score: 1

http://stackoverflow.com/q/50554074
has comment: http://stackoverflow.com/comment/88119548
has body: I have tried for so long to try and install this properly but I can't get it to work, and I have looked around for help. So I have it 'installed' but when i try this import tensorflow I get this huge error Traceback (most recent call last): File "D:\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper fp, pathname, description = imp.find_module('_pywrap_tensorflow_internal', [dirname(__file__)]) File "D:\Python\lib\imp.py", line 297, in find_module raise ImportError(_ERR_MSG.format(name), name=name) ImportError: No module named '_pywrap_tensorflow_internal' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 41, in &lt;module&gt; from tensorflow.python.pywrap_tensorflow_internal import * File "D:\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in &lt;module&gt; _pywrap_tensorflow_internal = swig_import_helper() File "D:\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper import _pywrap_tensorflow_internal ImportError: No module named '_pywrap_tensorflow_internal' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\WHATEVERS\characters\sPEECHRECOG.py", line 1, in &lt;module&gt; import tensorflow File "D:\Python\lib\site-packages\tensorflow\__init__.py", line 24, in &lt;module&gt; from tensorflow.python import * File "D:\Python\lib\site-packages\tensorflow\python\__init__.py", line 49, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow File "D:\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 52, in &lt;module&gt; raise ImportError(msg) ImportError: Traceback (most recent call last): File "D:\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper fp, pat…
tagged with: tensorflow
type: Question
has title: Installing Tensorflow, not working
has answer: http://stackoverflow.com/a/50554449
linked to: http://stackoverflow.com/q/50430086
score: 0
has comment: http://stackoverflow.com/comment/88120799
answer count: 1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88119319
has comment: http://stackoverflow.com/comment/88122771
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/88187994
type: Comment
type: QuestionComment
has text: add your code here, don't link to it offsite
comment on: http://stackoverflow.com/q/50589295
score: 0

http://stackoverflow.com/q/50593150
has title: recurly - finding accounts
accepted answer: http://stackoverflow.com/a/50593395
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50593395
tagged with: python
tagged with: recurly
type: AnsweredQuestion
has body: I want to know how can I search for a particular account in my recurly system? I am using the latest python recurly module, 2.8.3... but I see no recurly method for searching/finding an account. I at first thought I could do: import recurly # {set key, subdomain, and default currency params here.} userAccount = recurly.Account(account_code="acc code") but this doesn't do anything, it just creates an empty recurly account object. Is there a search or find method for accounts? I am blind, and unfortunately https://dev.recurly.com/docs makes my web browser choke and often times it brings my computer to a huge lag, or locks up completely. and my pc is no slouch in the cpu/ram department. So I am having a difficult time reading the various python examples. I wish there was just a document for recurly via the python module. Thanks in advance...
type: Question

http://stackoverflow.com/a/50553439
upvote count: 3
answers question: http://stackoverflow.com/q/50553203
has comment: http://stackoverflow.com/comment/88118760
has comment: http://stackoverflow.com/comment/88119472
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50553203
type: Answer
has comment: http://stackoverflow.com/comment/88118350
has comment: http://stackoverflow.com/comment/88118886
has body: This looks to me to be a Correlated Subquery Relationship Hybrid. When Run.default_region is added as a filter, you want to update the query to add WHERE EXISTS ( SELECT 1 FROM tags WHERE run_id = runs.id AND name = "region" AND value = "default") Return that as an expression, with the exists() function: from sqlalchemy.sql import exists, and_ @default_region.expression def default_region(cls): return exists([1]).where(and_( Tag.run_id == cls.id, Tag.name == 'region', Tag.value == 'default')) Note that you want to avoid using == True or == False here, there is no need! Just use the property directly: session.query(Run).filter(Run.default_region).all() or use ~ to negate: session.query(Run).filter(~Run.default_region).all() By defining the .expression method for the property, you have told SQLAlchemy to use that method when accessing the property on the class, so the context is always the class there. Without defining .exists (or a .comparator), Run.default_region would call the default_region getter (the method decorated with `@hybrid_property) as a class method, so only then would that method have to then work with either an instance or a class being passed in. For some hybrid property implementations, that happens to work by virtue of how they use attributes on the context. As for the implementation of the default_region instance property, I'd not use reduce() there; use the any() function: @hybrid_property def default_region(self): return any( t.name == "region" and t.value == "default" for t in self.tag_collection) any() stops iterating over the supplied generator expression when a match has been found.
score: 3
has comment: http://stackoverflow.com/comment/88119194

http://stackoverflow.com/comment/88245246
type: AnswerComment
comment on: http://stackoverflow.com/a/50592082
type: Comment
has text: @Deloryn I extended the answer
score: 0

http://stackoverflow.com/q/50646878
downvote count: 0
type: Question
upvote count: 2
tagged with: data-manipulation
has body: I have a CSV file in (roughly) the following format: Day | Asset Allocation 0 | NYSE:100+++FTSE100:143+++DAX30:94 1 | NYSE:103+++FTSE97:143+++DAX30:95 2 | NYSE:102+++DAX30:97 3 | NYSE:102+++DAX30:97+++STOXX:102 So all assets are summarized in one column and separated by "+++". The order of the assets within the column can change as the CSV file progresses. I would like to rearrange the data to the following format: Day | NYSE | FTSE | DAX | STOXX 0 | 100 | 143 | 94 | 0 1 | 103 | 143 | 95 | 0 2 | 102 | 0 | 97 | 0 3 | 102 | 0 | 97 | 102 Preferably, I would like to be able to do it in Python, just because I do have some prior experience and might be able to find my way around more quickly. However, as the final dataset is likely to contain several million rows, I would of course be open to employ any other way that can handle the data more efficiently. I would greatly appreciate if someone could point me in the right direction. Thanks!
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
has answer: http://stackoverflow.com/a/50647997
accepted answer: http://stackoverflow.com/a/50647997
favorite count: 0
tagged with: python
has title: Extract column headers from cell and rearrange columns accordingly
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/88328009
comment on: http://stackoverflow.com/q/50658884
type: Comment
type: QuestionComment
has text: It's just a guess but I suspect numba is cancelling some of the speed advantage of numpy in this way. I don't know of any implementation of vectors and matrices that is faster than numpy
score: 0

http://stackoverflow.com/comment/88334925
score: 0
type: Comment
has text: What response do you get from the browser? 404 not found? 500 server error?
type: QuestionComment
comment on: http://stackoverflow.com/q/50662377

http://stackoverflow.com/a/50698166
answers question: http://stackoverflow.com/q/50698111
upvote count: 1
score: 1
has body: Using the csv module and enumerate. Ex: import csv data = [(789,255,25,33.0),(855,275,25,33.0)] with open(filename, "w") as outfile: writer = csv.writer(outfile) for i, line in enumerate(data, 1): writer.writerow([i]+ list(line)) Using Pandas import pandas as pd data = [(789,255,25,33.0),(855,275,25,33.0)] df = pd.DataFrame(data) df.to_csv(filename, header=None)
downvote count: 0
has comment: http://stackoverflow.com/comment/88410562
type: Answer

http://stackoverflow.com/q/50542608
accepted answer: http://stackoverflow.com/a/50543804
answer count: 1
has title: Importing own Python package from git
score: 0
has comment: http://stackoverflow.com/comment/88098600
has comment: http://stackoverflow.com/comment/88098427
tagged with: package
has answer: http://stackoverflow.com/a/50543804
tagged with: python
tagged with: git
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88098500
has body: I have the following python package created by myself: C:. │ .gitignore │ MANIFEST │ setup.py │ ├───.vscode │ │ settings.json │ │ │ └───.ropeproject │ config.py │ objectdb │ ├───calendarlib │ │ __init__.py │ │ │ ├───cal │ │ │ cal.py │ │ │ event.py │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ cal.cpython-36.pyc │ │ calendar.cpython-36.pyc │ │ event.cpython-36.pyc │ │ __init__.cpython-36.pyc │ │ │ ├───database │ │ │ db.py │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ db.cpython-36.pyc │ │ __init__.cpython-36.pyc │ │ │ └───ui │ window.py │ __init__.py │ ├───calendarlib.egg-info │ dependency_links.txt │ PKG-INFO │ SOURCES.txt │ top_level.txt │ └───dist calendarlib-0.1.tar.gz calendarlib-0.2.tar.gz __init__s are empty. Now when I use this code like with creating main.py here and importing stuff, it works. But when I push it to my git repo, install it with: pip install -U git+https://github.com/frynio/calendarlib (it is present in site-packages in Python installation dir) and do something like this: import sys from calendarlib.ui import window if __name__ == '__main__': app = window.QApplication(sys.argv) foo = window.CalendarWindow() foo.show() sys.exit(app.exec_()) It says: Traceback (most recent call last): File "main.py", line 2, in &lt;module&gt; from calendarlib.ui import window File "C:\Python36\lib\site-packages\calendarlib\ui\window.py", line 4, in &lt;module&gt; from database import db ModuleNotFoundError: No module named 'database' The code is in here. What can I do? Should I import it somehow different in my app, or should I change imports in calendarlib itself?
type: Question

http://stackoverflow.com/comment/88400209
type: Comment
has text: I am using notepad++ and command line for running my script. I can confirm I get memmory error. my coworker with 16gb ram also get out of memmory error. I am doing group by on 20milion row dataframe. Before I split it it was 40milion
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50682787

http://stackoverflow.com/comment/113489148
comment on: http://stackoverflow.com/a/50674639
has text: `from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload`
score: 4
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50794870
has body: You are probably missing tesseract-ocr from your machine. Check the installation instructions here: https://github.com/tesseract-ocr/tesseract/wiki On a Mac, you can just install using homebrew: brew install tesseract It should run fine after that
type: Answer
answers question: http://stackoverflow.com/q/50655738
downvote count: 1
upvote count: 23
score: 22

http://stackoverflow.com/q/50617292
has comment: http://stackoverflow.com/comment/88244377
has title: How to use distinct value of a list for a each process in python
has comment: http://stackoverflow.com/comment/88244459
type: Question
tagged with: python-multiprocessing
upvote count: 0
score: -2
has answer: http://stackoverflow.com/a/50617665
accepted answer: http://stackoverflow.com/a/50617665
has body: I have a list such as foo = ['battery', 'correct', 'horse', 'staple'] Now i am using multiprocessing and i am using one value from list in each process. Now i want my process to not to use a value which is already being used by another process. If there are 4 value in a list then there will be at max 4 processes. How can i achieve this.
answer count: 1
favorite count: 0
downvote count: 2
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88244523
has comment: http://stackoverflow.com/comment/88244405

http://stackoverflow.com/comment/88233190
type: QuestionComment
comment on: http://stackoverflow.com/q/50583777
has text: KDTree needs a starting point there's no way around that. If you start your search at any distance away from that point there is no way to know if your point is connected to your search area.
score: 0
type: Comment

http://stackoverflow.com/q/50645325
tagged with: arrays
has comment: http://stackoverflow.com/comment/88301400
has answer: http://stackoverflow.com/a/50645732
upvote count: 3
has body: Currently I have an array as follows: myArray = np.array( [[ 976.77 , 152.95 , 105.62 , 53.44 , 0 ], [ 987.61 , 156.63 , 105.53 , 51.1 , 0 ], [1003.74 , 151.31 , 104.435, 52.86 , 0 ], [ 968. , 153.41 , 106.24 , 58.98 , 0 ], [ 978.66 , 152.19 , 103.28 , 57.97 , 0 ], [1001.9 , 152.88 , 105.08 , 58.01 , 0 ], [1024.93 , 146.59 , 107.06 , 59.94 , 0 ], [1020.01 , 148.05 , 109.96 , 58.67 , 0 ], [1034.01 , 152.69 , 107.64 , 59.74 , 0 ], [ 0. , 154.88 , 102. , 58.96 , 0 ], [ 0. , 147.46 , 100.69 , 54.95 , 0 ], [ 0. , 149.7 , 102.439, 53.91 , 0 ]] ) I would like the fill in the zeros in the first column with the previous last value (1034.01) however if the 0's start from index 0, for it to remain as 0. Example of end result: myArrayEnd = np.array( [[ 976.77 , 152.95 , 105.62 , 53.44 , 0 ], [ 987.61 , 156.63 , 105.53 , 51.1 , 0 ], [1003.74 , 151.31 , 104.435, 52.86 , 0 ], [ 968. , 153.41 , 106.24 , 58.98 , 0 ], [ 978.66 , 152.19 , 103.28 , 57.97 , 0 ], [1001.9 , 152.88 , 105.08 , 58.01 , 0 ], [1024.93 , 146.59 , 107.06 , 59.94 , 0 ], [1020.01 , 148.05 , 109.96 , 58.67 , 0 ], [1034.01 , 152.69 , 107.64 , 59.74 , 0 ], [1034.01 , 154.88 , 102. , 58.96 , 0 ], [1034.01 , 147.46 , 100.69 , 54.95 , 0 ], [1034.01 , 149.7 , 102.439, 53.91 , 0 ]] ) I would like the code to be applicable to any array not just this one, where the situation may be different. (Column 3 might be all 0's and Column 4 might have 0's in the middle which should be filled with the last previous value).
has answer: http://stackoverflow.com/a/50645722
has comment: http://stackoverflow.com/comment/88301452
favorite count: 0
answer count: 5
has answer: http://stackoverflow.com/a/50645529
has answer: http://stackoverflow.com/a/50645535
has title: Fill values in a numpy array given a condition
tagged with: python
possible better answer: http://stackoverflow.com/a/50646075
has answer: http://stackoverflow.com/a/50646075
type: AnsweredQuestion
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/88301438
accepted answer: http://stackoverflow.com/a/50645732
type: Question
tagged with: numpy

http://stackoverflow.com/comment/88163026
comment on: http://stackoverflow.com/q/50571152
has text: Is there any way to replace recurse ()? or how to get and list all files from a github repositroy in new version github3.py( 0.9.3v,1.1.0v)?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88352838
comment on: http://stackoverflow.com/a/50671188
score: 0
type: AnswerComment
has text: This is Perfect! Both snippets work fine! Thank you so Much Blckknght!
type: Comment

http://stackoverflow.com/q/50647260
possible better answer: http://stackoverflow.com/a/50647380
answer count: 2
has comment: http://stackoverflow.com/comment/88326285
accepted answer: http://stackoverflow.com/a/50647386
has body: I have a list of lists: [[10, 9, 8], [8, 7], [1, 2, 3]] The sublists are not necessarily of the same size. I need to find a number that occurs in two seperate lists, and return the list index and the numbers index in those lists. in this case it would be 8, list 0, list 1, list 0 idx 2, list 1 idx 0. Right now I am doing it with a bunch of for loops, but this is ridiculously slow... are there are faster more pythonic way of achieving this?
has comment: http://stackoverflow.com/comment/88305129
favorite count: 0
has comment: http://stackoverflow.com/comment/88305317
downvote count: 3
has answer: http://stackoverflow.com/a/50647386
has comment: http://stackoverflow.com/comment/88305515
tagged with: python
has answer: http://stackoverflow.com/a/50647380
has comment: http://stackoverflow.com/comment/88326315
duplicate of: http://stackoverflow.com/q/10066642
type: AnsweredQuestion
upvote count: 0
tagged with: list
has comment: http://stackoverflow.com/comment/88305282
tagged with: set
score: -3
type: Question
has comment: http://stackoverflow.com/comment/88305503
has title: Finding an element that occurs in two lists, in a list of lists
tagged with: algorithm
linked to: http://stackoverflow.com/q/10066642

http://stackoverflow.com/comment/88164712
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50573857
score: 0
has text: https://developers.facebook.com/docs/graph-api/changelog/breaking-changes#login-4-24

http://stackoverflow.com/comment/88269348
has text: Meanwhile, `'.'join(thearray)` doesn’t work because you’re missing the `.` between the string and the method. I’m pretty sure (not in front of a computer, so I can’t test) that would be a `SyntaxError`, not a `TypeError`. I’m also pretty sure your error string is not actually one Python can generate. Please read [mcve] in the help, and copy and paste the actual error and the actual code that generates it if you want us to debug it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50629625
score: 2

http://stackoverflow.com/comment/88142401
type: Comment
has text: so if i replace can I overcome negative entropy while training. beside can I use tf.nn.softmax_cross_entropy_with_logits for binary classification
score: 0
comment on: http://stackoverflow.com/q/50565662
type: QuestionComment

http://stackoverflow.com/comment/88193587
type: QuestionComment
has text: @mikescotty not sure which is a better dupe cause he is currently using append
comment on: http://stackoverflow.com/q/50592137
score: 0
type: Comment

remote-debugging
tag name: remote-debugging
type: Tag
tags question: http://stackoverflow.com/q/50626663

http://stackoverflow.com/a/50678301
type: Answer
answers question: http://stackoverflow.com/q/50678117
score: 2
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/88391262
has body: Use: df = pd.DataFrame(np.array(L).reshape(5, 22).T, columns = list("abcde"))

http://stackoverflow.com/q/50698386
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/50699006
has answer: http://stackoverflow.com/a/50699006
has title: Get dataframe when a next line is numeric
has answer: http://stackoverflow.com/a/50698733
type: Question
score: 1
has body: I have a DataFrame that looks something like this: import numpy as np import pandas as pd df=pd.DataFrame([['ph','ro','to'],[5,5,8],[4,3,1],['ph','ro','to'],[np.NaN,np.NaN,np.NaN], [np.NaN,np.NaN,np.NaN],['ph','ro','togr'],[5,5,8],['ph','gho','to'], [np.NaN,np.NaN,np.NaN]],columns=['A','B','C']) df A B C 0 ph ro to 1 5 5 8 2 4 3 1 3 ph ro to 4 NaN NaN NaN 5 NaN NaN NaN 6 ph ro togr 7 5 5 8 8 ph gho to 9 NaN NaN NaN What I want to do is get where df.A='ph' and the next row in the the same column is numerique and obtain: A B C 0 ph ro to 6 ph ro togr
answer count: 2
tagged with: pandas
upvote count: 1
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50698733

http://stackoverflow.com/a/57068040
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50662730
answers question: http://stackoverflow.com/q/50662730
upvote count: 2
type: Answer
has body: I think this may be what you want: Button(background=normal_color, foreground=text_color, activebackground=pressed_color, activeforeground=pressed_text_color) This changes the button from normal_color to pressed_color when the button is pressed. It's actually a simple question with a simple answer but I had to look everywhere too. Finally found this answer by reading http://effbot.org/tkinterbook/button.htm.
score: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/92753050
comment on: http://stackoverflow.com/a/52600893
score: 0
type: Comment
has text: look in the link below. it gets rid of "Module 'pygame' has no 'init' member" error in vs code when you are trying to make a pygame.
type: AnswerComment

http://stackoverflow.com/a/50554437
answers question: http://stackoverflow.com/q/50554102
score: 0
type: Answer
has body: You're calling random.randint inside traffic. Every time you call it, it generates a new random integer for you, thus selecting a random image to display each time you call traffic. To fix this, randomly choose your image ahead of time (For example when you reset the car to the top of the screen) and save it in a variable. Then pass that variable to traffic. def traffic(traffic_x, traffic_y, traffic_image): gameDisplay.blit(traffic_image, (traffic_x, traffic_y)) # ... traffic_list = [traffic1, traffic2, traffic3, traffic4, traffic5] # ... car_image = traffic_list[random.randint(0, 4)] # ... call traffic(x, y, car_image) multiple times ...

http://stackoverflow.com/q/50566870
answer count: 1
favorite count: 0
type: UnansweredQuestion
has title: operation by line with dataframe in pandas
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/22149584
has answer: http://stackoverflow.com/a/50566967
upvote count: 1
downvote count: 1
type: Question
has body: I want to do an operation with dataframe in Pandas 23.0 but I can not find the best way to do it. I pick up from a CSV an id with a time and value and I intend to calculate the mean (mean ()) for each of the rows. Example: id time value 1 22:10:01 10 2 22:10:02 20 3 22:10:03 30 2 22:10:04 40 1 22:10:05 50 It would be something like this: id time value mean 1 22:10:01 10 10 2 22:10:02 20 20 3 22:10:03 30 30 2 22:10:04 40 30 ((40 + 20) / 2) 1 22:10:05 50 30 ((50 + 10) / 2) Taking into account that the first means would be the value itself. I have arrived at a solution using an auxiliary dictionary: dat = pd.read_csv ('file.csv') dicc = {} for row in dat.itertuples (): ids = row [1] values = row [3] timestamps = row [2] if ids in dicc dicc [ids]['id'].append(ids) dicc [ids]['value'].append(values) dicc [ids]['mean'].append((dicc[ids]['mean'][- 1]+values)/2) else: dicc [ids] = { 'sensor_id': [ids], 'timestamp': [timestamps], 'mean': [values] df2 = pd.DataFrame.from_dict(data=dicc) df2.to_csv('file2.csv') basically what I do is fill in the dictionary knowing if the id has already appeared or not. If try to create a new df with the mean column in order to test the timming: last=len(datos.columns) df=pd.DataFrame(data=dat, columns=dat.keys()) df.insert(loc=last, column='mean', value=None) but I don't find the way to do that process in a dataframe
tagged with: dataframe
score: 0
tagged with: pandas

http://stackoverflow.com/q/50639614
has body: I am working on a text classification problem in python using sklearn. I have created the model and saved it in a pickle. Below is the code I used in sklearn. vectorizerPipe = Pipeline([('tfidf', TfidfVectorizer(lowercase=True, stop_words='english')), ('classification', OneVsRestClassifier(LinearSVC(penalty='l2', loss='hinge'))),]) prd=vectorizerPipe.fit(features_used,labels_used]) f = open(file_path, 'wb') pickle.dump(prd, f) Is there any way to use this same pickle to get the output in DataFrame based apache spark and not RDD based. I have gone through the following articles but didn't find a proper way to implement. what-is-the-recommended-way-to-distribute-a-scikit-learn-classifier-in-spark how-to-do-prediction-with-sklearn-model-inside-spark -> I found both these questions on StackOverflow and find it useful. deploy-a-python-model-more-efficiently-over-spark I am a beginner in Machine learning. So, pardon me If the explanation is naive. Any related example or implementation would be helpful.
tagged with: python
type: UnansweredQuestion
score: 1
upvote count: 1
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/92012259
type: Question
tagged with: apache-spark-mllib
tagged with: apache-spark
answer count: 1
downvote count: 0
tagged with: scikit-learn
has title: Using sklearn-python model in spark ML 2.2.0 for prediction
favorite count: 0
linked to: http://stackoverflow.com/q/39672114
has answer: http://stackoverflow.com/a/59278225
linked to: http://stackoverflow.com/q/42887621
has comment: http://stackoverflow.com/comment/91996908

http://stackoverflow.com/q/50620282
linked to: http://stackoverflow.com/q/48787264
downvote count: 0
favorite count: 0
has body: I am using the standard solution to do speech to text processing with time stamps (see code below). I know from this post that it is possible to add arguments to the gcloud commandline tool, like --format=json. General question: How do I specify those in google.cloud.speech? I can't seem to find any documentation on Googles site on how to do this with Python. Specific question: My aim right now, is to write out a dictionary style JSON file that contains entries for all words, plus their start and end time per word. I realise that I cloud write a hacky solution, but if a option already exists, that would be preferable. Code: def transcribe_file_with_word_time_offsets(speech_file, language): """Transcribe the given audio file synchronously and output the word time offsets.""" print("Start") from google.cloud import speech from google.cloud.speech import enums from google.cloud.speech import types print("checking credentials") client = speech.SpeechClient(credentials=credentials) print("Checked") with io.open(speech_file, 'rb') as audio_file: content = audio_file.read() print("audio file read") audio = types.RecognitionAudio(content=content) print("config start") config = types.RecognitionConfig( encoding=enums.RecognitionConfig.AudioEncoding.FLAC, language_code=language, enable_word_time_offsets=True) print("Recognizing:") response = client.recognize(config, audio) print("Recognized") for result in response.results: alternative = result.alternatives[0] print('Transcript: {}'.format(alternative.transcript)) for word_info in alternative.words: word = word_info.word start_time = word_info.start_time end_time = word_info.end_time print('Word: {}, start_time: {}, end_time: {}'.format( word, start_time.seconds + start_time.nanos * 1e-9, end_time.seconds + end_time.nanos * 1e-9)) if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument(dest='path', help='Audio file to be recogni…
upvote count: 6
has answer: http://stackoverflow.com/a/64921112
tagged with: google-api
score: 6
tagged with: python
type: AnsweredQuestion
has title: Google cloud speech to text in Python: Save translation and time to JSON
tagged with: speech-to-text
possible better answer: http://stackoverflow.com/a/65232181
accepted answer: http://stackoverflow.com/a/64921112
type: Question
has answer: http://stackoverflow.com/a/65232181
answer count: 2

hamming-distance
tags question: http://stackoverflow.com/q/50615262
tag name: hamming-distance
type: Tag

http://stackoverflow.com/q/50684079
type: Question
possible better answer: http://stackoverflow.com/a/50684284
has comment: http://stackoverflow.com/comment/88378206
has answer: http://stackoverflow.com/a/50684263
accepted answer: http://stackoverflow.com/a/50684263
answer count: 2
has comment: http://stackoverflow.com/comment/88378020
upvote count: 1
favorite count: 0
has body: I'm new to Python (3.6) and I'm trying to figure out a way to create a nested dictionary from a list of lists. The example input is: myList = [[1, B, C],[1, D, C],[1, E, C],[1, F, G],[1, H, G],[2, I, C],[2, J, C],[2, K, G]] What I want to get is: result = {1: {C: [B, D, E], G: [F, H]}, 2: {C: [I, J], G: [K]}} What I've got for now is: result = defaultdict(list) for key, *values in myList: result[key].extend(values) Which gives me the output: {1: [B, C, D, C, E, C, F, G, H, G], 2: [I, C, J, C, K, G]} I'm looking for a way to create a nested dictionary, where every repeated value in the list of values for a key becomes a key of a sub-dictionary. Could you advise what approaches can I consider bearing in mind that I'm dealing with a large dataset? What I did so far has a major flaw as I loose the information on which value should be assigned to which key in sub-dictionaries.
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/88378083
type: AnsweredQuestion
tagged with: python-3.x
downvote count: 0
score: 1
has title: Create a nested dictionary from a dictionary based on repeated values
has answer: http://stackoverflow.com/a/50684284

http://stackoverflow.com/q/50643386
tagged with: pandas
has body: Working with data in Python 3+ with pandas. It seems like there should be an easy way to check if two columns have a one-to-one relationship (regardless of column type), but I'm struggling to think of the best way to do this. Example of expected output: A B C 0 'a' 'apple' 1 'b' 'banana' 2 'c' 'apple' A &amp; B are one-to-one? TRUE A &amp; C are one-to-one? FALSE B &amp; C are one-to-one? FALSE
has comment: http://stackoverflow.com/comment/88297413
favorite count: 0
has answer: http://stackoverflow.com/a/64310994
tagged with: one-to-one
has answer: http://stackoverflow.com/a/53551320
answer count: 5
has comment: http://stackoverflow.com/comment/118624170
tagged with: python
possible better answer: http://stackoverflow.com/a/53551320
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50643635
has title: Easy Way to See if Two Columns are One-to-One in Pandas
has comment: http://stackoverflow.com/comment/88296998
downvote count: 2
upvote count: 17
type: Question
has comment: http://stackoverflow.com/comment/88296966
has answer: http://stackoverflow.com/a/56870168
has answer: http://stackoverflow.com/a/50643856
score: 15
accepted answer: http://stackoverflow.com/a/50643635

http://stackoverflow.com/comment/88293090
score: 2
type: Comment
has text: There is a slight problem with this, this applies dropout across all timesteps meaning that some timesteps can be completely dropped. To dropout every timestep independently, you need to specify `noise_shape=(batch_size, 1, features)` [doc](https://keras.io/layers/core/#dropout).
type: AnswerComment
comment on: http://stackoverflow.com/a/50636042

http://stackoverflow.com/comment/88180908
type: QuestionComment
comment on: http://stackoverflow.com/q/50585674
score: 0
has text: or: create your Popen from within a thread already. Depends on what you want to achieve.
type: Comment

http://stackoverflow.com/a/50567308
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89107557
has comment: http://stackoverflow.com/comment/96815511
has body: You should fit the MinMaxScaler using the training data and then apply the scaler on the testing data before the prediction. In summary: Step 1: fit the scaler on the TRAINING data Step 2: use the scaler to transform the TRAINING data Step 3: use the transformed training data to fit the predictive model Step 4: use the scaler to transform the TEST data Step 5: predict using the trained model (step 3) and the transformed TEST data (step 4). Example using your data: from sklearn import preprocessing min_max_scaler = preprocessing.MinMaxScaler() #training data df = pd.DataFrame({'A':[1,2,3,7,9,15,16,1,5,6,2,4,8,9],'B':[15,12,10,11,8,14,17,20,4,12,4,5,17,19],'C':['Y','Y','Y','Y','N','N','N','Y','N','Y','N','N','Y','Y']}) #fit and transform the training data and use them for the model training df'A','B' = min_max_scaler.fit_transform(df'A','B') df['C'] = df['C'].apply(lambda x: 0 if x.strip()=='N' else 1) #fit the model model.fit(df['A','B']) #after the model training on the transformed training data define the testing data df_test df_test = pd.DataFrame({'A':[25,67,24,76,23],'B':[2,54,22,75,19]}) #before the prediction of the test data, ONLY APPLY the scaler on them df_test'A','B' = min_max_scaler.transform(df_test'A','B') #test the model y_predicted_from_model = model.predict(df_test['A','B']) Example using iris data: import matplotlib.pyplot as plt from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from sklearn.svm import SVC data = datasets.load_iris() X = data.data y = data.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0) scaler = MinMaxScaler() X_train_scaled = scaler.fit_transform(X_train) model = SVC() model.fit(X_train_scaled, y_train) X_test_scaled = scaler.transform(X_test) y_pred = model.predict(X_test_scaled) Hope this helps. See also by post here: https://towardsdatascience.com/everything-you-need-to-know-about-min-max…
upvote count: 60
type: Answer
has comment: http://stackoverflow.com/comment/138680291
answers question: http://stackoverflow.com/q/50565937
has comment: http://stackoverflow.com/comment/96810830
accepted answer of: http://stackoverflow.com/q/50565937
downvote count: 0
has comment: http://stackoverflow.com/comment/91150869
has comment: http://stackoverflow.com/comment/91559723
has comment: http://stackoverflow.com/comment/88164747
score: 60
has comment: http://stackoverflow.com/comment/88165168
has comment: http://stackoverflow.com/comment/89106686

http://stackoverflow.com/q/50573859
has answer: http://stackoverflow.com/a/50573886
tagged with: split
has body: I am trying to split a dataframe column into two columns and have it "merged" into the original one. For example, some players have multiple position eligibility and I want to split them into a primary and secondary position column. Player Roster Position John Doe 1B/2B Becomes Player Primary Position Secondary Position John Doe 1B 2B The code is as follows - I tried a merge and of course it is telling me that there are no like columns to merge on. I don't know if I can merge based on the index, or how to get the player name to go into the "secondData" dataframe. filename = "DKSalaries.csv" playerData = pd.read_csv(filename) secondData = (playerData['RosterPosition'].str.split('/', 1, expand=True).rename(columns={0:'Primary Position', 1:'Secondary Position'})) newData = playerData.merge(secondData, how='left') print(newData)
tagged with: dataframe
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88157232
accepted answer: http://stackoverflow.com/a/50573886
has comment: http://stackoverflow.com/comment/88157313
tagged with: python
has comment: http://stackoverflow.com/comment/88157331
type: AnsweredQuestion
has title: Split Dataframes into 2 columns and merge into original
type: Question

http://stackoverflow.com/q/50554791
has comment: http://stackoverflow.com/comment/88121300
score: 1
has body: i want to create QLabels dynamically at runtime, and change the Text afterwards. I did it like that: def __init__(self, *args, **kwargs): QWidget.__init__(self, *args, **kwargs) self.counter = 0 self.items = self.read_hosts() self.layout = QGridLayout() for item in self.items: self.item = QLabel(item, self) self.item.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.item.setAlignment(Qt.AlignCenter) self.item.setStyleSheet("QLabel {background-color: green;}") self.layout.addWidget(self.item,self.counter, 0) self.counter += 1 self.setLayout(self.layout) self.startWorker() self.show() def change_txt(self, lb, i): self.item.setText("{}".format(i)) It won't work. I understand why it would change just the text of the last label. I'm doing something wrong during assignment. How can I create all labels completely variably and subsequently change the texts? I am using: PyQT5 on Windows 10 Thanks! Here is my whole code: import sys from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import * import os class Worker(QObject): update = pyqtSignal(str,int) exception = pyqtSignal(str) def read_hosts(self): #try: file = open("hosts.ini", "r") return file.readlines() #except Exception as ex: #self.exception.emit(str(ex)) def check_ping(self): #try: hosts = self.read_hosts() while True: for host in hosts: print(host) params = " -l 1000" response = os.system("ping " + host + params) print("weiter") self.update.emit(host, response) #except Exception as ex: #self.exception.emit(str(ex)) class Window(QWidget): def __init__(self, *args, **kwargs): QWidget.__init__(self, *args, **kwargs) self.counter = 0 self.items = self.read_hosts() self.layout = QGridLayout() for item in self.items: self.item = QLabel(item, self) self.item.setObjectName("label" + str(self.counter)) print("label" + str(self.counter)) self.item.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.item.setAlignment(Qt.AlignCenter) self.item.setStyleSheet("QLabel {background-…
tagged with: pyqt5
upvote count: 1
has comment: http://stackoverflow.com/comment/88121424
type: Question
has comment: http://stackoverflow.com/comment/88121727
tagged with: qlabel
has title: PyQt - Create QLabels at runtime and change text afterwards
tagged with: pyqt
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88121545
accepted answer: http://stackoverflow.com/a/50555598
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50555598
type: AnsweredQuestion

http://stackoverflow.com/q/50542339
has answer: http://stackoverflow.com/a/50546150
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/50592392
favorite count: 0
linked to: http://stackoverflow.com/q/23294658
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50543064
tagged with: python
has body: This is my exercise: get the user's first name, last name and birth year. Create initials from the name (first letter) and calculate the age of the user. I wrote a script: def age_name(): # var= firstName ,lastName ,year is_running=True firstName =input("What is your name?").lower() while is_running==True: if firstName.isalpha() and len(firstName)&gt;0: lastName = input("What is your last name?").lower() if lastName.isalpha() and len(lastName) &gt; 0: year = input("What is your birth year?") if year.isnumeric() or len(year)==4: year=int(year) print("Your initials are {0}{1} and your age is {2}.".format(firstName[0],lastName[0],2018-year)) #print("Your initials are ",firstName[0],lastName[0],"and your age is ",str(2018-year)) else: print("invalid year. please type your birth year") year = input("What is your birth year?") else: print("invalid last name. please type your last name") lastName = input("What is you last name?").lower() else: print("invalid name. please type your name") firstName = input("What is you name?").lower() age_name() I've tested the code and this is what I get: What is your name?p5 invalid name. please type your name What is you name?peter What is your last name?p5 invalid last name. please type your last name What is you last name?pen What is your last name?pen What is your birth year?p5 invalid year. please type your birth year What is your birth year?10 What is your last name?pen What is your birth year?1800 Your initials are pp and your age is 218. What is your last name? First of all, I think my code is a bit repetitive - if someone has ideas to shorten it. Second and biggest problem - I keep getting the last name question. Where is my bug?
score: 3
has comment: http://stackoverflow.com/comment/88098831
upvote count: 3
has comment: http://stackoverflow.com/comment/88095939
has comment: http://stackoverflow.com/comment/88095932
has title: How to check if the user's input is valid Python
type: Question

http://stackoverflow.com/comment/88363088
type: Comment
has text: @Dark - Why do you think?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50676729

http://stackoverflow.com/a/50695465
score: 2
downvote count: 0
upvote count: 2
has body: Here is mixture of functional and pandastic approach: df = pd.DataFrame({'w1': [0, 1, 1, 0], 'w2': [1, 1, 0, 1], 'w3': [1, 0, 0, 0], 'w4': [0, 1, 1, 0], 'w5': [1, 1, 0, 1], 'w6': [0, 0, 1, 1], 'w7': [0, 1, 1, 0], 'w8': [1, 1, 1, 1]}) def errase_diff(row, n = 4, Diff = 3): """ returns array with erassed diff values after last positive value in first n column """ row_length = len(row) last_positive_id = [i for i, v in enumerate(row[:4]) if v == 1][-1] row[last_positive_id + 1: last_positive_id + 1 + Diff] = [0 for _ in range(Diff)] return row[:row_length] df.apply(lambda x: errase_diff(x), 1) w1 w2 w3 w4 w5 w6 w7 w8 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 0 0 1 2 1 0 0 1 0 0 0 1 3 0 1 0 0 0 1 0 1 be aware that this solution erase data in your original df
answers question: http://stackoverflow.com/q/50695000
type: Answer

http://stackoverflow.com/comment/88391299
type: Comment
comment on: http://stackoverflow.com/q/50648207
score: 0
type: QuestionComment
has text: Thanks a lot guys. I found the solution in the other post to be working out. So marked my question as duplicate.

http://stackoverflow.com/comment/88546964
has text: @MajidAzimi What do you mean that you _"needed to substract `center.x` and `center.y` before applying this function"_? Do you see parameter `cnt` and what it is doing? I used the same variable name `cnt` (as opposite to something more human, such as `center`) because that is how _you called it in your example_ (!).
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50557989
type: Comment

http://stackoverflow.com/comment/88318927
comment on: http://stackoverflow.com/q/50653892
score: 1
has text: Open migration file in question (`accounts.0002_auto_20180514_0523`) and find where migration is trying to add `''` to integer field.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88297704
has text: No. I get a different error that is too long to put in a comment. I would move it to chat but I dont have enough rep to do that.
type: Comment
comment on: http://stackoverflow.com/a/50643413
type: AnswerComment
score: 0

http://stackoverflow.com/a/50642282
type: Answer
accepted answer of: http://stackoverflow.com/q/50620531
has body: Alembic doesn't have to connect to the database using the database URI to run upgrades. In your alembic\env.py file there will be a function like this: def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ connectable = engine_from_config( config.get_section(config.config_ini_section), prefix='sqlalchemy.', poolclass=pool.NullPool) with connectable.connect() as connection: context.configure( connection=connection, target_metadata=target_metadata ) with context.begin_transaction(): context.run_migrations() All that matters is that that the variable connectable is an engine instance when alembic calls connect() on it. Therefore you could do something like this (this isn't tested but I do something similar myself): def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ sshtunnel.SSH_TIMEOUT = 5.0 sshtunnel.TUNNEL_TIMEOUT = 5.0 server = sshtunnel.SSHTunnelForwarder( ('ssh.pythonanywhere.com', 22), ssh_password="mypassword", ssh_username="myusername", remote_bind_address=\ (myname.mysql.pythonanywhere-services.com', 3306)) server.start() connectable = create_engine( 'mysql+mysqldb://mynameb:dbpassword@127.0.0.1:%s/dbname' % server.local_bind_port ) with connectable.connect() as connection: context.configure( connection=connection, target_metadata=target_metadata ) with context.begin_transaction(): context.run_migrations() Ideally you'd put all of your connection logic somewhere it can be accessed both from the alembic/env.py and in your project so you only have it defined once and then you could just import the engine directly into env.py, but you get the idea.
answers question: http://stackoverflow.com/q/50620531
type: AcceptedAnswer
score: 0

http://stackoverflow.com/a/50691885
has body: Representing rooms as functions is unlikely to be a viable approach. As you've discovered, you end up repeating a lot of code. This sort of application is a classic use case for Python objects and classes. (It looks as though you may still be learning Python, so you may not have encountered these yet.) Modelling rooms, minions, and items each as a class will allow you to express your game in a much simpler and more straightforward way.
has comment: http://stackoverflow.com/comment/88393674
answers question: http://stackoverflow.com/q/50691801
has comment: http://stackoverflow.com/comment/88396432
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88395463
downvote count: 0

http://stackoverflow.com/a/50663731
type: AcceptedAnswer
score: 4
accepted answer of: http://stackoverflow.com/q/50627861
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/50627861
downvote count: 0
has comment: http://stackoverflow.com/comment/88388782
has comment: http://stackoverflow.com/comment/88387350
has body: You should be able to do it also with discrete state without any problem (I never tried, though). The probability prob_s_a_* you are talking about are the probabilities of drawing the sampled actions with the current policy (one value per sample). PPO does not use D_KL (the KL divergence), as from its experiments it performed worse (they just clip the probabilities ratio). So you need just to add a placeholder for the old log prob and clip the ratio between the new log prob (tf.log(ch_action_p_values)) and the old log ones. Here is an example (e_clip is the clipping value, in the paper they use 0.2) vanilla_loss = -tf.reduce_sum(advantages * tf.log(ch_action_p_values)) old_log_probs = tf.placeholder(...) log_probs = tf.log(ch_action_p_values) prob_ratio = tf.exp(log_prob - old_log_probs) clip_prob = tf.clip_by_value(prob_ratio, 1.-e_clip, 1.+e_clip) ppo_loss = -tf.reduce_mean(tf.minimum(tf.multiply(prob_ratio, advantages), tf.multiply(clip_prob, advantages))) Beside the usual advantages and ch_action_p_values, you need to feed the loss with old_log_probs, computed as the log probability of the current policy on the sampled actions.

http://stackoverflow.com/comment/88409014
type: Comment
has text: If my answer helps you do not forget to mark it as correct, if you do not know how to do it I invite you to review the [tour], that is the best way to thank
type: AnswerComment
comment on: http://stackoverflow.com/a/50685919
score: 0

http://stackoverflow.com/q/50644578
has comment: http://stackoverflow.com/comment/88299592
tagged with: scipy
tagged with: signal-processing
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/88299492
has answer: http://stackoverflow.com/a/50644762
downvote count: 0
answer count: 1
score: 4
has title: Apply a high-pass filter to a WAV file with scipy.signal.firwin
has comment: http://stackoverflow.com/comment/88299896
favorite count: 0
has body: I'm trying to apply a high-pass filter (cutoff: 1000 Hz) to a mono 16-bit 44.1 Khz WAV file with scipy.signal.firwin: from scipy.io import wavfile from scipy import signal import numpy as np sr, x = wavfile.read('test.wav') # 16-bit mono 44.1 khz b = signal.firwin(5, cutoff=1000, fs=sr, pass_zero=False) x = signal.lfilter(b, [1.0], x) wavfile.write('test2.wav', sr, x.astype(np.int16)) The result is totally similar to the input (but not exactly equal), i.e. no high-pass has been applied. What should I modify to make this high-pass with firwin work?
type: UnansweredQuestion
tagged with: python
tagged with: audio
has comment: http://stackoverflow.com/comment/88300085
has comment: http://stackoverflow.com/comment/88300616

http://stackoverflow.com/comment/88404132
comment on: http://stackoverflow.com/a/50687280
score: 0
type: AnswerComment
has text: Yeah that is what I ended up doing. Thanks
type: Comment

http://stackoverflow.com/q/50666614
has answer: http://stackoverflow.com/a/50671497
has title: Pandas - Join two JSON in different structure the right way
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/50673048
score: 2
type: AnsweredQuestion
downvote count: 0
tagged with: join
has body: I know there are many similar problems, but still I have the feeling I'm doing so many things wrong here, I'm sure some of you can help me and give me some advise for the future, I tried many different ways but still doesn't work properly. I have the two following data sources that I'd like to join with pandas. First json with properties - let's call it json1: [ { "propertyDetails": { "accountId": 102864, "availableFromFormatted": "On request", "cityName": "Derendingen", "contactFormTypeId": 3, "countryId": 1, "description": "Mehr erfahren: Für weitere Bilder, Informationen zu Raumangebot, Gemeinde und Lage besuchen sie uns auf www.immostema.ch und geben Sie oben rechts im Suchfeld die Objektnummer I0398 ein. Wir freuen uns auf Sie! **Schauen Sie sich das Kurzvideo an:** [https://youtu.be/xyD9oX4nmDQ](https://youtu.be/xyD9oX4nmDQ) In Derendingen im Kanton Solothurn, verkaufen wir an ruhiger Wohnlage dieses **5½-Zimmer-Einfamilienhaus**(Doppeleinfamilienhaushälfte). Das Haus, im Jahr 2013 erbaut, wurde mit qualitativ hochwertigen Materialen Innen ausgebaut. Das Haus eignet sich sehr gut für Familien und bietet sehr schönes und ruhiges Wohnen. Zum Haus gehören auch ein Autounterstand mit Geräteraum sowie ein zusätzlicher Parkplatz. **Hier die Eckdaten:** - Einfamilienhaus mit 5½ - Zimmer - Grundstück: 221 m² - Wohnfläche: 141 m² - Nutzfläche: 216 m² - Hochwertiger Innenausbau - Wärmepumpe - Fussbodenheizung - Grosse gedeckte Terrasse - Grosser Balkon - 1 Autounterstand mit grossem Geräteraum zur Eigennutzung - 1 Parkplatz Schulen, Einkaufsmöglichkeiten, Banken, Post, erreicht man in wenigen Minuten. Busbetrieb Solothurn und Umgebung (BSU) verkehrt im 15 Minutentakt. Die Bushaltestelle befindet sich nur 50m vom Haus entfernt. Verlangen Sie die detaillierte Verkaufsdokumentation. ", "geoAccuracy": 8, "id": 4998203 }, "propertyDetailsView": { "accountPropertiesUrl": "/en/agency-properties/immostema-ag/102864" } }, { "propertyDetails": { "accountId": 98465, "attributesSiz…
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/88349614
has answer: http://stackoverflow.com/a/50673048
type: Question
upvote count: 2
answer count: 2
favorite count: 0
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50671497

http://stackoverflow.com/comment/88220250
type: QuestionComment
score: 1
has text: What was wrong with `tf.gather_nd`? It should do what you want.
comment on: http://stackoverflow.com/q/50605059
type: Comment

http://stackoverflow.com/q/50581917
has answer: http://stackoverflow.com/a/50587110
accepted answer: http://stackoverflow.com/a/50587110
upvote count: 3
answer count: 1
tagged with: keras
favorite count: 0
has body: I am trying to design a CNN architecture in keras python. I want to transform (for my decoder) form the deconvoluation layer 5 (512 filters with filter size 4x4) to the next layer (using deconvolution2D) and to go to deconvolution layer 6 128 filters with filter size 7x7. How can I do that deconvolution? What I tried is the following: d6 = Deconvolution2D(128, 5, 5, subsample=(2,2), activation='relu',init='uniform', output_shape=(None, 128, 7, 7), border_mode='same')(d6) However, this operation leads to 128 filters with size 8x8. How can I have instead 7x7? I am trying also to go from (8x8) to (7x7) using simply convolution by choosing as filter size (3x3) and the same number of filters: d6 = Convolution2D(128, 3, 3, activation='relu', border_mode='same')(d6) However, the result in the end is again the same (128,8,8) instead of (128, 7, 7)
tagged with: python
type: AnsweredQuestion
downvote count: 0
has title: Deconvolution layers in keras
type: Question
tagged with: numpy
score: 3

http://stackoverflow.com/a/59329910
answers question: http://stackoverflow.com/q/50620954
score: 18
has body: Assume you are running under Windows. Application Error code 0xc0000005, also known as Access Violation error, is a common problem experienced by Windows users, regardless of os version. There are various causes to trigger Application Error 0xc0000005. For my case, I'm running debug mode in PyCharm (or Eclipse) with code that includes the following: from pympler import muppy all_objects=muppy.get_objects() # this causes pydev debugger exit with code -1073741819 (0xC0000005) It was perfectly fine if execute the same piece of code through PyCharm in non-debug (Run) mode. Disabled the above code in debug mode, issue resolved. Environment: PyCharm Community 2019.3, Anaconda 3, Python 3.7.3, pympler 0.7, Windows 10 Enterprise
has comment: http://stackoverflow.com/comment/137520359
downvote count: 0
has comment: http://stackoverflow.com/comment/129769980
type: Answer
has comment: http://stackoverflow.com/comment/136464571
upvote count: 18

http://stackoverflow.com/q/50545927
accepted answer: http://stackoverflow.com/a/50546732
has comment: http://stackoverflow.com/comment/88102768
has title: Clicker game in python not working
tagged with: python-3.x
tagged with: tkinter
duplicate of: http://stackoverflow.com/q/5767228
downvote count: 2
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: -1
has answer: http://stackoverflow.com/a/50546732
linked to: http://stackoverflow.com/q/5767228
type: Question
has comment: http://stackoverflow.com/comment/88102786
answer count: 1
has body: I have the code off a clicker below and I'm trying to solve how to show to the number of clicks on the window in tkinter. I'm new to python. If I click on the button the number of clicks remains the same. I don't know if the text doesn't updates or if the increase() function doesn't work. Please help me solve this. from tkinter import * clicks = 0 def increase(clicks): clicks += 1 root = Tk() root.geometry('500x300') label=Label(text="Clicks:") show=Label(text=clicks) btc = Button(text="Click me", command=increase(clicks)) label.pack() show.pack() btc.pack() root.mainloop()
favorite count: 0

http://stackoverflow.com/q/50549832
tagged with: pyside
has comment: http://stackoverflow.com/comment/88111520
has comment: http://stackoverflow.com/comment/88112015
tagged with: selection
type: Question
has answer: http://stackoverflow.com/a/50551424
answer count: 1
has comment: http://stackoverflow.com/comment/88125702
score: 0
has comment: http://stackoverflow.com/comment/88110574
tagged with: focus
has comment: http://stackoverflow.com/comment/88110611
favorite count: 0
accepted answer: http://stackoverflow.com/a/50551424
tagged with: qlistwidget
upvote count: 1
tagged with: python
has body: I am using PySide and I have a QListWidget. I made a dummy item and placed it at the top of the QListWidget. I did this so when the tool first opens, no useful item is selected by default. I do not like that this empty item is "highlighted", revealing the item to the user. How can I get rid of this outline/highlight? I will include an image of the issue:
downvote count: 1
type: AnsweredQuestion
has title: How to remove focus from QListWidget item

http://stackoverflow.com/comment/88314158
score: 0
type: Comment
has text: you forgot a `split('-')[0]` part missing in op's code but that gives the expected output
comment on: http://stackoverflow.com/a/50651452
type: AnswerComment

http://stackoverflow.com/q/50630821
tagged with: tensorflow
has answer: http://stackoverflow.com/a/50631922
accepted answer: http://stackoverflow.com/a/50631922
type: Question
score: 0
answer count: 1
tagged with: keras
has body: I'm running Keras in an NVIDIA Docker container on a multi-GPU machine. I'd like to instantiate a fairly standard model (Xception), but I keep getting weird errors. MRE: import tensorflow as tf from keras.applications import Xception height = 299 width = 299 num_classes = 1000 # Instantiate model model = Xception(weights=None, input_shape=(height, width, 3), classes=num_classes) I get the error: Traceback (most recent call last): File "basic_test.py", line 9, in &lt;module&gt; model = Xception(weights=None, input_shape=(height, width, 3), classes=num_classes) File "/usr/local/lib/python2.7/dist-packages/keras/applications/xception.py", line 235, in Xception x = Dense(classes, activation='softmax', name='predictions')(x) File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 619, in __call__ output = self.call(inputs, **kwargs) File "/usr/local/lib/python2.7/dist-packages/keras/layers/core.py", line 881, in call output = self.activation(output) File "/usr/local/lib/python2.7/dist-packages/keras/activations.py", line 29, in softmax return K.softmax(x) File "/usr/local/lib/python2.7/dist-packages/keras/backend/tensorflow_backend.py", line 2963, in softmax return tf.nn.softmax(x, axis=axis) TypeError: softmax() got an unexpected keyword argument 'axis' Versions for Python, Keras &amp; Tensorflow: python -c 'import keras; import tensorflow; import sys; print(sys.version, 'keras.__version__', 'tensorflow.__version__')' Using TensorFlow backend. ('2.7.12 (default, Nov 20 2017, 18:23:56) \n[GCC 5.4.0 20160609]', '2.1.6', '1.4.0')
has title: cannot instantiate an Xception model in Keras
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/88352283
has text: Try `word_tokenize('\n'.join(data_corpus))`
comment on: http://stackoverflow.com/q/50668970
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/88282045
type: Comment
comment on: http://stackoverflow.com/q/50629071
type: QuestionComment
score: 0
has text: If the LP dual is infeasible, then it's possible that your original model may be unbounded. To troubleshoot the exception, it may be helpful running the solve as a python script. That is, add `SolverFactory('glpk').solve(model, tee=True)` and `model.display()` to the bottom of your model file and executing it as a script: `python model.py`.

http://stackoverflow.com/comment/88254720
comment on: http://stackoverflow.com/a/50608469
has text: you need to change your `elements_gen()` function to `yield(x['seq'], y)`
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50685769
score: 0
has comment: http://stackoverflow.com/comment/88381829
type: UnansweredQuestion
has title: How do I read unstructured csv file using pandas
answer count: 0
type: Question
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has body: In python, how can I read an unstructured csv file (with some redundant rows of texts) and output it as a new structured csv file using pandas? There are some unwanted rows in the csv file (at the very beginning as shown by the picture) which is getting parsed as a unique column resulting in incorrect format of columns, but actually these lines should be ignored The unstructured csv The Desired Structure : I have searched for a solution, but none of the previous questions here solve my problem
tagged with: python
has comment: http://stackoverflow.com/comment/88381333

http://stackoverflow.com/a/50609073
downvote count: 0
has body: You can create a date_range and use merge Example: &gt;&gt;&gt; pd.date_range(start=df.date.min(), end=df.date.max(), freq='1D') DatetimeIndex(['2017-11-09', '2017-11-10', '2017-11-11', '2017-11-12', '2017-11-13', '2017-11-14'], dtype='datetime64[ns]', freq='D') Then df2 = pd.DataFrame((pd.date_range(start=df.date.min(), end=df.date.max(), freq='1D')), columns=["date"]) pd.merge(df2,df, on="date", how="left").fillna(0) date count 0 2017-11-09 3.0 1 2017-11-10 0.0 2 2017-11-11 0.0 3 2017-11-12 4.0 4 2017-11-13 0.0 5 2017-11-14 5.0
answers question: http://stackoverflow.com/q/50608966
type: Answer
upvote count: 2
score: 2

functional-programming
tags question: http://stackoverflow.com/q/50680275
tag name: functional-programming
type: Tag
tags question: http://stackoverflow.com/q/50651619

http://stackoverflow.com/comment/88146870
has text: What is the type of the var 'Dropout'? Are we sure dropout works with masking? (I don't know)
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50567049

http://stackoverflow.com/q/50560526
tagged with: web-scraping
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50560581
accepted answer: http://stackoverflow.com/a/50560581
type: Question
upvote count: 2
answer count: 1
has body: I'm working with the following HTML snippet from a page on Goodreads using Python 3.6.3: “Don't cry because it's over, smile because it happened.” ― Dr. Seuss , I used BeautifulSoup to scrape the HTML and isolate just the "quoteText" class seen in the snippet above. Now, I want to save the quote and author name as separate strings. I was able to get the author name using (quote_tag.find(class_="quoteText")).text I'm not sure how to do the same for the quote. I'm guessing I need a way to remove the subclass from my output and tried using the extract method. quote.extract(class_="authorOrTitle") but I got an error saying extract got an unexpected keyword argument 'class_' Is there any other way to do what I'm trying to do? This is my first time posting on here so I apologize if the post doesn't meet particular specificity/formatting/other standards.
favorite count: 0
tagged with: beautifulsoup
has title: Extract subclass from class using beautifulsoup
downvote count: 1
tagged with: python

http://stackoverflow.com/q/50660042
downvote count: 0
has title: Creating a candlestick chart with multiple axes (not twin axis )
favorite count: 0
has comment: http://stackoverflow.com/comment/88331223
tagged with: pandas
tagged with: candlestick-chart
tagged with: python
tagged with: multiple-axes
answer count: 0
has body: I have created a candlestick chart that displays the percentage deviation from the moving average, with the percentage as the left side Y-Axis parameter. I want to plot the closing price that corresponds to those percentages( derived by a formula present in my code) on the right side Y-Axis. I am not looking for a twin axis, however. How can I go about doing this? Currently, I am able to make 2 subplots, with the candlestick on the upper plot and corresponding closing prices on the lower plot. This is my code: import datetime as dt import matplotlib.pyplot as plt from matplotlib import style import pandas as pd pd.core.common.is_list_like = pd.api.types.is_list_like import pandas_datareader.data as web import numpy as np from mpl_finance import candlestick_ohlc import matplotlib.dates as mdates from matplotlib.dates import DateFormatter, MonthLocator, YearLocator, DayLocator style.use( 'ggplot' ) start_year = int( input( 'Start year: ' ) ) start_month = int( input( 'Start month: ' ) ) #for months before October, only type in the corresponding digit without the 0 start_day = int( input( 'Start day: ' ) ) print() end_year = int( input( 'End year: ' ) ) end_month =int( input( 'End month: ' ) ) #for months before October, only type in the corresponding digit without the 0 end_day = int( input( 'End day: ' ) ) start = dt.datetime( start_year, start_month, start_day ) end = dt.datetime( end_year, end_month, end_day ) print() ticker = input( 'Ticker: ' ) #should be in Uppercase ticker = ticker.upper() df = web.DataReader( ticker, 'morningstar', start, end ) print() file_name = input( 'What\'s the csv file name that is stored on your device? ( ticker.csv ): ' ) #input should be in Lowercase .csv format file_name = file_name.lower() df.to_csv( file_name ) df = pd.read_csv( file_name, parse_dates=True, index_col=0 ) alldays = DayLocator() # minor ticks on the days weekFormatter = DateFormatter('%b %d %Y') # e.g., Jan 12 2018 dayFormatter = DateFormatter('%d') # e.g., 12 plt.s…
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/88331332
type: Question
score: 1
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/88330192

http://stackoverflow.com/a/50612770
score: 1
has body: Are you sure the length of Gene1 isn't 201? You don't say what you want to happen in the case where the length isn't divisible by the number of bins. My code mixes sublists of length floor(length/nBins) and ceiling(length/nBins) to get the right number of bins. new_data = {key : [value[ int(bin_number*len(value)/nBins): int((bin_number+1)*len(value)/nBins) ] for bin_number in range(nBins)] for key, value in myData.items()}
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88235660
type: Answer
accepted answer of: http://stackoverflow.com/q/50612386
answers question: http://stackoverflow.com/q/50612386
downvote count: 0

http://stackoverflow.com/q/50675730
tagged with: metaprogramming
type: Question
has comment: http://stackoverflow.com/comment/88361047
downvote count: 0
has comment: http://stackoverflow.com/comment/88361093
tagged with: setattr
has answer: http://stackoverflow.com/a/50676728
answer count: 1
tagged with: python
has title: define_method in Python
favorite count: 0
has comment: http://stackoverflow.com/comment/88361635
upvote count: 2
has body: I would like to dynamically define some methods for Python class. I googled for a while and found this. I changed the code a bit to fulfill my requirement. Here's my codes: class Base(object): def add_method(self, field): def func(self, value): self.colors[field] = value return self return func def define_method(self, *fields): for field in fields: setattr(self, "with_" + field, self.add_method(field)) class MyColor(Base): def __init__(self): self.colors = { "black": "000", "red": "f00", "green": "0f0" } # ========== ========== # by doing this, I assume `with_red()` and `with_green()` # will be generated, and they're chain-able. super(MyColor, self).define_method("red", "green") s = MyColor() s.with_red("111").with_green("222") print(s.colors) # should output: {"black": "000", "red": "111", "green": 222} The codes will raise error: Traceback (most recent call last): File "main.py", line 26, in &lt;module&gt; s.with_red("111").with_green("222") TypeError: _with_field() missing 1 required positional argument: 'value' What is wrong? Thanks for your time! ========== Edit ========== Sorry, I changed my original implementation on Base class, which is as below(has a bug, which always change the last field passed to define_method()). @Alex's answer stands. class Base: def define_method(self, *fields): for field in fields: def _with_field(self, value): self.colors[field] = value return self setattr(self, "with_" + field, _with_field)
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50676728
linked to: http://stackoverflow.com/q/5449244

http://stackoverflow.com/q/50579299
downvote count: 5
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/88167868
favorite count: 0
has body: I have a dataframe like that: time A time B 2017-11 2017-12 2018-01 2018-02 2017-01-24 2020-01-01 NaN NaN NaN NaN 2016-11-28 2020-01-01 NaN 4.0 2.0 2.0 2017-03-18 2017-12-21 NaN NaN NaN NaN I want replace all NaN to 0 when the column name between time A and time B. for example, for third row, the time range is from 2017-03-18 to 2017-12-21, so data at the third row with columns name between this range, if it is NaN, replace it with 0, otherwise remain as the same. Hopes its clear. Thanks
upvote count: 2
has answer: http://stackoverflow.com/a/50580354
score: -3
possible better answer: http://stackoverflow.com/a/50580004
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88167805
has answer: http://stackoverflow.com/a/50580004
tagged with: dataframe
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/50580354
has title: pandas dataframe replace NaN with 0 when column name in a certain date range
has comment: http://stackoverflow.com/comment/88167889

http://stackoverflow.com/comment/88234863
type: QuestionComment
comment on: http://stackoverflow.com/q/50612394
has text: Are you sure that `@asyncio.coroutine` is necessary?
score: 0
type: Comment

http://stackoverflow.com/q/50668651
tagged with: python
has comment: http://stackoverflow.com/comment/88347505
has answer: http://stackoverflow.com/a/50671733
score: 4
has comment: http://stackoverflow.com/comment/88349079
has comment: http://stackoverflow.com/comment/88356295
answer count: 1
tagged with: scipy
tagged with: performance
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88347846
has comment: http://stackoverflow.com/comment/88348912
upvote count: 4
tagged with: numpy
downvote count: 0
has comment: http://stackoverflow.com/comment/88347217
favorite count: 0
has title: Why scipy.distance.cdist has a big performance difference between using float32 (slower) and float64 (faster)?
has body: Why scipy.distance.cdist has a big performance difference between using float32 and float64? from scipy.spatial import distance import numpy as np import time a_float32 = np.empty((1000000, 512), dtype=np.float32) b_float32 = np.empty((1, 512), dtype=np.float32) a_float64 = np.empty((1000000, 512), dtype=np.float64) b_float64 = np.empty((1, 512), dtype=np.float64) t1 = time.time() for i in range(100): distance.cdist(a_float32, b_float32, "sqeuclidean") t2 = time.time() print(t2-t1) t1 = time.time() for i in range(100): distance.cdist(a_float64, b_float64, 'sqeuclidean') t2 = time.time() print(t2-t1) On my computer, this code produces a timing of 130.6998474597931 for float32 and 22.450339794158936 for float64, a whopping 6x difference. What is the reason for such a big difference with float64 being faster than float32? However the gap seems to become smaller and smaller if instead of b being np.empty((1, 512)), b is np.empty((k, 512)) with k (>1) becoming larger and larger. For example, when k=5, I get 222.25975680351257 for float32 and 110.36117148399353 for float64 (2x). Why the gap becomes smaller when k becomes larger?
type: Question

http://stackoverflow.com/a/50677830
answers question: http://stackoverflow.com/q/50677770
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50677770
downvote count: 0
type: Answer
score: 7
upvote count: 7
has body: Coerce the errors and dropna i.e: dates['Date'] = pd.to_datetime(dates['Date'],errors='coerce') dates.dropna(inplace=True)
has comment: http://stackoverflow.com/comment/88365191

http://stackoverflow.com/comment/88196554
type: AnswerComment
comment on: http://stackoverflow.com/a/50574998
score: 0
type: Comment
has text: The return statement cannot be before the try statement as the `root.destroy()` in the try statement is required to close the form. The return must be the last statement in `main()`.

http://stackoverflow.com/a/50584637
answers question: http://stackoverflow.com/q/50584072
type: Answer
upvote count: 1
has body: You can use the functional API to create a multi-output network. Essentially every output will be a separate prediction. Something along the lines of: in = Input(shape=(w,h,c)) # image input latent = Conv...(...)(in) # some convolutional layers to extract features # How share the underlying features to predict animal = Dense(2, activation='softmax')(latent) collar = Dense(2, activation='softmax')(latent) model = Model(in, [animal, coller]) model.compile(loss='categorical_crossentropy', optimiser='adam') You can have as many separate outputs you like. If you have only binary features you can have a single vector output as well, Dense(2, activation='sigmoid') and first entry could predict cat or not, while second whether it has a collar. This would be multi-class multi-label setup.
downvote count: 0
score: 1

http://stackoverflow.com/comment/88368727
score: 0
has text: Update the question with the _GeckoDriver_ console logs
type: QuestionComment
comment on: http://stackoverflow.com/q/50679623
type: Comment

http://stackoverflow.com/q/50641147
type: UnansweredQuestion
tagged with: local-security-authority
tagged with: python-sphinx
has comment: http://stackoverflow.com/comment/88292865
tagged with: python
has comment: http://stackoverflow.com/comment/88293454
has answer: http://stackoverflow.com/a/50642514
score: 1
has title: sphinx-build with -blinkcheck and custom CA
type: Question
downvote count: 0
has body: We have our own company wide certificate authority which we use to signa SSL certificates. Mostly, this is working fine as long as you have your OS (CentOS 7 in our case) register that authority. It is stored here: /etc/pki/ca-trust/source/anchors/company_ca.pem This allows Firefox/chrome to trust the SSL certificates that were signed via it. I am using sphinx-build -W -blinkcheck […] to check that the links in my Python project are still valid as link rot sucks in documentation. This is fine for all external links. However, when linking to our own SSL version of mantis (a bug tracker), I get a SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:579)'),))) error. Mantis, in our set up, only runs on https. How do I tell sphinx to add the company-wide authority? I run this generally via tox like thus: The tox fragement which runs this: [testenv:docs] basepython=python2.7 deps=-r{toxinidir}/requirements/requirements.txt commands=./check_docs.bash The bash script: #!/bin/bash set -eux sphinx-apidoc --force --separate --private --module-first -o docs src/ '*/*test*' cd docs pytest --maxfail=1 \ --tb=line \ -v \ --junitxml=junit_sphinx.xml \ --exitfirst \ --failed-first \ --full-trace \ -ra \ --capture=no \ check_sphinx.py And the pythons script: import subprocess def test_linkcheck(tmpdir): doctrees = tmpdir.join("doctrees") htmldir = tmpdir.join("html") subprocess.check_call([ "sphinx-build", "-W", "-blinkcheck", "-d", str(doctrees), ".", str(htmldir) ]) def test_build_docs(tmpdir): doctrees = tmpdir.join("doctrees") htmldir = tmpdir.join("html") subprocess.check_call([ "sphinx-build", "-W", "-bhtml", "-d", str(doctrees), ".", str(htmldir) ])
upvote count: 1
tagged with: certificate-authority
answer count: 1
favorite count: 0

http://stackoverflow.com/q/50659212
has title: How do I get the face_recognition encoding from many images in a directory and store them in a CSV File?
tagged with: python
accepted answer: http://stackoverflow.com/a/50680979
upvote count: 1
tagged with: loops
answer count: 1
tagged with: opencv
tagged with: encoding
has body: This is the code I have and it works for single images: Loading images and apply the encoding from face_recognition.face_recognition_cli import image_files_in_folder Image1 = face_recognition.load_image_file("Folder/Image1.jpg") Image_encoding1 = face_recognition.face_encodings(Image1) Image2 = face_recognition.load_image_file("Folder/Image2.jpg") Image_encoding2 = face_recognition.face_encodings(Image2) Face encodings are stored in the first array, after column_stack we have to resize Encodings_For_File = np.column_stack(([Image_encoding1[0]], [Image_encoding2[0]])) Encodings_For_File.resize((2, 128)) Convert array to pandas dataframe and write to csv Encodings_For_File_Panda = pd.DataFrame(Encodings_For_File) Encodings_For_File_Panda.to_csv("Celebrity_Face_Encoding.csv") How do I loop over the images in 'Folder' and extract the encoding into a csv file? I have to do this with many images and cannot do it manually. I tried several approaches, but none a working for me. Cv2 can be used instead of load_image_file?
tagged with: loadimage
has answer: http://stackoverflow.com/a/50680979
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88369491
type: Question

http://stackoverflow.com/comment/88099395
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50543932
has text: Yes tried. I can see the values but I need the them broken up into tuples so i can call the values out separately in later functions
score: 0

http://stackoverflow.com/a/50569195
answers question: http://stackoverflow.com/q/50569171
score: 13
upvote count: 13
has comment: http://stackoverflow.com/comment/88148374
has body: You can use len for length of dask DataFrame column or index: print (len(df_dask['A'])) 5 print (len(df_dask.index)) 5 Your solution is beter if need count all non NaNs values - add compute: df = pd.DataFrame(np.random.normal(0, 1, (5, 2)), columns=["A", "B"]) df.loc[0, 'A'] = np.nan print (df) A B 0 NaN -1.727669 1 -0.390900 0.573806 2 0.338589 -0.011830 3 2.392365 0.412912 4 0.978736 2.238143 import dask.dataframe as dd df_dask = dd.from_pandas(df, npartitions=3) print (df_dask['A'].count().compute()) 4
has comment: http://stackoverflow.com/comment/88148427
has comment: http://stackoverflow.com/comment/88148853
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/100649616

http://stackoverflow.com/a/50618032
answers question: http://stackoverflow.com/q/50617943
has comment: http://stackoverflow.com/comment/88254981
has body: What you are seeing is a default representation of the list sims. If you do print(sims[0]) then, if WorldCupSim.WorldCupSim has defined a string representation (which is what print() will show you) then you should see more useful stuff.
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88254846
accepted answer of: http://stackoverflow.com/q/50617943
upvote count: 2
type: Answer

http://stackoverflow.com/a/54642920
has body: Check if you've missed the configuration on your proj/proj/__init__.py as described in Celery Docs The file must have: from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',)
has comment: http://stackoverflow.com/comment/96119597
answers question: http://stackoverflow.com/q/50651736
score: 0
has comment: http://stackoverflow.com/comment/106249803
type: Answer

http://stackoverflow.com/comment/88332063
comment on: http://stackoverflow.com/q/50661005
score: 1
has text: `nums` probably has < 3 elements. The real questions is why not use `9 in nums`?
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50697171
answer count: 1
accepted answer: http://stackoverflow.com/a/50699366
has body: I'm having a problem converting the numpy variable to tf variable. The original code I'm trying to change is as follows from numpy import exp, array, random, dot training_set_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]]) training_set_outputs = array([[0, 1, 1, 0]]).T random.seed(1) synaptic_weights = 2 * random.random((3, 1)) - 1 for iteration in xrange(10000): output = 1 / (1 + exp(-(dot(training_set_inputs, synaptic_weights)))) synaptic_weights += dot(training_set_inputs.T, (training_set_outputs - output) * output * (1 - output)) print 1 / (1 + exp(-(dot(array([1, 0, 0]), synaptic_weights)))) I've edited some of the lines to be from numpy import exp, array, random, dot import tensorflow as tf import os dir =os.path.dirname(os.path.realpath('/Users/karnny/Desktop/Project')) training_set_inputs = tf.Variable([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]]) training_set_inputs_transpose = tf.transpose(training_set_inputs) training_set_outputs = tf.Variable([[0, 1, 1, 0]]) training_set_outputs_transpose = tf.transpose(training_set_outputs) random.seed(1) saver = tf.train.Saver() with tf.Session() as sess: sess.run(tf.global_variables_initializer()) #adjust weight weights = 2 * random.random((3, 1)) - 1 #train neural network for iteration in range(10000): output = 1 / (1 + exp(-(tf.tensordot(training_set_inputs, synaptic_weights,1)))) weights += tf.tensordot(training_set_inputs_transpose, (training_set_outputs_transpose - output) * output * (1 - output),1) saver.save(sess, dir + '/data-all') #test result print (1 / (1 + exp(-(dot(array([0, 1, 0]), synaptic_weights))))) print (1 / (1 + exp(-(dot(array([1, 1, 0]), synaptic_weights))))) print (1 / (1 + exp(-(dot(array([1, 0, 1]), synaptic_weights))))) print (1 / (1 + exp(-(dot(array([1, 0, 0]), synaptic_weights))))) print (1 / (1 + exp(-(dot(array([0, 0, 0]), synaptic_weights))))) There seems to be an error about the variable type on the 'output' variable. The error if as follows. TypeError: Input 'b' of 'MatM…
tagged with: python
has title: Converting numpy variables to tf variables for graph freezing purpose
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50699366
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/88403411
tagged with: numpy
score: 0
tagged with: deep-learning

http://stackoverflow.com/q/50552512
duplicate of: http://stackoverflow.com/q/142545
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: file
has comment: http://stackoverflow.com/comment/88115798
has title: How do I set the value of a dictionary that's on another file from another file?
has body: I want to change the value of the dictionary in another file file1.py a = {"a":"cat"} file2.py a["a"] = "dog"
type: Question
has comment: http://stackoverflow.com/comment/88115954
linked to: http://stackoverflow.com/q/142545
score: 0
has comment: http://stackoverflow.com/comment/88115817

http://stackoverflow.com/q/50600814
tagged with: firebase-realtime-database
tagged with: python
tagged with: firebase
type: AnsweredQuestion
has title: How to index and retrieve ordered firebase nested data (3 level) using Python
accepted answer: http://stackoverflow.com/a/50601139
has body: I have firebase json data with the below structure: Below is the index rule I have in Firebase: "rules": { "Trip": { ".indexOn": ["tripLastUpdateTimestamp"] } } And this is the Python code I used for retrieving the firebase data based on the trip_LastUpdateTimestamp: ref = db.reference('Trip') snapshot = ref.orderbychild('tripLastUpdateTimestamp').start_at(1527647100).end_at(1527647200).get() But the above code doesn't return any data. Can you guys please help me to fix this problem? would be really helpful if you guys let me know what I'm doing wrong.
type: Question
score: 0
has answer: http://stackoverflow.com/a/50601139
answer count: 1

http://stackoverflow.com/q/50558867
score: 1
has title: Python: random date generation
has comment: http://stackoverflow.com/comment/88128347
has comment: http://stackoverflow.com/comment/88128432
type: Question
type: AnsweredQuestion
has body: I want to generate random dates in the same format as the input, but no matter how many times I run the code, I want it to return the same random date, against each input value. I'm reading from csv file to a data frame as follows: in_df = pd.read_csv('file.txt',sep="\t", encoding='ISO-8859-1',usecols=['MY_DATE']) Input dataframe: MY_DATE 0 2015-11-30 1 2016-10-14 2 2015-11-20 Expected output after 1st call to function: MY_DATE 0 2018-10-22 1 2019-06-15 2 2007-09-01 Expected output after 2nd call to function, for the same input: MY_DATE 0 2018-10-22 1 2019-06-15 2 2007-09-01 2015-11-30 results in, say, 2018-10-22 on first run, but doesn't result in the same date when I rerun it, even after setting the prop as global. Here's my code snippet: global prop prop= random.random() def gen_exp_dt(prop,start_dttm, end_dttm, format=None): stime = time.mktime(time.strptime(start_dttm,format)) etime = time.mktime(time.strptime(end_dttm, format)) rtime = stime + (prop * (etime - stime)) return time.strftime(format, time.localtime(rtime)) Any suggestions?
upvote count: 2
has comment: http://stackoverflow.com/comment/88128413
has comment: http://stackoverflow.com/comment/88128456
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50559063
accepted answer: http://stackoverflow.com/a/50559063
has comment: http://stackoverflow.com/comment/88128536
tagged with: python
has comment: http://stackoverflow.com/comment/88128445

http://stackoverflow.com/a/50685780
has comment: http://stackoverflow.com/comment/88382685
has body: An O(n) solution would be: child_parent = {1:2, 3:1, 4:1, 5:2, 1:5, 6:5, 7:2} parent_children = {} for child, parent in child_parent.items(): parent_children.setdefault(parent, []).append(child) giving: {5: [1, 6], 1: [3, 4], 2: [5, 7]} And, for ease of evaluation, the data represents the following tree: 2 / \ 7 5 / \ 6 1 / \ 3 4
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88382283
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50684578

http://stackoverflow.com/q/50547179
downvote count: 0
answer count: 1
favorite count: 0
tagged with: weak-references
tagged with: python-3.x
upvote count: 2
has title: How can I get a weak reference to the send method of a generator?
has answer: http://stackoverflow.com/a/50547247
tagged with: python
tagged with: generator
score: 2
type: AnsweredQuestion
has body: The weakref documentation doesn't seem to provide a method for creating a weak reference to the send method of a generator: import weakref def gen(): yield g=gen() w_send=weakref.ref(g.send) w_send() # &lt;- this is None; the g.send object is ephemeral I didn't think it would work but I did try the weakref.WeakMethod just in case as well: &gt;&gt;&gt; w_send=weakref.WeakMethod(g.send) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\ricky\AppData\Local\Programs\Python\Python37\lib\weakref.py", line 50, in __new__ .format(type(meth))) from None TypeError: argument should be a bound method, not &lt;class 'builtin_function_or_method'&gt; How can this be done without wrapping the generator in a custom class? Like this: import weakref def gen(): yield class MyGenerator: def __init__(self): self._generator = gen() def send(self, arg): return self._generator.send(arg) g = MyGenerator() ref = weakref.WeakMethod(g.send) I don't want to do this. Is there a better way? The reason I want to do this is I am working on an idea for a simple messaging protocol for an app I might build. The messaging looks something like this: # messaging module from typing import Generator from functools import wraps from collections import NamedTuple import weakref class Message(NamedTuple): channel: int content: str _REGISTRY = {} def _do_register(channel, route): # handle bound methods if hasattr(route,"__self__") and hasattr(route,"__func__"): route_ref = weakref.WeakMethod(route) # handle generators elif isinstance(route, Generator): route_ref = weakref.ref(route.send) # get weak ref to route.send here # all other callables else: route_ref = weakref.ref(route) try: _REGISTRY[channel].add(route_ref) except KeyError: _REGISTRY[channel] = {route_ref} def register(obj=None, *, channel, route=None): """Decorator for registering callable objects for messaging.""" if obj is None: def wrapper(callable): @wraps(callable) def wrapped(*args, **kwargs): non…
has comment: http://stackoverflow.com/comment/88105147
type: Question
accepted answer: http://stackoverflow.com/a/50547247
has comment: http://stackoverflow.com/comment/88106398

http://stackoverflow.com/comment/88247055
comment on: http://stackoverflow.com/a/50615190
type: AnswerComment
score: 1
type: Comment
has text: Rather than a bare `except`, specify the exception types that you'd expect to be raised (e.g. `AttributeError`). If you need to catch multiple exception types, you can specify a parenthesized tuple of them (e.g. `except (AttributeError, IndexError):` or whatever).

http://stackoverflow.com/comment/88291090
type: QuestionComment
has text: I also tried `max` and `tuple`, `max` behave same as `sum`.But `tuple` is different from `sum`.There is no **iter** operation in `tuple`.I think the built-in function involve **iter** operation is different.@tobias_k
score: 0
comment on: http://stackoverflow.com/q/50637863
type: Comment

http://stackoverflow.com/comment/118188351
comment on: http://stackoverflow.com/a/50572526
type: Comment
score: 0
type: AnswerComment
has text: Is there a way to do it without specifying the file name?

protocol-buffers
tags question: http://stackoverflow.com/q/50553628
tag name: protocol-buffers
type: Tag
tags question: http://stackoverflow.com/q/50627125
tags question: http://stackoverflow.com/q/50582470

http://stackoverflow.com/q/50580188
has title: How to achieve something like VBA's "Range.Find" using win32?
has comment: http://stackoverflow.com/comment/88172556
linked to: http://stackoverflow.com/q/47204701
upvote count: 6
has answer: http://stackoverflow.com/a/50584834
accepted answer: http://stackoverflow.com/a/50584834
has body: I'm looking to achieve functionality similar to the Range.Find method in VBA using win32com package in Python. I'm dealing with an Excel CSV file. While I have found lots of solutions using range(), it seems to require specifying a fixed range of cells, as opposed to Range.Find in VBA, which will auto search in worksheet without fixing the range. Here is my code: import win32com.client as client excel= client.dynamic.Dispatch("Excel.Application") excel.visible= True wb= excel.workbooks.open(r"ExcelFile.xls") ws= wb.worksheets('First') ### This able to extract information: test_range= ws.Range("A1") ### Got issue AttributeError: 'function' object has no attribute 'Find': test_range= ws.Range.Find("Series ID") print(test_range.value) Does it mean Range.Find method does not supported in win32 package or I point it with the wrong existing module?
has answer: http://stackoverflow.com/a/50582535
has comment: http://stackoverflow.com/comment/88178831
has comment: http://stackoverflow.com/comment/88170050
tagged with: python
has answer: http://stackoverflow.com/a/70844388
has comment: http://stackoverflow.com/comment/88169576
answer count: 4
favorite count: 0
downvote count: 9
possible better answer: http://stackoverflow.com/a/50581758
score: -3
has answer: http://stackoverflow.com/a/50581758
tagged with: excel
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88169973
type: Question
has comment: http://stackoverflow.com/comment/88179203
has comment: http://stackoverflow.com/comment/88170117

http://stackoverflow.com/comment/88109010
type: Comment
type: QuestionComment
has text: Added an else statement to go to the dosomething html with check, still does the same thing. It still has a post request on page load.
comment on: http://stackoverflow.com/q/50548962
score: 0

http://stackoverflow.com/a/50568116
downvote count: 0
has comment: http://stackoverflow.com/comment/88146467
has body: OK I made some searches here on SO and found: https://stackoverflow.com/a/24045425/7386332 The equivalent here would simply be as 0 evaluates to False inside the comprehension. import pandas as pd df = pd.DataFrame({ 'id': ['01','02','03'], 'Apple': [1,0,0], 'Apricot': [1,0,0], 'Banana': [0,1,0], 'Climentine': [0,1,0], 'Orange': [0,1,1], 'Pear': [0,1,0], 'Pineapple': [0,0,1] }) df = (df.set_index('id') .apply(lambda row: ', '.join([col for col, b in zip(df.columns, row) if b]), axis=1) .reset_index()) Time comparison Small set (the above) 1.37 ms ± 4.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) # list comprehensio 1.41 ms ± 2.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) # df.dot 3.28 ms ± 81.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) # df.melt Using (df = pd.concat([df]*1000)) to simulate larger set: 36.9 ms ± 137 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) # df.dot 39.8 ms ± 369 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) # df.melt 84.5 ms ± 215 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) # list comprehension
has comment: http://stackoverflow.com/comment/88146525
upvote count: 2
answers question: http://stackoverflow.com/q/50559480
has comment: http://stackoverflow.com/comment/88146274
has comment: http://stackoverflow.com/comment/88146291
type: Answer
score: 2

http://stackoverflow.com/comment/88213327
comment on: http://stackoverflow.com/a/50602026
score: 1
type: AnswerComment
type: Comment
has text: `default=0` is the second part of the answer. The first part is to make the field optional in the form with `required=False`, or in the model with `blank=True`.

http://stackoverflow.com/comment/88388262
type: Comment
has text: So by reading in the csv, you create a bunch of new tickets. You're not checking if these tickets are in the database already whatsoever, so how should sql-alchemy know?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50689189

http://stackoverflow.com/a/56429102
upvote count: 6
answers question: http://stackoverflow.com/q/50649853
downvote count: 0
has body: It happens when common column in both table are of different data type. Example: In table1, you have date as string whereas in table2 you have date as datetime. so before merging,we need to change date to common data type.
type: Answer
score: 6

http://stackoverflow.com/q/50636711
has answer: http://stackoverflow.com/a/50636754
favorite count: 0
has body: Consider i have two pandas dataframe df = pd.DataFrame() df['r_no'] = [1,1,1,2,3,1,1,1,2] df['user'] = ['sam','sam','sam','sam','peter','jack','jack','Kris','peter'] df['value'] = [76,76,7,8,8,2,29,2,8] df['cam_id'] = ['ab','abc','ab','ab','ab','abcd','abcd','abcd','ab'] df_2 = pd.DataFrame() df_2['r_no'] = [1,3,2,2,4,1,1,3,2,5,7,2,8,9,3] df r_no user value cam_id 0 1 sam 76 ab 1 1 sam 76 abc 2 1 sam 7 ab 3 2 sam 8 ab 4 3 peter 8 ab 5 1 jack 2 abcd 6 1 jack 29 abcd 7 1 Kris 2 abcd 8 2 peter 8 ab df_2 r_no 0 1 1 3 2 2 3 2 4 4 5 1 6 1 7 3 8 2 9 5 10 7 11 2 12 8 13 9 14 3 Expected Output A new column in df dataframe df['count_greaterandequal'] 0 3 1 3 2 3 3 7 4 10 5 3 6 3 7 3 8 7 to calculate the number for r_no in df---dataframe has been equal to or greater than in df_2---dataframe
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50636754
downvote count: 2
upvote count: 1
type: Question
tagged with: numpy
tagged with: dataframe
has title: Compare each value of a Series against every other value from another Series in pandas
score: -1
tagged with: pandas
answer count: 1

http://stackoverflow.com/a/50604685
has body: Going AJAX might be a solution, download the file via AJAX, then initiate redirection after download complete. AJAX download can be eased using JQuery or related plugins, a post for reference. Redirection can be achieved on success at client side like below. $.fileDownload('some/file.pdf') .done(function () { window.location.href = 'REDIRECT_URL'; }) .fail(function () { alert('File download failed!'); });
type: Answer
accepted answer of: http://stackoverflow.com/q/50604257
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50604257
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/50636307
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88283228
type: Question
accepted answer: http://stackoverflow.com/a/50922886
tagged with: pandas
answer count: 1
downvote count: 0
has title: How to calculate summary statistics for certain consecutive day ranges
has body: I have a dataset (DATE_LOCATION, Sold) which has products sold on various dates. The dates are being given for 9 months with random 13 days or more from a month. I have to segregate the data in a such a way that the for the product how many products were sold continuously for 1-3 days, sold continuously for 4-7 given days, sold continuously for 8-15 given days and sold continuously for>16 days. So how can I code this in python using pandas and other packages DATE_LOCATION Sold 07-08-16 0:00 2 08-08-16 0:00 7 12-08-16 0:00 3 13-08-16 0:00 1 14-08-16 0:00 2 15-08-16 0.00 1 . . . 22-10-16 0:00 1 23-10-16 0:00 2 26-10-16 0:00 1 28-10-16 0:00 1 29-10-16 0:00 3 30-10-16 0:00 3 . . .(goes for 9 months of data) . I don't know even how to code for this in python The output needed is Days Sold 1-3 20 #(7,8),(22,23),(26),(28,29,30) dates because the range is [1,3] 4-7 7 #(12,13,14,15) dates because the range is [4,7] 8-15 0 &gt;16 0 Would be happy if at least someone posted a link to where to start. I tried df["DATE_LOCATION"] = pd.to_datetime(df.DATE_LOCATION) df["DAY"] = df.DATE_LOCATION.dt.day def flag(x): if 1&lt;=x&lt;=3: return '1-3' elif 4&lt;=x&lt;=7: return '4-7' elif 8&lt;=x&lt;=15: return '8-15' else: return '&gt;=16' df["Days"] = df.DAY.apply(flag) df["Days"].Sold.sum() This gave me the number of products sold between these days in each month. But I need the sum of the products for the specified range where the products are sold in a streak specified.
favorite count: 0
tagged with: python-3.x
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/88283429
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50922886

http://stackoverflow.com/q/50661107
has comment: http://stackoverflow.com/comment/88333775
tagged with: pylint
tagged with: python
has comment: http://stackoverflow.com/comment/88333695
score: 2
has comment: http://stackoverflow.com/comment/88385234
tagged with: python-3.x
answer count: 0
upvote count: 2
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/50612169
has comment: http://stackoverflow.com/comment/88333573
has comment: http://stackoverflow.com/comment/88333656
type: Question
linked to: http://stackoverflow.com/q/31907762
has comment: http://stackoverflow.com/comment/88423272
has comment: http://stackoverflow.com/comment/88387022
tagged with: visual-studio-code
has title: PyLint Shows Lots of Errors on Visual Studio Code
has body: While working on a Python script in which I had to import opencv, VSCode throws a lot of errors whenever I call the opencv package for any function. Is there something I haven't set up on my editor? Thanks for any help.
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/50634291
has comment: http://stackoverflow.com/comment/88278855
has comment: http://stackoverflow.com/comment/88278676
type: Question
score: 0
has title: Word within a Nested list python
has answer: http://stackoverflow.com/a/50634326
has answer: http://stackoverflow.com/a/50634316
has body: I have a nested list. I need to check whether a particular string is in an element on the list - How do I do it? I am checking if "boy" is in list[0] list = [["I am a boy"],["I am a girl"]] print (list[0]) if "boy" in list[0]: print ("You got it")
answer count: 4
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50634386
tagged with: python
has answer: http://stackoverflow.com/a/50634395

http://stackoverflow.com/a/50656305
type: Answer
has comment: http://stackoverflow.com/comment/88324827
answers question: http://stackoverflow.com/q/50656058
score: 0
has body: You can try this Xpath : //a[contains(text(),'Cultures and Identities')]/ancestor::div[contains(@class,'field-title')]/following-sibling::div[contains(@class,'start')]/span
has comment: http://stackoverflow.com/comment/88324881

http://stackoverflow.com/q/50667928
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50667954
has title: remove character in series with replace
score: 0
has answer: http://stackoverflow.com/a/50668314
has comment: http://stackoverflow.com/comment/88349188
type: Question
answer count: 2
tagged with: replace
tagged with: pandas
has body: I have a series that looks like following: datum 02-jun-18 01-jun-18 01-jun-18 30-maj-18 30-maj-18 29-maj-18 27-maj-18 25-maj-18 25-maj-18 25-maj-18 14-maj-18 I want to remove the days on each row but keep the month and year with the follwing code: df['datum']=df['datum'].replace(df['datum'][0:2],' ') But it does not work. Can anyone explain why and how I can tackle this problem?
tagged with: series
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88345638

http://stackoverflow.com/comment/88110959
type: QuestionComment
comment on: http://stackoverflow.com/q/50549910
type: Comment
has text: I understand and I know it should but I'm telling you it doesn't work. Copy code and try to do this yourself.
score: 0

http://stackoverflow.com/q/50648367
score: 4
tagged with: multithreading
has comment: http://stackoverflow.com/comment/88313408
tagged with: pyqt5
has answer: http://stackoverflow.com/a/50650306
tagged with: qt
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88309493
type: Question
upvote count: 4
has body: I know that in general, QObject() instances should be created in the main thread. I also know that - once created - you can move a QObject() from the main thread to another one: official Qt docs can be found here # Worker-object approach # ----------------------- # Note: these codelines execute in the main thread. workerThread = QThread() workerObj = WorkerObj() workerObj.moveToThread(workerThread) &nbsp; Currently I am facing the exact opposite problem. I have a QObject() instantiated in a (non-main) QThread. I want to move it to the main thread, like this: # Move a QObject() to the main thread # ------------------------------------ # Note: these codelines execute in some QThread myObj = QObject() myObj.moveToThread(threading.main_thread()) I get the following error: TypeError: moveToThread(self, QThread): argument 1 has unexpected type '_MainThread' I probably get the error because the main thread is not a genuine QThread. What should I do to make it work? EDIT: Apparently the answer was right in the documentation of the moveToThread() function. This is pretty embarrassing. My sincere apologies. I'll be more careful next time.
has comment: http://stackoverflow.com/comment/88308767
answer count: 1
has comment: http://stackoverflow.com/comment/88308797
downvote count: 0
accepted answer: http://stackoverflow.com/a/50650306
has comment: http://stackoverflow.com/comment/88311029
tagged with: qt5
favorite count: 0
has title: PyQt5: How to move a QObject to the main thread?
tagged with: python

http://stackoverflow.com/a/50632571
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/50632506
score: 1
has body: Use numpy.ndarray.tolist(trajectory_features) to convert your numpy array into a regular list containing your floats.
upvote count: 1

http://stackoverflow.com/comment/88395645
comment on: http://stackoverflow.com/q/50693031
score: 1
has text: Can you confirm what it is you're looking for?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88355072
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50672643
score: 0
has text: Are you asking to perform what Excel calls a VLOOKUP inside of pandas?

http://stackoverflow.com/a/50677542
score: 0
has body: If you aren't set on using with smtplib, then I would recommend SendGrid for sending emails (if you send &lt; 100 emails/day then it's free). import sendgrid from sendgrid.helpers.mail import * sg = sendgrid.SendGridAPIClient(apikey=sendgrid_api_key) from_email = Email("test@example.com") to_email = Email("test@example.com") subject = "Sending with SendGrid is Fun" content = Content("text/plain", "content") mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) print(response.status_code)
type: Answer
has comment: http://stackoverflow.com/comment/88442526
answers question: http://stackoverflow.com/q/50674347
has comment: http://stackoverflow.com/comment/88412714

http://stackoverflow.com/comment/93668617
has text: perhaps add `HEADER` after the with ?
comment on: http://stackoverflow.com/q/50570865
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50557963
has comment: http://stackoverflow.com/comment/88126800
type: AnsweredQuestion
has title: Why does `pip install` seem to change the interpreter line on some machines?
has answer: http://stackoverflow.com/a/50558082
tagged with: pypi
type: Question
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/88126754
has body: I put my colorize.py package onto PyPi and discovered the following strange behavior. If I download the colorize.py-0.9.1.tar.gz from the project page, and I examine the first line of colorize.py, I get the following output: $ wget https://files.pythonhosted.org/packages/91/d8/805853c14a8ccf67ddfe2cf41b634395ef69a1138a0dade303bf4b7c9b45/colorize.py-0.9.1.tar.gz $ tar xvfz colorize.py-0.9.1.tar.gz $ head -n1 colorize.py-0.9.1/colorize.py #!/usr/bin/env python However, on the same my Ubuntu 16.04.4 LTS laptop, if I install using pip, the first line is has been replaced: $ pip install colorize.py $ head -n1 $(which colorize.py) #!/usr/bin/python On the other hand, my friend runs the same installation command on her OS X laptop, and gets the original interpreter line. What is going on here, and is it possible to force pip to not change the interpreter line when performing installation?
accepted answer: http://stackoverflow.com/a/50558082
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/40718770
favorite count: 0
tagged with: pip
tagged with: python

http://stackoverflow.com/a/50582770
has body: You do not need to use lookarounds, use an optional group: ABC(?:[BC]*C)?BA See the regex demo. Details ABC - an ABC substring (?:[BC]*C)? - a non-capturing group matching 0 or more occurrences of B or C chars followed with a C letter BA - a BA substring. This will effectively match AB that can only be followed with C and then any number of B or C letters (but this steak of chars is optional) followed with CBA. Note that depending on what you are doing with the pattern, a capturing group will also do, ABC([BC]*C)?BA.
upvote count: 2
answers question: http://stackoverflow.com/q/50582040
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50582040
has comment: http://stackoverflow.com/comment/88176940
has comment: http://stackoverflow.com/comment/88176918
type: Answer
has comment: http://stackoverflow.com/comment/88176703
downvote count: 0
score: 2

eclipse
tag name: eclipse
tags question: http://stackoverflow.com/q/50640450
tags question: http://stackoverflow.com/q/50697557
type: Tag

http://stackoverflow.com/comment/88314726
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50651841
has text: Second, is this something you're doing one time, or zillions of times? If you're doing it repeatedly, you probably want to build an index and search that. Exactly what that means depends on what the format is and what kinds of search you're trying to do. For example, full-word dictionary searches are a trivial tree search (or maybe a bloom filter in front of subtrees), while general text searches are a hard problem but with known solutions you can just drop in if you're happy with the "80% good enough" answer.

http://stackoverflow.com/a/50599516
type: AcceptedAnswer
score: 0
type: Answer
has body: Following the suggestions in the comments I have written the following code: def f(x, y, points): points = sorted(points) xunique = np.unique([point[0] for point in points]) yunique = np.unique([point[1] for point in points]) xmax = np.max(xunique) ymax = np.max(yunique) deltax = xunique[1] - xunique[0] deltay = yunique[1] - yunique[0] x0 = xunique[0] y0 = yunique[0] ni = len(xunique) nj = len(yunique) i1 = int(np.floor((x-x0)/deltax)) if i1 == ni: i1 = i1 - 1 i2 = int(np.ceil((x-x0)/deltax)) if i2 == ni: i2 = i2 - 1 j1 = int(np.floor((y-y0)/deltay)) if j1 == nj: j1 = j1 - 1 j2 = int(np.ceil((y-y0)/deltay)) if j2 == ni: j2 = j2 - 1 pp=[] if (i1==i2): if i1&gt;0: i1=i1-1 else: i2=i2+1 if (j1==j2): if j1&gt;0: j1=j1-1 else: j2=j2+1 pp=[points[i1 * nj + j1], points[i1 * nj + j2], points[i2 * nj + j1], points[i2 * nj + j2]] (x1, y1, q11), (_x1, y2, q12), (x2, _y1, q21), (_x2, _y2, q22) = pp return (q11 * (x2 - x) * (y2 - y) + q21 * (x - x1) * (y2 - y) + q12 * (x2 - x) * (y - y1) + q22 * (x - x1) * (y - y1)) / ((x2 - x1) * (y2 - y1))
answers question: http://stackoverflow.com/q/50585504
accepted answer of: http://stackoverflow.com/q/50585504

http://stackoverflow.com/q/50571570
downvote count: 0
favorite count: 0
has title: Change specific values in a Pandas DataFrame (where there are mixed types)
tagged with: python
has answer: http://stackoverflow.com/a/50571619
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50572080
type: Question
accepted answer: http://stackoverflow.com/a/50571619
tagged with: dataframe
has answer: http://stackoverflow.com/a/50571780
score: 4
has body: I have a pandas dataframe and I would like to increase any value greater than zero by some increment (say, .001), but only in a subset of columns. df=pd.DataFrame({'a': ['abc', 'abc', 'abc', 'abc'], 'b': [2,np.nan, 0, 6], 'c': [1, 0, 2, 0]}) a b c 0 abc 2.0 1 1 abc NaN 0 2 abc 0.0 2 3 abc 6.0 0 So I tried this: df[df.loc[:,['b', 'c']]&gt;0]+=1 TypeError: Cannot do inplace boolean setting on mixed-types with a non np.nan value However, because the first column is has an object dtype, I cannot do this as you can see by the error. The desired output would be: a b c 0 abc 2.001 1.001 1 abc NaN 0 2 abc 0.0 2.001 3 abc 6.001 0 Is there some way to do this kind of thing without explicitly looping through each column separately? I believe I am just missing a simple approach but cannot seem to find an example.
upvote count: 4
answer count: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50571780

http://stackoverflow.com/q/50686430
type: Question
upvote count: 0
has body: This is for a project at school, and I'm quite new to coding in python. Basically, I am making a program that prints a set amount of 'X's and spaces, like X X X X X... However, I want the user to choose how many 'X's and spaces they want to print. This is all I've done so far: xnum = input("Choose the amount of 'X's you would like to be printed") xnum = xnum.upper() spacenum = input("Choose the amount of spaces you would like to be printed") linenum = input("Choose how many characters you would like to be displayed on one line") I want to find out how to make the program print the number of 'X's the user asks for, and same with the spaces. PS: I already have the code for how many characters per line, I just need some help on printing the set amount of 'X's and spaces.
score: -2
answer count: 1
accepted answer: http://stackoverflow.com/a/50692633
has comment: http://stackoverflow.com/comment/88383986
has title: Printing a set amount of characters
favorite count: 0
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/88382866
has answer: http://stackoverflow.com/a/50692633
has comment: http://stackoverflow.com/comment/88382539
type: AnsweredQuestion
tagged with: pyscripter
has comment: http://stackoverflow.com/comment/88383122

http://stackoverflow.com/q/50665990
type: AnsweredQuestion
has title: Exporting to CSV File
score: 1
has answer: http://stackoverflow.com/a/50666216
has answer: http://stackoverflow.com/a/50666420
type: Question
tagged with: export-to-csv
answer count: 2
possible better answer: http://stackoverflow.com/a/50666216
downvote count: 0
accepted answer: http://stackoverflow.com/a/50666420
favorite count: 0
tagged with: beautifulsoup
tagged with: web-scraping
upvote count: 1
tagged with: python
has body: I'm trying to export the results of this code to a CSV file. I copied 2 of the results further down below after the code. There are 14 items for each stock and I'd like to write to a CSV file and have a column for each of the 14 items and one row for each stock. import requests from bs4 import BeautifulSoup base_url = 'http://finviz.com/screener.ashx?v=152&amp;s=ta_topgainers&amp;o=price&amp;c=0,1,2,3,4,5,6,7,25,63,64,65,66,67' html = requests.get(base_url) soup = BeautifulSoup(html.content, "html.parser") main_div = soup.find('div', attrs = {'id':'screener-content'}) table = main_div.find('table') sub = table.findAll('tr') rows = sub[5].findAll('td') for row in rows: link = row.a if link is not None: print(link.get_text()) This is the format of the results, 14 items/columns for each stock. PTN Palatin Technologies, Inc. Healthcare Diagnostic Substances USA 240.46M 9.22 193.43M 2.23M 0.76 1.19 7.21% 1,703,285 3 LKM Link Motion Inc. Technology Application Software China 128.95M - 50.40M 616.76K 1.73 1.30 16.07% 1,068,798 4 Tried this but couldn't get this to work. TextWriter x = File.OpenWrite ("my.csv", ....); x.WriteLine("Column1,Column2"); // header x.WriteLine(coups.Cells[0].Text + "," + coups.Cells[1].Text);

http://stackoverflow.com/comment/89134819
comment on: http://stackoverflow.com/q/50610342
score: 0
has text: @Carlos more times that I can count, my friend.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88329596
comment on: http://stackoverflow.com/a/50659644
has text: It sounds like they might have counted the characters in ` ` and tried to strip the whole tag off with string slicing, in which case they should probably be using `x.string` instead of slicing.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50546067
accepted answer of: http://stackoverflow.com/q/50546012
answers question: http://stackoverflow.com/q/50546012
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: nope.. I get it.. c.execute("INSERT INTO userInfo (username, password, authority, name, surname, idnum) " VALUES is making this error.. I hate this when I post my question here (I post here atleast after thinking 1 hour about it) I immedietly find the answer...
score: 1
upvote count: 1

http://stackoverflow.com/a/50644039
score: 1
answers question: http://stackoverflow.com/q/50642098
upvote count: 1
has body: You might be interested in a stacked area plot. This should work on your DataFrame, named df: df.drop(columns='age').plot(kind='area', stacked=True) One issue is that legend items will show up in reverse order compared to the vertical ordering of the plot areas. To fix this, you can manually reverse the legend handles and labels: ax = plt.gca() leg_handles, leg_labels = ax.get_legend_handles_labels() ax.legend(leg_handles[::-1], leg_labels[::-1]) Here's some example data (post text, not images, so we can easily copy-paste and experiment :)): df = pd.DataFrame({'age': [1, 2, 3], 'Class1': [22, 14, 26], 'Class2': [14, 15, 14], 'Class3': [64, 71, 60] }) Output: To reverse the vertical order in the plot so that Class 1 ends up at the top, sort the columns (axis=1) in descending order before plotting: df.drop(columns='age').sort_index(axis=1, ascending=False)plot(kind='area', stacked=True)
type: Answer
downvote count: 0

http://stackoverflow.com/comment/88295018
has text: I forgot endfor. I will add it in few minutes
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50641183
type: AnswerComment

http://stackoverflow.com/q/50575957
tagged with: http://stackoverflow.com/tag/pdf
has answer: http://stackoverflow.com/a/50576769
has title: How to robustly extract author names from pdf papers?
favorite count: 0
linked to: http://stackoverflow.com/q/34837707
has answer: http://stackoverflow.com/a/50576045
has comment: http://stackoverflow.com/comment/88199075
type: UnansweredQuestion
tagged with: python
tagged with: nlp
linked to: http://stackoverflow.com/q/26283715
tagged with: named-entity-recognition
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/88185252
has answer: http://stackoverflow.com/a/50576478
has body: I'd like to extract author names from pdf papers. Does anybody know a robust way to do so? For example, I'd like to extract the name Archana Shukla from this pdf https://arxiv.org/pdf/1111.1648
score: 0
downvote count: 4
answer count: 3
tagged with: information-extraction

http://stackoverflow.com/comment/139844353
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50635014
has text: There is a method to eliminate subsets from a list of sets [here](https://stackoverflow.com/a/14107790/1089161).
type: AnswerComment

http://stackoverflow.com/q/50670669
answer count: 3
has comment: http://stackoverflow.com/comment/88351159
has answer: http://stackoverflow.com/a/50671188
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50670987
linked to: http://stackoverflow.com/q/937000
tagged with: binary-search-tree
tagged with: return
has comment: http://stackoverflow.com/comment/88351163
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50670990
has comment: http://stackoverflow.com/comment/88351923
tagged with: python
tagged with: recursion
score: 2
has comment: http://stackoverflow.com/comment/88351371
has comment: http://stackoverflow.com/comment/88351193
upvote count: 2
has body: Before asking, I searched out some old questions and get a better idea to put the "return" in front of the inside re-invocated the function to get the expected result. some of them like: How to stop python recursion Python recursion and return statements. But when I do the same thing with my problem, it gets worse. I have a Binary Search Tree and want to get the TreeNode instance by given a node's key, so it looks an easier traversal requirement and I already easily realized similar functions below, with which I did NOT put return in front of the function: #preorder_List=[] def preorder(treeNode): if treeNode: preorder_List.append(treeNode.getKey()) preorder(treeNode.has_left_child()) preorder(treeNode.has_right_child()) return preorder_List so for my new requirement, I compose it like below first: def getNode(treeNode,key): if(treeNode): if(treeNode.key==key): print("got it=",treeNode.key) return treeNode else: getNode(treeNode.left_child(),key) getNode(treeNode.right_child(),key) then the issue occurs, it finds the key/node but kept running and report a None error finally and then I put return in front of the both left and right branch like below: def getNode(treeNode,key): if(treeNode): if(treeNode.key==key): print("got it=",treeNode.key) return treeNode else: return getNode(treeNode.left_child(),key) return getNode(treeNode.right_child(),key) but this makes the thing worse, it did reach the key found and return None earlier. Then I tried to remove one "return" for the branch, no matter right or left. It works (Update: this worked when my test case contains only 3 nodes, when I put more nodes, it didn't work, or to say if the expected node is from right, then put return in front of right branch invocation works, for left one, it didn't). What's the better solution?
has comment: http://stackoverflow.com/comment/88351135
type: Question
has comment: http://stackoverflow.com/comment/88351358
has title: Return or not return in a recursive function
linked to: http://stackoverflow.com/q/35273905
tagged with: search

http://stackoverflow.com/comment/88186088
has text: The `receive_timeout` argument exists in v1.1.2 and above of ldap3. It sounds as though your AWS deployment may have picked up an earlier version of ldap3.
score: 0
comment on: http://stackoverflow.com/q/50586947
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50607851
linked to: http://stackoverflow.com/q/45894261
tagged with: windows
has title: Install W10 Store apps from CLI
has comment: http://stackoverflow.com/comment/88225716
tagged with: cmd
score: 1
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: store
upvote count: 1
tagged with: python
has body: I'm making a little python script that automatically downloads and install certain apps from the store to not to forget some of them in case i format my pc. Is there a way to install those app from cmd/powershell so i can call this in python?
type: Question
downvote count: 0
tagged with: powershell

http://stackoverflow.com/a/50625892
has body: Just keep track of how many lines you need to skip as you are reading line by line, and decrement that value if it is &gt; 0 with open('test.csv') as f: rd = csv.reader(f, delimiter=' ');next(rd) # skips header skip = 0 for i, j in rd: if not skip: skip = 0 if int(j) &lt; 2 else int(j) print(i, j) else: skip -= 1 Output for your sample input: A 1 A 1 A 1 A 2 A 3 The 2 lines after A 2 and the three lines after A 3 are all skipped.
has comment: http://stackoverflow.com/comment/88263262
answers question: http://stackoverflow.com/q/50625680
has comment: http://stackoverflow.com/comment/88264829
has comment: http://stackoverflow.com/comment/88264868
has comment: http://stackoverflow.com/comment/88263520
downvote count: 0
has comment: http://stackoverflow.com/comment/88263758
type: Answer
has comment: http://stackoverflow.com/comment/88264052
score: 3
upvote count: 3

tcp
type: Tag
tags question: http://stackoverflow.com/q/50631905
tag name: tcp

http://stackoverflow.com/a/50589207
type: AcceptedAnswer
has body: IIUC, there is no need for a loop. The following creates a new column called new_TripID based on 2 conditions: That the original TripID changes from one row to the next, or that the difference in your time column is greater than one df['new_TripID'] = ((df['TripID'] != df['TripID'].shift()) | (df.time.diff() &gt; 1)).cumsum() &gt;&gt;&gt; df TripID Lat Lon time delta_t new_TripID 0 1 53.55 9.99 74 1.0 1 1 1 53.58 9.99 75 1.0 1 2 1 53.60 9.98 76 5.0 1 3 1 53.60 9.98 81 1.0 2 4 1 53.58 9.99 82 1.0 2 5 1 53.59 9.97 83 NaN 2 6 2 52.01 10.04 64 1.0 3 7 2 52.34 10.05 65 1.0 3 8 2 52.33 10.07 66 NaN 3 Note that from your description and your data, it looks like you could really use groupby, and you should probably look into it for other manipulations. However, in the particular case you're asking for, it's unnecessary
type: Answer
accepted answer of: http://stackoverflow.com/q/50589099
has comment: http://stackoverflow.com/comment/88346748
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50589099
upvote count: 3

http://stackoverflow.com/comment/88548492
has text: but the overfitting issue is not gone completely
comment on: http://stackoverflow.com/a/50770495
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50686007
has comment: http://stackoverflow.com/comment/88382512
type: Question
tagged with: apache-spark-sql
tagged with: pyspark
has comment: http://stackoverflow.com/comment/88381993
has body: I have a PySpark dataframe mydf and am grouping by 2 columns (code and col1) to obtain a resultant table with highest distinct count of third column (newid). Eg: mydf code col1 newid 100 MNO 1 100 MNO 2 230 LLL 3 245 TTE 4 230 LLL 5 230 LIO 6 100 FGH 7 Expected Result: code col1 count(distinct newid) 100 MNO 2 230 LLL 2 245 TTE 1 Current results using the code below: mydf.groupBy("code","col1").agg(count("newid"), countDistinct("newid")\ .orderBy(desc("countDistinct('newid')"))) code col1 newid 100 MNO 2 230 LLL 2 245 TTE 1 100 FGH 1 230 LIO 1
linked to: http://stackoverflow.com/q/50685522
linked to: http://stackoverflow.com/q/31064243
score: 0
tagged with: pandas
has title: PySpark grouping by 2 columns to get top 1 count per group
duplicate of: http://stackoverflow.com/q/31064243
has comment: http://stackoverflow.com/comment/88383108
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88386088
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/88382740

http://stackoverflow.com/q/50674767
answer count: 1
downvote count: 0
has title: Using os.walk to get all files from dir and its subdirs
favorite count: 0
has comment: http://stackoverflow.com/comment/88359230
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/16953842
has body: I'm currently writing a python script which you can give a drive or folder, and it then iterates through every image on the drive or folder and moves them all into one folder. My issue is that using os.walk, it isn't opening the subdirs automatically. As an example, say I chose the E: drive to scan. E: drives file structure; E: + Folder1 - file.png - file2.png - files.jpg The only file that my script will detect is files.jpg, as the other files are nested in a subdir, which os.walk does not open and check for files. Here's the code I'm using as of right now; # For each file in the drive for folders, sub_folders, files in os.walk(drive): # For each name in the files for filename in files: if filename == drive + "\\ImageSorter\\": continue file_name = os.path.splitext(filename)[0] extension = os.path.splitext(filename)[1] Is there a way to get os.walk to iterate through all subdirs on the drive, rather than just the first folder?
duplicate of: http://stackoverflow.com/q/16953842
upvote count: 3
has answer: http://stackoverflow.com/a/50674838
tagged with: os.walk
type: Question
score: 3

http://stackoverflow.com/a/50634343
has body: The proximate problem is that '%s' % k is not quite the same thing as str(k) but slower—it's: The same thing as str(k) but slower if k is anything but a tuple, The same thing as str(k[0]) if k is a one-element tuple, or A TypeError if k is a tuple with any other length. The % operator takes a tuple, but for compatibility with Python ancient 1.2 or so, and for quick&amp;dirty hacking at the interactive terminal, it treats anything that isn't a tuple as a one-element tuple. Which works, except when you actually give it a tuple. If you don't understand why k is a tuple—that's exactly what dict.items() iterates: key-value tuples. To fix this, you can use '%s' % (k,). This actually is the same thing as str(k) but slower. But why do you want the same thing as str(k) but slower in the first place? Why not just str(k)? But then it's not clear why you're trying to do this in the first place, and all it's going to do is give you another TypeError. [str(item)] is a list of one string. (The string happens to be a string representation of a key-value tuple out of globals(), but that doesn't actually matter here.) You then try to index that list with 'Top 10', which obviously isn't an index. If that error isn't obvious, imagine that you'd written this instead: lst = [1, 2, 3] lst['Top 10'] = 'a' Maybe what you wanted is: for k in globals().values(): k['Top 10'] = 'a' But that isn't going to work either. There are a few more problems to get through, but ultimately you come down to one that can't be solved. globals() contains all of your globals, not just the ones you created above. For example, it contains Partidas, and k, and probably pd. And a bunch of other modules you imported and functions you defined and so on. Most of those things are not dicts, dataframes, or other kinds of mappings, so you're just going to get yet another TypeError. Worse, a few of them are mappings, but not mappings you wanted to add a 'Top 10' key to, and for those, you'll be corrupting your data silent…
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50634086

http://stackoverflow.com/q/50679177
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50679448
score: 3
possible better answer: http://stackoverflow.com/a/50679691
has answer: http://stackoverflow.com/a/50679691
has title: Using python pandas how to do some following analysis
has body: I have yield data for some villages, For sample data, please see attachment.enter image description here Village Yield(in Kg) Date Village1 0.22 01/06/18 Village1 0.23 02/06/18 Village1 0.55 01/06/18 Village1 0.2 02/06/18 Village2 0.88 31/05/18 Village2 0.89 30/05/18 Village2 0.63 30/05/18 Village2 0.55 30/05/18 Now, I want to showing that , villages corresponding yield data with experiment date.so, village1 has 4 yield values. Please see attachment.enter image description here Village Yield-1 Yield-2 Yield-3 Village1 0.22 01/06/18 0.23 02/06/18 0.55 01/06/18 Any help it will helpful. Thanks
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88367761
has answer: http://stackoverflow.com/a/50679448
has answer: http://stackoverflow.com/a/50679607
favorite count: 0
has comment: http://stackoverflow.com/comment/88390064
upvote count: 3
answer count: 3
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/88367753
tagged with: python
has comment: http://stackoverflow.com/comment/88367794

http://stackoverflow.com/q/50683701
upvote count: 1
downvote count: 7
type: Question
has title: How can I extract a string from a text field that matches with a "value" in my Dictionary and return the dict's key into a new column in the Output?
tagged with: dataframe
tagged with: pandas
has comment: http://stackoverflow.com/comment/88377163
answer count: 1
has body: I would like to extract from a description field (column in my DF) the first string that matches another string in a dictionary (using Python) or show Null if there is no match, for i.e.: # read an excel with columns (IDX, DESCRIPTION) df = pd.read_excel("example.xlsx") Input: example.xlsx [IDX] [Column DESCRIPTION] [Row 1] ["I live in Russia"] [Row 2] ["I was borned in USA"] [Row 3] ["I would like to move to England"] My dictionary has the following countries: countries= [ {'value': ['usa'], 'country': 'United States of America'}, {'value': ['u.s.a.'], 'country': 'United States of America'}, {'value': ['united states'], 'country': 'United States of America'}, {'value': ['spain'], 'country': 'Spain'}, {'value': ['russia'], 'country': 'Russia'}, {'value': ['rusia'], 'country': 'Russia'}, {'value': ['canada'], 'country': 'Canada'}, {'value': ['france'], 'country': 'France'}, {'value': ['mexico'], 'country': 'Mexico'} ] Output: [IDX] [Column DESCRIPTION] [Column Country] [Row 1] ["I live in Russia"] ['RUSSIA'] [Row 2] ["I was borned in USA"] ['UNITED STATES OF AMERICA'] [Row 3] ["I would like to move to England"] [Null] A new excel with an additional column with the matched country or null
tagged with: string
score: -6
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88377138
tagged with: dictionary
has answer: http://stackoverflow.com/a/50683881

http://stackoverflow.com/comment/88243713
type: QuestionComment
has text: Nothing wrong with the way you wrote it. It's what you did before. df is a slice of another dataframe so all changes to it will trigger this warning. Set `df.is_copy = None` before this assignment and the warning will disappear.
comment on: http://stackoverflow.com/q/50616898
score: 0
type: Comment

http://stackoverflow.com/a/50644376
has body: I'm not sure how well anaconda and virtual environments i.e.venv work together. If you're using anaconda anyway then I highly recommend using anaconda environments. Please go through this short tutorial about anaconda environments - you won't regret it. Why it didn't work for you? The conda command is available only in the base anaconda environment. So when you run the command - conda insall -c conda-forge holopy, it installed holopy in the base anaconda environment and it won't be available to you in your venv. After looking at the documentation of holopy it seems probable that when they said virtual environment they actually meant anaconda virtual environment. Therefore the solution is to first create an anaconda virtual environment called holopy-env and then run the command conda install -n holopy-env -c conda-forge holopy. A better way of doing things with Anaconda I will also give you a quick and clean example of how to create an environment using anaconda. If you're using Anaconda then it would be wise to use it's environment management tools. Create an environment.yml file with the following contents: environment.yml using conda-forge/holopy &amp; python 3.6 name: holopy-env # any name for the environment channels: - conda-forge dependencies: # everything under this, installed by conda - python=3.6 - holopy - pip: # everything under this, installed by pip - future How to install the environment? conda create --force -f environment.yml How to activate the environment? source activate opencv-env After activating the environment You should be able to import holopy Install pip packages using pip install &lt;package&gt; Install conda packages using conda install -n holopy-env -c CHANNEL &lt;package&gt;
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88440624
accepted answer of: http://stackoverflow.com/q/50643691
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88417486
answers question: http://stackoverflow.com/q/50643691
has comment: http://stackoverflow.com/comment/88438642
has comment: http://stackoverflow.com/comment/88427866

http://stackoverflow.com/comment/88304113
type: AnswerComment
score: 0
type: Comment
has text: Thanks, this works. Just one more question, how can I iterate over more than one row. When I run this code, it only provides the value of the first row of the xml.
comment on: http://stackoverflow.com/a/50639934

http://stackoverflow.com/a/50692647
score: 22
upvote count: 22
type: AcceptedAnswer
downvote count: 0
has body: Try print with parenthesis in Python3 i.e. print(x) instead of print x
type: Answer
accepted answer of: http://stackoverflow.com/q/50692522
answers question: http://stackoverflow.com/q/50692522

mininet
tag name: mininet
tags question: http://stackoverflow.com/q/50551480
tags question: http://stackoverflow.com/q/50549757
type: Tag

http://stackoverflow.com/a/50799700
has body: I found no way to work with JAVA Keystore in python, so I changed the flow to using pkcs10Request and creating p12 cert using openssl
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50692814

cookies
tags question: http://stackoverflow.com/q/50660567
type: Tag
tag name: cookies
tags question: http://stackoverflow.com/q/50599818
tags question: http://stackoverflow.com/q/50616865

http://stackoverflow.com/q/50655446
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has body: Using re in python3, I want to match appearances of percentages in text, and substitute them with a special token (e.g. substitute "A 30% increase" by "A @percent@ increase"). I only want to match if the percent expression is a standalone item. For example, it should not match "The product's code is A322%n43%". However, it should match when a line contains only one percentage expression like "89%". I've tried using delimiters in my regex like \b, but because % is itself a non-alphanumeric character, it doesn't catch the end of the expression. Using \s makes it impossible to catch expression standing by themselves in a line. At the moment, I have the code: &gt;&gt;&gt; re.sub(r"[+-]?[.,;]?(\d+[.,;']?)+%", ' @percent@ ', "1,211.21%") ' @percent ' which still matches if the expression is followed by letters or other text (like the product code example above). &gt;&gt;&gt; re.sub(r"[+-]?[.,;]?(\d+[.,;']?)+%", ' @percent@ ', "EEE1,211.21%asd") 'EEE @percent@ asd' What would you recommend?
has answer: http://stackoverflow.com/a/50655589
has answer: http://stackoverflow.com/a/50655765
answer count: 2
possible better answer: http://stackoverflow.com/a/50655589
downvote count: 0
has comment: http://stackoverflow.com/comment/88322006
favorite count: 0
has title: Python regex match only if standalone
tagged with: python
tagged with: regex
accepted answer: http://stackoverflow.com/a/50655765

http://stackoverflow.com/comment/88368861
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50678185
has text: A simple method could be to take the average after normalizing. Then low average means "good" peak.

http://stackoverflow.com/q/50631195
has answer: http://stackoverflow.com/a/50639075
upvote count: 3
type: UnansweredQuestion
has title: Getting an error OpenCV(3.4.1) C:\projects\opencv-python\opencv\modules\imgproc\src\thresh.cpp:1406: error: (-215)
type: Question
tagged with: opencv
score: 3
has body: I ran the below code and I am getting an error as OpenCV(3.4.1) C:\projects\opencv-python\opencv\modules\imgproc\src\thresh.cpp:1406: error: (-215) src.type() == (((0) &amp; ((1 &lt;&lt; 3) - 1)) + (((1)-1) &lt;&lt; 3)) in function cv::threshold I am not clear on what this means and how to fix it import numpy as numpy from matplotlib import pyplot as matplot import pandas as pandas import math from sklearn import preprocessing from sklearn import svm import cv2 blur = cv2.GaussianBlur(img,(5,5),0) ret3,th3 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) image = numpy.invert(th3) matplot.imshow(image,'gray') matplot.show()
has comment: http://stackoverflow.com/comment/88272489
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/95529673
type: Comment
type: QuestionComment
has text: hoefling, could you type up a more complete answer based on your comment? I don't know how to check the build log and I'm not sure what you want us to add to `pip show`
score: 0
comment on: http://stackoverflow.com/q/50585246

http://stackoverflow.com/comment/88220398
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50601917
has text: PostgreSQL version 9.6
score: 0

http://stackoverflow.com/comment/88225024
score: 0
has text: What is `bytespdate2num` ?
comment on: http://stackoverflow.com/q/50607534
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50643691
has body: I want to work with the python package holopy. Apparently you have to use conda to install it, so I first installed Anaconda 4.2.0 (since I'm using Python 3.5). I opened the virtual environment I normally use and installed holopy as they recommend on the official site: conda install -c conda-forge holopy Afterwards, when in the virtual environment I type conda list, holopy shows up. But when I type python3 and then import holopy, it says package not found. It does however work when I leave the virtual environment. I need it in the virtual environment though, how can I do that?
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/50644174
has answer: http://stackoverflow.com/a/52669322
type: Question
possible better answer: http://stackoverflow.com/a/50644174
accepted answer: http://stackoverflow.com/a/50644376
tagged with: conda
has title: Importing a package installed with anaconda in virtual environment
score: 2
downvote count: 0
tagged with: virtualenv
favorite count: 0
answer count: 3
has answer: http://stackoverflow.com/a/50644376
tagged with: python

http://stackoverflow.com/a/50607795
answers question: http://stackoverflow.com/q/50607740
upvote count: 3
type: Answer
downvote count: 0
has body: Use: df = (df.melt('ID', var_name='Col2') .query('value== 1') .sort_values(['ID', 'Col2']) .drop('value',1)) Alternative solution: df = (df.set_index('ID') .mask(lambda x: x == 0) .stack() .reset_index() .drop(0,1)) print (df) ID Col2 8 1002 2 24 1002 4 2 1004 1 10 1004 2 35 1005 5 44 1006 6 5 1007 1 21 1007 3 23 1009 3 55 1009 7 Explanation: First reshape values by melt or set_index with unstack Filter only 1 by query or convert 0 to NaNs by mask sort_values for first solution create columns from MultiIndex by reset_index Last remove unnecessary columns by drop
score: 3

http://stackoverflow.com/a/50657960
has comment: http://stackoverflow.com/comment/88326979
type: Answer
has body: def collatz(number): If number%2==0: return number //2 else: return 3*number+1 userInput = int(input()) while userInput != 1: userInput = collatz(userInput) print(userInput) I hope this helps.. As per the info in the link you provided every number eventually becomes 1 when you do num//2(floor division as you need only integers not float) for even and 3*num+1 for odds repeatedly on the results
answers question: http://stackoverflow.com/q/50657770
has comment: http://stackoverflow.com/comment/88326917
score: 0

http://stackoverflow.com/a/50595500
answers question: http://stackoverflow.com/q/50595428
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88200633
type: Answer
has body: you need a field function to count total list in a record, example like this. @api.multi def _get_count_list(self): data_obj = self.env['example.object'] for data in self: list_data = data_obj.search([('Fill the condition')]) data.example_count = len(list_data) example_count = fields.Integer("Count", compute='_get_count_list')
accepted answer of: http://stackoverflow.com/q/50595428

http://stackoverflow.com/comment/88176869
score: 1
comment on: http://stackoverflow.com/q/50579050
has text: ok, seems that you don't need me.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88228753
comment on: http://stackoverflow.com/a/50609477
score: 1
type: AnswerComment
has text: Why not just `df2.columns = df1.columns`? (If that long header is really a single column name)
type: Comment

http://stackoverflow.com/comment/88100322
type: QuestionComment
has text: `chr( your hex value ) `?
comment on: http://stackoverflow.com/q/50544636
score: 1
type: Comment

http://stackoverflow.com/comment/88321398
comment on: http://stackoverflow.com/q/50654981
type: QuestionComment
has text: Can you provide a [mcve] such that we can reproduce this? Looking at the code along you are right, it should clear the axes.
score: 0
type: Comment

http://stackoverflow.com/q/50649553
type: Question
has title: How to integrate under the curve and shade the integrated area in Python?
tagged with: curve
linked to: http://stackoverflow.com/q/10046262
score: 0
has comment: http://stackoverflow.com/comment/88310223
has body: I am using Python 3.6 (Spyder). I have a 3 column dataset (x,y1,y2). I want to integrate under the curve for the y1 vs x plot for multiple regions(like the shaded blocks that are in the linked figure): that is, x1 &lt; x &lt; x2 and x3 &lt; x &lt; x4 and x5 &lt; x &lt; x6 ... and I want to shade these integrated regions in different colours. Finally, I want to do the same for y2 vs x plot and shade those regions as well. Any suggestions will be deeply appreciated. Thank you, AB
has comment: http://stackoverflow.com/comment/88312363
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: integrate
tagged with: matplotlib

http://stackoverflow.com/comment/88164481
score: 0
comment on: http://stackoverflow.com/a/50577706
has text: I want to distinct the queryset from DateField by month
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50572710
possible better answer: http://stackoverflow.com/a/50572831
has title: How to open a popup after clicking on button in python kivy?
has answer: http://stackoverflow.com/a/50572831
has answer: http://stackoverflow.com/a/50572836
score: 0
answer count: 2
tagged with: button
accepted answer: http://stackoverflow.com/a/50572836
tagged with: python
has body: I am trying to open popup after clicking on button using python kivy but getting an error Here is my code: from kivy.app import App from kivy.uix.button import Button from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label from kivy.uix.popup import Popup from kivy.config import Config Config.set("graphics", "resizable", 0) Config.set("graphics", "width", 400) Config.set("graphics", "height", 500) class myLayout(BoxLayout): def __init__(self, **kwargs): super(myLayout, self).__init__(**kwargs) btn = Button(text="Click") btn.bind(on_press=self.clk) self.add_widget(btn) def clk(self, obj): popup = Popup(content="I am popup") return popup.open() class ReminderApp(App): def build(self): mL = myLayout() return mL if __name__ == "__main__": ReminderApp().run() It works if in clk function instead of popup just print something, for e.g.: def clk(self, obj): print("Hello world") Help me please, I'm stuck Here is the error message: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/kivy/lang/builder.py", line 619, in _apply_rule setattr(widget_set, key, value) File "kivy/weakproxy.pyx", line 33, in kivy.weakproxy.WeakProxy.__setattr__ File "kivy/properties.pyx", line 478, in kivy.properties.Property.__set__ File "kivy/properties.pyx", line 516, in kivy.properties.Property.set File "kivy/properties.pyx", line 571, in kivy.properties.Property.dispatch File "kivy/_event.pyx", line 1214, in kivy._event.EventObservers.dispatch File "kivy/_event.pyx", line 1120, in kivy._event.EventObservers._dispatch File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/kivy/uix/popup.py", line 223, in on__container self._container.add_widget(self.content) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/kivy/uix/boxlayout.py", line 312, in add_widget widget.fbind('pos_hint', self._trigger_layout) AttributeError: 'str' object has no attribute 'fbind…
tagged with: kivy
tagged with: bind
type: AnsweredQuestion
tagged with: popup
type: Question

http://stackoverflow.com/comment/88350435
has text: @tobi6 that's the idea: I'm using puppet for the shared modules. But for data scientists unfamiliar with puppet and other internal operational tools in my company, having the opportunity to test a DAG with a new module without the need for devops' help would be a huge win.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50661276
score: 0

http://stackoverflow.com/comment/88125687
score: 0
type: Comment
type: QuestionComment
has text: @JohnRotenstein. I know multipart principles is upload the single object to the single storage. But I would like to know in case I will have single object with size of the 10TB, what I will do? because as far I know, I can only upload maximum 5TB data to single storage.
comment on: http://stackoverflow.com/q/50556549

http://stackoverflow.com/q/50683740
score: 0
answer count: 2
has body: I am trying to train a CNN-LSTM to read a sequence of 6 frames at a time to the CNN (VGG16 without top layer) and give the extracted features to an LSTM in Keras. The issue is that, since I need to send 6 frames at a time, I need to reshape every 6 frames and add a dimension. Also, since the labels are for every frame, I need to create another variable to get the label of the first frame for every sequence and put it in a new array and then feed both to feed the model (code below). The issue is that the data gets way too big to use model.fit() and even when trying with it on a small part of the data I get weird horrible results, so I am trying to use model.fit_generator to iterate the input to the model. But since I cannot just directly feed the data I load from the dataset (because I need to reshape and do what I explained in the first paragraph), I am trying to make my own generator. However, things are not going well and I keep getting errors saying 'tuple' is not an iterator. Does anyone know how I can fix the code to make it work? train_batches = ImageDataGenerator().flow_from_directory(train_path, target_size=(224, 224), classes=['Bark', 'Bitting', 'Engage', 'Hidden', 'Jump', 'Stand', 'Walk'], batch_size=18156, shuffle=False) valid_batches = ImageDataGenerator().flow_from_directory(valid_path, target_size=(224, 224), classes=['Bark', 'Bitting', 'Engage', 'Hidden', 'Jump', 'Stand', 'Walk'], batch_size=6, shuffle=False) test_batches = ImageDataGenerator().flow_from_directory(test_path, target_size=(224, 224), classes=['Bark', 'Bitting', 'Engage', 'Hidden', 'Jump', 'Stand','Walk'], batch_size=6, shuffle=False) def train_gen(): n_frames=6 n_samples=6 #to decide H=W=224 C = 3 imgs, labels = next(train_batches) y = np.empty((n_samples, 7)) j = 0 for i in range(n_samples): y[i] = labels[j] j +=6 frame_sequence = imgs.reshape(n_samples,n_frames, H,W,C) return frame_sequence,y def valid_gen(): v_frames=6 v_samples=1 H=W=224 C = 3 vimgs,vlabels = next(valid_batches) y2 …
tagged with: keras
has title: Creating custom data_generator in Keras for fit_generate()
tagged with: python
has answer: http://stackoverflow.com/a/50701633
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50687881
possible better answer: http://stackoverflow.com/a/50701633
tagged with: tensorflow
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/50687881

http://stackoverflow.com/q/50697673
tagged with: struct
upvote count: 1
has answer: http://stackoverflow.com/a/50704615
accepted answer: http://stackoverflow.com/a/50704615
has comment: http://stackoverflow.com/comment/88406758
answer count: 1
has comment: http://stackoverflow.com/comment/88405909
has title: Python struct unpack multiple bytes with reverse endianess
favorite count: 0
tagged with: buffer
has comment: http://stackoverflow.com/comment/88406914
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has body: So I have a buffer with N bytes and i read them with this, which works but has the reverse endianness from the one i need. buffer=struct.unpack_from( 'h'*(N/2), databuff) I noticed that endianness is reverse so I wanna experiment with endianess and I use this buffer=struct.unpack_from( '&lt;h'*(N/2), databuff) However I get this error: &gt;&gt;&gt;buffer=struct.unpack_from( '&lt;h'*1344, databuff) struct.error: bad char in struct format How do I reverse endianness on multiple bytes?
type: Question

http://stackoverflow.com/comment/88385865
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50686050
type: Comment
has text: Yes, the indexes of the maxims. Thanks for the help, @PEREZje

http://stackoverflow.com/a/50619876
score: 2
upvote count: 2
has body: Write a function to do your task i.e def get_middle(df,percent): start = int(len(df)*percent) end = len(df) - start return df.iloc[start:end] get_middle(df,0.33)
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50619640

http://stackoverflow.com/comment/88313915
comment on: http://stackoverflow.com/a/50651486
type: AnswerComment
has text: I recommend using `a_set = list(map(set, a))` in your list comprehension. The one-off conversion cost is likely less than the benefit of O(1) lookup in loops.
type: Comment
score: 1

http://stackoverflow.com/q/50564928
answer count: 1
tagged with: keras
favorite count: 0
has body: Creating doc2vec model x:List of Sentences(Movie reviews) length of x =2000 doc2vec_data = [] for line in x: temp = ''.join(str(token) for token in line.lower()) doc2vec_data.append(temp) File = open('doc2vec_data.txt', 'w',encoding="utf-8") for item in doc2vec_data: File.write("%s\n" % item) sentences=gensim.models.doc2vec.TaggedLineDocument("doc2vec_data.txt") d2v =gensim.models.Doc2Vec(sentences, dm=0,window = 5, size=5, iter = 100, workers=32,dbow_words=1, alpha=2,min_aplha=0.5) Creating Numpy array of vectors: as doc2vec model cant be directly used in keras sequential model. vec=np.array([d2v.infer_vector(item) for item in x]) Keras Sequential Model: model=Sequential() model.add(Embedding(2000,128,input_length=vec.shape[1])) model.add(LSTM(200,dropout=0.2,recurrent_dropout=0.2)) model.add(Dense(1,activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) y:sentence labels (0 and 1) model.fit(vec,y, batch_size=32,epochs=8, verbose=1) Above code is giving me this error- InvalidArgumentError Traceback (most recent call last) ~\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args) 1349 try: -&gt; 1350 return fn(*args) 1351 except errors.OpError as e: ~\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata) 1328 feed_dict, fetch_list, target_list, -&gt; 1329 status, run_metadata) 1330 ~\Anaconda3\lib\site-packages\tensorflow\python\framework\errors_impl.py in __exit__(self, type_arg, value_arg, traceback_arg) 472 compat.as_text(c_api.TF_Message(self.status.status)), --&gt; 473 c_api.TF_GetCode(self.status.status)) 474 # Delete the underlying status object from memory otherwise it stays alive InvalidArgumentError: indices[0,0] = -19 is not in [0, 2000) [[Node: embedding_1/Gather = Gather[Tindices=DT_INT32, Tparams=DT_FLOAT, validate_indices=true, _device="/job:localhost/replica:0/task:0/device:…
tagged with: deep-learning
tagged with: sentiment-analysis
tagged with: python
downvote count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50565136
score: 1
accepted answer: http://stackoverflow.com/a/50565136
type: Question
has title: How to use sentence vectors from doc2vec in keras Sequntial model for sentence sentiment analysis?
upvote count: 1

http://stackoverflow.com/a/50554808
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50554698
accepted answer of: http://stackoverflow.com/q/50554698
upvote count: 2
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/88120759
has body: You can do that with the re module: import re s = "--test -test2 --test3 arg arg arg -test4" print({m.group(1): m.group(2) or None for m in re.finditer(r"--?(\w+)(?: ([^-]*)|$)", s)}) prints: {'test': None, 'test2': None, 'test3': 'arg arg arg ', 'test4': None} Explanation: --? One or two - (\w+) Any combination of word characters ([a-zA-Z0-9_]) saved in the first group (?: ([^-]*)|$) a anonymous group consisting of either (|) ([^-]*) Any number of None - saved in the second group $ The end of the string ( In this case the second group is empty)

http://stackoverflow.com/a/50641100
has comment: http://stackoverflow.com/comment/88292155
score: 0
has body: for this you don't have to use df.loc dprev = "eiffel tower" df[df['place'] == dprev] See this answer
answers question: http://stackoverflow.com/q/50641053
type: Answer

http://stackoverflow.com/comment/88313060
type: Comment
type: QuestionComment
has text: @Morrison, I don't see any similarity with that question. The image contains partition information, the actual size is different that the file size. I want to know how to get the actual size from the decompressed file in the stdout.
comment on: http://stackoverflow.com/q/50651039
score: 1

http://stackoverflow.com/comment/88311960
type: Comment
type: QuestionComment
has text: @thisAaronMdev, it's not necessarily that it doesn't work, it's that it's the wrong way to think about it. You want your program to be able to handle all users, not just `User3`. If you want to do something special with a certain user, you can add a `self.userid` field to your `User` class, and then when you're looping through your list with of `for user in users` you can check `if user.userid == User3`.
comment on: http://stackoverflow.com/q/50650133
score: 0

http://stackoverflow.com/comment/88324814
score: 0
type: Comment
has text: Didn't work after removing phone field .still getting same error.
type: AnswerComment
comment on: http://stackoverflow.com/a/50654708

http://stackoverflow.com/q/50566728
tagged with: python
answer count: 4
downvote count: 6
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50566816
has answer: http://stackoverflow.com/a/50566841
has comment: http://stackoverflow.com/comment/88143670
has body: I like to know how to use split function to count a total from list. For example, workdays = {'work': '5,6,8,10,13,14,15,18,20,22,24,25,28,30'} Output should be like this I have worked 14 days.
type: Question
tagged with: split
has comment: http://stackoverflow.com/comment/88143399
upvote count: 0
has comment: http://stackoverflow.com/comment/88143458
favorite count: 0
possible better answer: http://stackoverflow.com/a/50566784
accepted answer: http://stackoverflow.com/a/50566816
has answer: http://stackoverflow.com/a/50566784
has answer: http://stackoverflow.com/a/50566795
score: -6
has title: count total in a list python by split
linked to: http://stackoverflow.com/q/743806

http://stackoverflow.com/comment/88202046
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50595727
has text: Why would you wanna do that in first place ?
score: 0

http://stackoverflow.com/a/56157729
type: Answer
has body: From pandas 0.25 onward you will be able to escape column names with backticks so you can do a.query('`a b` == 5')
accepted answer of: http://stackoverflow.com/q/50697536
downvote count: 0
upvote count: 105
answers question: http://stackoverflow.com/q/50697536
score: 105
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/135399560
has comment: http://stackoverflow.com/comment/116576315

http://stackoverflow.com/q/50574010
has title: deploy trained python data science project on azure as service
type: Question
accepted answer: http://stackoverflow.com/a/50674733
answer count: 2
linked to: http://stackoverflow.com/q/48205428
downvote count: 0
possible better answer: http://stackoverflow.com/a/50575041
has body: I have created a data science neural network in Python anaconda Spyder. My projects have multiple .py files and I have trained this model for 10 days and weights are generated. I want to use this model as a service and want to deploy it to Azure for consumption. I tried following but facing difficulties - 1) I tried deploying this as "Execute Python Script" in Azure ML studio but I am not finding an option to upload the weights. I understand I can zip all the .py files but what about the trained weights and virtual environment (I am using an old version of tensorflow)? 2) I am seeing an option of creating a Jupyter notebook but my project is created in Spyder and doesn't have .ipynb files. Is there any way to convert my .py files into .ipynb files? ALso, I have created a virtual environment with the older version of tensorflow and python version? How to take care of this while deploying to azure? 3) I tried deploying this to azure as a python web app but again what shall I do with the virtual environment and my existing weights? Also, how do I create my configuration or dependency file required for webapp? Please, can you let me know the best method to deploy this solution to azure with weights if possible? Thanks
tagged with: azure
has answer: http://stackoverflow.com/a/50575041
tagged with: python
tagged with: deployment
favorite count: 0
tagged with: service
upvote count: 2
has answer: http://stackoverflow.com/a/50674733
type: AnsweredQuestion
score: 2
tagged with: anaconda
linked to: http://stackoverflow.com/q/46222606

http://stackoverflow.com/comment/88155193
comment on: http://stackoverflow.com/q/50572500
has text: @MegaIng done. Thank you for your patience
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88127788
comment on: http://stackoverflow.com/a/50558463
type: AnswerComment
has text: Im just thinking, when i change the parameters from Player(x, y) to Player(color, width, height, x, y) and then in code `class Player(Block):` after that im added `Block.__init__(self, color, width, height)` and it is works, is that call instance right ?
score: 0
type: Comment

http://stackoverflow.com/comment/88278943
comment on: http://stackoverflow.com/a/50634281
type: AnswerComment
type: Comment
score: 0
has text: Actually I didn't know we can use `transform` like that. So feel free to accept your own solution.

http://stackoverflow.com/comment/88153188
has text: after running `load_job.result()`, is there any error message in `load_job.errors` ?
score: 1
comment on: http://stackoverflow.com/q/50565735
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50660389
score: 4
has comment: http://stackoverflow.com/comment/88331605
has title: Generate a vector that is orthogonal to a set of other vectors in any dimension
tagged with: matrix
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88331362
has answer: http://stackoverflow.com/a/50661011
accepted answer: http://stackoverflow.com/a/50661011
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/88331229
type: AnsweredQuestion
has body: Assume I have a set of vectors $ a_1, ..., a_d $ that are orthonormal to each other. Now, I want to find another vector $ a_{d+1} $ that is orthogonal to all the other vectors. Is there an efficient algorithm to achieve this? I can only think of adding a random vector to the end, and then applying gram-schmidt. Is there a python library which already achieves this?
tagged with: orthogonal
has comment: http://stackoverflow.com/comment/88331768
type: Question
downvote count: 0

http://stackoverflow.com/comment/88106821
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50547887
has text: @Boosted_d16 if that worked please accept this as the answer

http://stackoverflow.com/comment/88248187
comment on: http://stackoverflow.com/a/50617821
score: 0
has text: @san - Do you think all groups? Then change `['Sold'].sum()` to `['Sold'].agg(['sum','mean'])`
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/88224556
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50606929
has text: i have version 67.0
score: 0

http://stackoverflow.com/comment/88195196
type: Comment
comment on: http://stackoverflow.com/a/50592839
type: AnswerComment
score: 0
has text: Edited that in.

http://stackoverflow.com/comment/88263359
comment on: http://stackoverflow.com/a/50625174
type: AnswerComment
score: 0
type: Comment
has text: When I used print (test_a.run([xxx, aaa, bbb])), I expected aaa to indicate the locations of largest values of xxx in the 4th dimension and bbb to be those maximums... but it is not so. bbb is the maximum of xxx in the 4th dimension but aaa does not indicate those locations correctly...

http://stackoverflow.com/comment/88406229
type: QuestionComment
has text: Use `df.groupby(['Month'], as_index=False)['Score'].sum()`
comment on: http://stackoverflow.com/q/50698538
score: 1
type: Comment

http://stackoverflow.com/comment/88381293
score: 1
has text: No, you cannot hide the title bar any way except with `overrideredirect`. If you use that, you will have to create your own bindings for moving and resizing the window.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50684088

http://stackoverflow.com/comment/88470151
score: 0
type: AnswerComment
has text: @WWH98932 did you try restarting the kernal?
type: Comment
comment on: http://stackoverflow.com/a/50616233

http://stackoverflow.com/comment/88236135
has text: Does [this](https://stackoverflow.com/a/25875055/3757232) help?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50612898
type: Comment

http://stackoverflow.com/comment/88213853
type: AnswerComment
comment on: http://stackoverflow.com/a/50580810
score: 0
type: Comment
has text: @emax - Super, nice day!

http://stackoverflow.com/q/50544794
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51010126
tagged with: matplotlib
type: Question
score: 0
linked to: http://stackoverflow.com/q/50540317
has comment: http://stackoverflow.com/comment/88102517
has title: Placing coordinates on a map - Python
answer count: 1
tagged with: python
has body: I am trying to plot some coordinates (latitudes and longitudes) on top of an image of a map. The data I am plotting comes from a list of lists (the lats and lons are the 2nd and 3rd elements respectively). I have done some reading about matplotlib and 'extent', but I am still having trouble with aligning the coordinates with the map (that is, I can't get it 'to scale' so to speak). def mapping_data(atlas_data): i = 0 x = [] y = [] while i &lt; len(atlas_data): x.append(atlas_data[i][1]) y.append(atlas_data[i][2]) i = i + 1 image = plt.imread('map.png') mapped = plt.imshow(image) plt.imshow(mpimg.imread('map.png')) plt.scatter(x, y) plt.show() When I run my code as is, I get im1 (map normal, but points all in one spot and not on the map). When I add the desired extent of the map as below: (plt.imshow(mpimg.imread('map.png'), extent = (149.105, 149.130, -35.29, -35.27)) ... I get im2 (points as before, but map image flipped upside down)?? Can someone please help me with what is going wrong? Have I missed a step? I would really appreciate any help in aligning things! Here's an example of the data I'm using for reference: [['Kookaburra', -35.27667, 149.1097, 'Australian National Botaniacl Gardens, Canberra', '2000-08-14', 'Aves', 'Coraciiformes', 'Alcedinidae', 'Dacelo', 'Dacelo novaeguineae', 'False'], ['White-faced heron', -35.272244105599064, 149.12580246473127, 'Sullivans Creek--Turner Parkland', '2016-08-09', 'Aves', 'Ciconiiformes', 'Ardeidae', 'Egretta', 'Egretta novaehollandiae', 'False'], ['Australian King-parrot', -35.274386, 149.112636, 'CSIRO (Black Mountain)', '2014-10-20', 'Aves', 'Psittaciformes', 'Psittacidae', 'Alisterus', 'Alisterus scapularis', 'False'], ['Eastern Spinebill', -35.27719917903922, 149.10937031732462, 'Australian National Botanic Gardens', '2000-09-08', 'Aves', 'Passeriformes', 'Meliphagidae', 'Acanthorhynchus', 'Acanthorhynchus tenuirostris', 'False'], ['Crimson Rosella', -35.2780499, 149.11015749999999, 'Australian National Botanic Gar…

http://stackoverflow.com/a/50696038
type: Answer
answers question: http://stackoverflow.com/q/50695758
has comment: http://stackoverflow.com/comment/88480702
has body: Just copy file if it exists: #!/usr/bin/env python3.6 import shutil from pathlib import Path p = Path('/var/log') fname = 'demo.log' print('\n'.join([f'{i}' for i in p.glob('*')])) # list of files in /var/log/ origin = p / fname target = Path.home() / 'Desktop' if origin.exists(): shutil.copyfile(f'{origin}', f'{target}')
score: 0

http://stackoverflow.com/comment/88393001
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/172463/discussion-between-rishua-and-jezrael).
comment on: http://stackoverflow.com/a/50665603
score: 0
type: AnswerComment

http://stackoverflow.com/a/50595743
type: Answer
has body: I figured it out, I just needed more time. queue_lengths = [(queue - 1) if queue &gt; 0 else queue for queue in queue_lengths]
score: 0
answers question: http://stackoverflow.com/q/50595690

http://stackoverflow.com/q/50554776
tagged with: python
has answer: http://stackoverflow.com/a/50554804
score: 0
type: Question
has answer: http://stackoverflow.com/a/50554807
answer count: 2
has title: while count not working with inputs
has body: I need to create a program that reads multiple inputs and when 0 is pressed it shows how many numbers between 100 and 200 were typed. Here's my code: def counting(): total = 0 entry = int(input("Type a number: ")) while entry != 0: entry = int(input("Type a number: ")) if 100 &lt; entry &lt; 200: total += 1 print(total) It works fine except when the first number typed is between 100 and 200. If i type '123', '150', and '0', I'll get 1 (the first input is not counted). Any tips to fix this? Thanks :D
type: UnansweredQuestion

http://stackoverflow.com/comment/88158612
has text: @lopezdp Same, I'm doing it manually, it's really annoying. I'll go somewhere else tomorrow to see if it can change my IP address...
score: 0
comment on: http://stackoverflow.com/q/50571317
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50554152
upvote count: 0
has comment: http://stackoverflow.com/comment/88119142
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/88119141
linked to: http://stackoverflow.com/q/5082452
type: Question
has title: Python - basic arithmetic/variable names
answer count: 1
has comment: http://stackoverflow.com/comment/88119121
has body: The assignment is to write a program that spits out an odd number, a number, and then does basic arithmetic on those numbers. I've gotten it to spit out outputs fine, but I cannot seem to find a way to have the generated numbers be part of the equation. Here is the code I have: odd = int(input("Please enter an odd number from 1 to 99: ")) print(int(odd)) num = int(input("Please enter a number from 1 to 200: ")) print(int(num)) print('odd + num =',odd+num) print('odd - num =',odd-num) print('odd * num=',odd*num) print('odd / num =',odd/num) print('odd + num =',num+odd) print('odd - num =',num-odd) print('odd * num =',num*odd) print('odd / num =',num/odd) I need the 'odd / num =' section to be replaced with the numbers generated, but I'm unsure as to how to do that and my textbook says nothing about it. Any help would really be appreciated.
favorite count: 0
downvote count: 3
duplicate of: http://stackoverflow.com/q/5082452
tagged with: python
has answer: http://stackoverflow.com/a/50554310

http://stackoverflow.com/comment/88207854
comment on: http://stackoverflow.com/q/50599141
score: 0
type: Comment
type: QuestionComment
has text: don't use `iter` as variable, it shadows the built in [`iter`](https://docs.python.org/3/library/functions.html#iter) function. And `pylab` is deprecated. Use `import matplotlib.pyplot as plt` instead. [`random.seed()`](https://docs.python.org/3/library/random.html#random.seed) doesn't actually do anything unless you pass a variable and please have a look at the [python style guide](https://www.python.org/dev/peps/pep-0008/) (e.g. put spaces either side of operators).

http://stackoverflow.com/comment/88189414
comment on: http://stackoverflow.com/q/50589771
has text: You will need to find something to uniquely identify the tables, or get all the data from every table and then filter it afterward. Without a more in depth description of your problem we can't help much more
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88308885
type: QuestionComment
has text: What's the point of the `decorator` inner function? Why not just return `func` unaltered?
score: 0
comment on: http://stackoverflow.com/q/50649020
type: Comment

http://stackoverflow.com/comment/88350783
has text: It's not an IPython feature; the `help` function is a builtin. And I don't think it's possible to suppress that output. Best you can do is probably to write your own `help` function...
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50670470

http://stackoverflow.com/a/50639664
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50622153
score: 1
accepted answer of: http://stackoverflow.com/q/50622153
has body: By default there is a one2many field on the product.template that is called seller_ids. This is the relation between product_supplierinfo and product_template. So you can do something like this to get all the supplier codes: <t t-esc="', '.join([x.product_code for x in order_line.product_id.product_tmpl_id.seller_ids])" /> You can show all the product codes in a table as well Supplier Product Code
has comment: http://stackoverflow.com/comment/88294198
has comment: http://stackoverflow.com/comment/88294881
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88321510
has comment: http://stackoverflow.com/comment/88295248

http://stackoverflow.com/comment/88269970
type: QuestionComment
type: Comment
has text: To be honest ,I dont know ,i was hoping them to be strings
comment on: http://stackoverflow.com/q/50629625
score: 0

http://stackoverflow.com/comment/88388451
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50689167
has text: Its showing up on the screenshot. I would imagine its javascript populating it. Is there a way to grab it if it is?

http://stackoverflow.com/q/50591198
type: Question
has comment: http://stackoverflow.com/comment/88192254
has comment: http://stackoverflow.com/comment/88192350
has comment: http://stackoverflow.com/comment/88191831
score: 0
has comment: http://stackoverflow.com/comment/88191851
has comment: http://stackoverflow.com/comment/88191956
has comment: http://stackoverflow.com/comment/88191803
has comment: http://stackoverflow.com/comment/88191865
has comment: http://stackoverflow.com/comment/88191871
has title: Why doesn't the rest of the code after call() work?
has comment: http://stackoverflow.com/comment/88191902
has comment: http://stackoverflow.com/comment/88191882
tagged with: python
linked to: http://stackoverflow.com/q/50288783
tagged with: subprocess
answer count: 0
duplicate of: http://stackoverflow.com/q/50288783
type: UnansweredQuestion
has body: I want to be able to store both the inputs and outputs - just everything that I see on the terminal - in a file. I have to do that within the script, and not as a command in the terminal. I have tried doing that using call() at the beginning and end of the script, like so: from subprocess import call call(["script", "session.log"]) belong = raw_input("Random input getter no.1 ") take = raw_input("Input getter no.2") def ok(): print "OK" def place(): print "PLACE" def hope(): print "HOPE" if belong != 'mcr': ok() if take != 'mcrr': place() hope() print "random words" print "more words" call(["exit"]) Please ignore the nonsense phrases, I created those just so the .log file would have something in it. What happens when I run this is that this message appears on the terminal: Script started, file is session.log Nothing more. I am supposed to be prompted for an input, right? Then I entered: exit on the terminal, then this appeared: exit Script done, file is session.log Random input getter no.1 Only after typing "exit" on the terminal does the rest of the code actually work. I want the .log file to be created first, then run the entire code, then exit.
tagged with: logging

http://stackoverflow.com/q/50616051
has body: I created a mysql docker image as: docker run \ --name mysql \ -v /Users/pivdet/Downloads/backup/docker_mysql/conf.d:/etc/mysql/conf.d \ -v /Users/pivdet/Downloads/backup/docker_mysql/initdb.d:/docker-entrypoint-initdb.d \ -v /Users/pivdet/Downloads/backup/docker_mysql/data:/var/lib/mysql \ -e MYSQL_ROOT_PASSWORD=piv123 \ -p 3306:3306 \ -d mysql And started the server by docker start mysql I could connect to the server in terminal: $ mysql -h127.0.0.1 -P3306 -uroot -ppiv123 But when I tried to connect it by using peewee: import peewee mysql_db = peewee.MySQLDatabase("websdl", host="127.0.0.1", port=3306, user="root", passwd="piv123") if __name__ == "__main__": mysql_db.connect() There's an error: Traceback (most recent call last): File "models.py", line 6, in &lt;module&gt; mysql_db.connect() ... peewee.OperationalError: (1045, u"Access denied for user 'root'@'172.17.0.1' (using password: NO)") The user information of my db would be: mysql&gt; select Host, User from user; +-----------+------------------+ | Host | User | +-----------+------------------+ | % | root | | localhost | mysql.infoschema | | localhost | mysql.session | | localhost | mysql.sys | | localhost | root | +-----------+------------------+ 5 rows in set (0.01 sec)
linked to: http://stackoverflow.com/q/49019652
favorite count: 0
has title: peewee connect docker-mysql failed
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88656372
answer count: 0
score: 1
tagged with: mysql
has comment: http://stackoverflow.com/comment/88242171
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88274087
has comment: http://stackoverflow.com/comment/88242558
duplicate of: http://stackoverflow.com/q/49019652
tagged with: peewee
has comment: http://stackoverflow.com/comment/88242270
tagged with: docker
downvote count: 0

http://stackoverflow.com/comment/88535106
type: Comment
comment on: http://stackoverflow.com/a/50645807
has text: Hi, so I will need to activate the virtual environment on every reboot? The how will such issue be resolved in a live environment?
score: 0
type: AnswerComment

http://stackoverflow.com/q/50572602
has comment: http://stackoverflow.com/comment/88154991
has comment: http://stackoverflow.com/comment/88154878
has comment: http://stackoverflow.com/comment/88155005
has comment: http://stackoverflow.com/comment/88154988
has comment: http://stackoverflow.com/comment/88155053
has body: Suppose I had the following Player base class: from abc import ABC, abstractmethod class Player(ABC): def __init__(self, name, player_type): self.name = name self.player_type = player_type Wizard: from Player import Player class Wizard(Player): def __init__(self, name, player_type = "Wizard"): super().__init__(self,name) Main: from Player import Player from Wizard import Wizard def main(): gandalf = Wizard("Gandalf") print(gandalf.name) # Will print gandalf because the parameter assignment was shifted # because self was passed from the child to base class. print(gandalf.player_type) if __name__ == "__main__": main() I'm aware from this question, you shouldn't pass self from the subclass to the base class. That being said, suppose you made the mistake of doing so, the line print(gandalf.name) prints &lt;Wizard.Wizard object at 0x049F20B0&gt; because name was never assigned but what exactly does this value mean?
has comment: http://stackoverflow.com/comment/88154858
has comment: http://stackoverflow.com/comment/88154797
has comment: http://stackoverflow.com/comment/88154959
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/50572773
has comment: http://stackoverflow.com/comment/88154879
has comment: http://stackoverflow.com/comment/88154941
has comment: http://stackoverflow.com/comment/88154853
score: 0
has comment: http://stackoverflow.com/comment/88154955
has comment: http://stackoverflow.com/comment/88155054
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88154983
linked to: http://stackoverflow.com/q/50437465
type: UnansweredQuestion
has title: Value given when variable is empty

http://stackoverflow.com/comment/88308394
comment on: http://stackoverflow.com/q/50648543
score: 0
has text: lol. I don't know why I didn't think of that. Looking at the same problem for too long just doesn't help sometimes
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50543093
tagged with: python
type: AnsweredQuestion
tagged with: recursion
possible better answer: http://stackoverflow.com/a/50543442
has comment: http://stackoverflow.com/comment/88151855
type: Question
has title: Tricky Recursion in Python
has body: I am trying to solve this little exercise, but not sure how to... I need to write a function in python, a recursive function, that gets a natural number n as input, and returns a list with n elements, in which each element i is equal to the power of two of i (e.g., [1,4,9,16,...]) My idea was to set the stopping rule to be if n==1 return 1, but I am not sure how to do the second part, which I know should involve f(n-1), but I can't figure out of to do it with the list being there. Thank you !
has comment: http://stackoverflow.com/comment/88097336
has answer: http://stackoverflow.com/a/50543148
accepted answer: http://stackoverflow.com/a/50543148
score: 0
answer count: 2
upvote count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88170363
has answer: http://stackoverflow.com/a/50543442

http://stackoverflow.com/comment/88423128
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50591617
has text: Possible duplicate of [html5lib: TypeError: \_\_init\_\_() got an unexpected keyword argument 'encoding'](https://stackoverflow.com/questions/39086278/html5lib-typeerror-init-got-an-unexpected-keyword-argument-encoding)

http://stackoverflow.com/q/50615785
score: 0
has title: How to change size of textbox with size of text in wx python?
answer count: 1
has answer: http://stackoverflow.com/a/50619568
tagged with: wxpython
accepted answer: http://stackoverflow.com/a/50619568
tagged with: python
type: AnsweredQuestion
type: Question
has body: I am using the wx module and python 2.7 to create a personal assistant in python. So far it can search the internet and I want it to display the answer in the panel part of the wx window. I am using the wx.StaticText command to place text in the panel however this only prints the answer to a single line inside the window and doesn't fit (the answers are around two paragraphs long). I was wondering if their is something that will make the answer print inside the windows dimensions and if it doesn't fit resize the window? Cheers, Alex H

http://stackoverflow.com/comment/88305506
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50647383
has text: I don't think you even want to use `while people` here. See [Asking the user for input until they give a valid response](//stackoverflow.com/q/23294658) for better strategies to handle taking user input.

http://stackoverflow.com/comment/88360427
score: 0
type: Comment
has text: Hi Willem, Thanks for answering my question, I've seen more of your answers on my questions and I appreciate that! Thank you. It's small and simple, just what I needed.
comment on: http://stackoverflow.com/a/50645363
type: AnswerComment

http://stackoverflow.com/q/50546258
score: 0
linked to: http://stackoverflow.com/q/3462143
has title: Python: selecting the different elements of the intersection of the sets
answer count: 0
has comment: http://stackoverflow.com/comment/88123607
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88109605
has comment: http://stackoverflow.com/comment/88105900
has body: I need to check if the elements from 'a' are contained in 'b', and save in another vector the elements that are different. In R, I do as follows: a &lt;- df$v1 b &lt;- df2$v1 c &lt;- a[!(a %in% b)] How can I do the same thing in Python? I tried to use (a-b), but the result returned the difference of element values. I would not like that, I would like to retrieve elements that are different from 'a' to 'b'. Regards, Thaciana
duplicate of: http://stackoverflow.com/q/3462143
tagged with: dataframe
type: Question
has comment: http://stackoverflow.com/comment/88103782

http://stackoverflow.com/comment/117248685
score: 0
has text: This is useful thank you. Is there a way to adapt this for horizontal bar subplots? I'm having trouble going through each of my subplots.
type: Comment
comment on: http://stackoverflow.com/a/50560826
type: AnswerComment

http://stackoverflow.com/comment/88133420
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50561455
score: 0
has text: notebooks are notoriously bad at multiprocessing. Try running this on terminal and see what happens.

http://stackoverflow.com/a/50607271
has comment: http://stackoverflow.com/comment/88242078
upvote count: 2
has comment: http://stackoverflow.com/comment/88226758
answers question: http://stackoverflow.com/q/50563382
type: Answer
has comment: http://stackoverflow.com/comment/88241995
has comment: http://stackoverflow.com/comment/88226638
has body: console.py #!/usr/bin/env python3 from subprocess import check_output, PIPE commands = ['add.exe', 'sub.exe', 'print', 'exit', 'quit'] # Only commands with a set number of arguments num_cmd_args = { 'add.exe': 2, 'sub.exe': 2 } # Command help messages cmd_helps = { 'add.exe': 'Adds 2 numbers together. Returns num1 + num2', 'sub.exe': 'Subtracts 2 numbers. Returns num1 - num2', 'print': 'Prints all arguments passed' } while True: user_in = input('$ ').split() cmd = user_in[0] args = user_in[1:] # Default to '*' if not cmd not found in num_cmd_args n_args_needed = num_cmd_args.get(cmd, '*') # Check cmd if cmd not in commands: print('command not found:', cmd) continue elif cmd in ('exit', 'quit'): break # To make this much better, you're probably going to want to # do some type checking to make sure that the user entered # numbers for commands like add.exe and sub.exe. I suggest # also looking at word splitting and maybe escaping special # characters like \x07b or \u252c. # Check cmd's args if n_args_needed != len(args): print(cmd_helps[cmd]) elif n_args_needed in ('*', num_cmd_args[cmd]): out = check_output(['./'+cmd, *args]) print(out.decode(), end='') And these are my c++ files: add.cpp #include &lt;iostream&gt; using namespace std; int main(int argc, char** argv) { cout &lt;&lt; atoi(argv[1]) + atoi(argv[2]) &lt;&lt; endl; return 0; } sub.cpp #include &lt;iostream&gt; using namespace std; int main(int argc, char** argv) { cout &lt;&lt; atoi(argv[1]) - atoi(argv[2]) &lt;&lt; endl; return 0; } print.cpp #include &lt;iostream&gt; using namespace std; int main(int argc, char** argv) { for (int i=1; i&lt;argc; i++) cout &lt;&lt; argv[i] &lt;&lt; endl; return 0; }
score: 2
has comment: http://stackoverflow.com/comment/88226290
has comment: http://stackoverflow.com/comment/88227283
has comment: http://stackoverflow.com/comment/88231031
has comment: http://stackoverflow.com/comment/88225858
has comment: http://stackoverflow.com/comment/88242015
has comment: http://stackoverflow.com/comment/88227172
has comment: http://stackoverflow.com/comment/88241903
has comment: http://stackoverflow.com/comment/88227111
has comment: http://stackoverflow.com/comment/88231081
downvote count: 0
has comment: http://stackoverflow.com/comment/88242057
has comment: http://stackoverflow.com/comment/88231793

http://stackoverflow.com/a/50573782
has comment: http://stackoverflow.com/comment/88157361
accepted answer of: http://stackoverflow.com/q/50573565
type: Answer
has comment: http://stackoverflow.com/comment/88157263
answers question: http://stackoverflow.com/q/50573565
has body: You should use the __contains lookup instead of __in: samples = Sample.objects.filter(x_list__contains=x)
has comment: http://stackoverflow.com/comment/88157200
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/88157518
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50613071
has comment: http://stackoverflow.com/comment/88236320
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88236186
type: Question
tagged with: web-scraping
tagged with: python
score: 0
tagged with: selenium
tagged with: web-crawler
has body: How would you as a skilled programmer approach a project on webscraping a site for all it's soccer odds? I am trying to create a web scraper &amp; crawler for a friend to analyze the odds from all www.cashpoint.com's soccer leagues. As a new programmer, I now realize this task is bigger than I thought. The site contains javascript and there are more than just one site to scrape. I've become semi-familiar with python 3, web scraping and web crawling by following tutorials on youtube and made some small simple webscrapers. I'd like to ask a more skilled programmer how you would approach this project on making a program that scrapes all the soccer matches and then saves the info to a database. I was thinking about web crawling through https://www.cashpoint.com and gather the links for the sites that contains the odds. I'd use bucky's spider to do this: https://github.com/buckyroberts/Spider. After collecting the links I'd web scrape the pages using Selenium and xpath and store the info to a database. I've been looking at gingeleski's source code (https://github.com/gingeleski/odds-portal-scraper ) which does exactly this, just from another website. Basically you put links into a document and it'll scrape the odds and extract into a mysql database. Another approach I thought about was to iterate through the leagues through seleniums webdriver: example to click the left menu bar. webdriver.Chrome(chromedriver) driver.get('https://www.cashpoint.dk/en/site/index.html') driver.find_element_by_id('left_menu_sports_id1008').click() and then store this information to a database. I'd love to hear and learn from a programmer how you would approach this project. Thank you so much for reading this! Regards from Christian
has title: Webscrape soccer odds, how would you approach this project?

http://stackoverflow.com/comment/88395039
type: AnswerComment
has text: This is what I was after, thanks. I had to add `encoding="utf-8"` to get it playing nice.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50692552

http://stackoverflow.com/a/50648222
has comment: http://stackoverflow.com/comment/88338549
type: Answer
has body: Cross origin is enabled by default on Flask-SocketIO. My guess is that the way you are testing this is flawed. While running your example application, I can send a request to the main Socket.IO endpoint and I do get the Access-Control-Allow-Origin header in the response: ~ $ http http://localhost:5000/socket.io/ HTTP/1.1 200 OK Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: * Connection: keep-alive Content-Length: 119 Content-Type: application/octet-stream Date: Fri, 01 Jun 2018 17:10:01 GMT Set-Cookie: io=dd8d67788df54510830fea64bc82b1fd +-----------------------------------------+ | NOTE: binary data not shown in terminal | +-----------------------------------------+
has comment: http://stackoverflow.com/comment/88328313
has comment: http://stackoverflow.com/comment/88314795
has comment: http://stackoverflow.com/comment/88314512
accepted answer of: http://stackoverflow.com/q/50632723
has comment: http://stackoverflow.com/comment/88327059
answers question: http://stackoverflow.com/q/50632723
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88334433
has comment: http://stackoverflow.com/comment/88334901
has comment: http://stackoverflow.com/comment/88314299

http://stackoverflow.com/q/50596036
favorite count: 0
has answer: http://stackoverflow.com/a/50597920
tagged with: django
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: django-mptt
has title: How to show a certain number of levels in django-mptt?
accepted answer: http://stackoverflow.com/a/50597920
type: Question
downvote count: 0
answer count: 1
has body: In my Django project I use django-mptt application to create hierarchical tree. Right now next code works well but I want to show only first 4 level of the tree. How to make it correctly? I am confused. views.py: context['caregories'] = Category.objects.get(id=5).get_descendants() html: {% load mptt_tags %} &lt;ul&gt; {% recursetree caregories %} &lt;li&gt; {{ node.name }} {% if not node.is_leaf_node %} &lt;ul class="children"&gt; {{ children }} &lt;/ul&gt; {% endif %} &lt;/li&gt; {% endrecursetree %} &lt;/ul&gt;

http://stackoverflow.com/q/50684711
has title: Make a server listen to a specific port or Flask app running on another?
has body: Versiones rasa-core : 0.9.0a3 rasa-nlu : 0.12.3 Problema I have a web-app chat and a Rasa server that is a chatbot and I want the chatbot to handle the message received from the first one. At the end of this tutorial one can read that the path was to launch the following command to start the RASA-NLU server by executing the "run_server.bat" script. Load the custom trained model and start listening to port 5000: $ python -m rasa_nlu.server --path projects I tried the following but the terminal tells me that the port is already in use (myFlaskAppenv) mike@mike-thinks:~/Programing/Rasa/myflaskapp$ python -m rasa_nlu.server --path ~/Programing/Rasa/myflaskapp /home/mike/Programing/Rasa/myflaskapp/myFlaskAppenv/lib/python3.5/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. from ._conv import register_converters as _register_converters 2018-06-04 17:01:20+0100 [-] Log opened. 2018-06-04 17:01:20+0100 [-] Unhandled error in Deferred: 2018-06-04 17:01:20+0100 [-] Unhandled Error Traceback (most recent call last): File "/usr/lib/python3.5/runpy.py", line 85, in _run_code exec(code, run_globals) File "/home/mike/Programing/Rasa/myflaskapp/myFlaskAppenv/lib/python3.5/site-packages/rasa_nlu/server.py", line 402, in &lt;module&gt; rasa.app.run('0.0.0.0', cmdline_args.port) File "/home/mike/Programing/Rasa/myflaskapp/myFlaskAppenv/lib/python3.5/site-packages/klein/app.py", line 392, in run endpoint.listen(Site(self.resource())) File "/home/mike/Programing/Rasa/myflaskapp/myFlaskAppenv/lib/python3.5/site-packages/twisted/internet/endpoints.py", line 488, in listen interface=self._interface) --- &lt;exception caught here&gt; --- File "/home/mike/Programing/Rasa/myflaskapp/myFlaskAppenv/lib/python3.5/site-packages/twisted/internet/defer.py", line 121, in execute result = callable(*args, **kw) File "/home/mike/Programing/…
answer count: 1
tagged with: flask
score: 0
has answer: http://stackoverflow.com/a/50686971
accepted answer: http://stackoverflow.com/a/50686971
tagged with: port
tagged with: python
type: AnsweredQuestion
tagged with: rasa-core
tagged with: rasa-nlu
type: Question

http://stackoverflow.com/q/50620755
tagged with: python
has title: How to create an array/dataframe populated by 1 or 0 based on whether time is within a range?
score: 1
has answer: http://stackoverflow.com/a/50620976
tagged with: loops
upvote count: 1
has comment: http://stackoverflow.com/comment/88251660
type: Question
has comment: http://stackoverflow.com/comment/88256432
answer count: 3
tagged with: pandas
has body: Basically, I have a dataframe which has 2 columns, both of which are hours: 0 1 +-----+----+ 0| 11 | 12 | +-----+----+ 1| 3 | 4 | +-----+----+ 2| 11 | 12 | +-----+----+ 3| 6 | 7 | +-----+----+ 4| 16 | 16 | etc... This has a few thousand rows. I want to make another dataframe which has column headers '1' to '24' (based on the hours of a 24 hour period) and for each row of the dataframe above displays 1 if the hour time is within that range (inclusive) and 0 if it is outside. So for example the second row of the above dataframe would be something like: 1 2 3 4 5 6 7 8 ......24 0 0 1 1 0 0 0 0 ......0 And I want to do the same for each row of the first dataframe and append to the new 24 hour data frame. Hopefully this makes sense and someone can help! Happy to walk through further if it doesn't make sense! Also am new to posting on here so not sure exactly how to get the data to paste over in a sensible way.
downvote count: 0
has comment: http://stackoverflow.com/comment/88251466
has answer: http://stackoverflow.com/a/50622000
favorite count: 0
has answer: http://stackoverflow.com/a/50620935
tagged with: time
type: UnansweredQuestion

http://stackoverflow.com/comment/88310342
comment on: http://stackoverflow.com/q/50649640
has text: Since you're already using a regex, why not use it to do the splitting too? Just `re.findall('(.+?):(.+?).', string)` will give you a list of (index, count) pairs.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50618261
linked to: http://stackoverflow.com/q/971667
upvote count: 7
has comment: http://stackoverflow.com/comment/88393148
tagged with: python
downvote count: 0
has comment: http://stackoverflow.com/comment/88392829
has answer: http://stackoverflow.com/a/50694079
tagged with: django
has body: In my Django project I get below error when I query my data: django.db.utils.OperationalError: (1052, "Column 'name' in field list is ambiguous") using: http://localhost:8000/api/physicalserver/list/?switchesport__bandwidth=10 but if I use: http://localhost:8000/api/physicalserver/list/?switches__id=xxx It will work fine. my ListAPIView code: class PhysicalServerListAPIView(ListAPIView): serializer_class = PhysicalServerListSerializer permission_classes = [AllowAny] pagination_class = CommonPagination def get_queryset(self): query_params = self.request.query_params filters = {'{}__contains'.format(key): value for key, value in query_params.items() } qs = PhysicalServer.objects.filter(**filters) return qs.extra(select={'length':'Length(name)'}).order_by('length', 'name') my serializer code: class PhysicalServerListSerializer(ModelSerializer): bandwidth = serializers.SerializerMethodField() class Meta: model = PhysicalServer fields = "__all__" depth = 1 def get_bandwidth(self, obj): return obj.switchesport.bandwidth my model of PhysicalServer: class PhysicalServer(models.Model): name = models.CharField(max_length=32) switches = models.ForeignKey(to=Switches, on_delete=models.DO_NOTHING) physical_server_model = models.ForeignKey(to=PhysicalServerModel, null=True, on_delete=models.DO_NOTHING) switchesport = models.OneToOneField(to=SwitchesPort, related_name="physical_server", on_delete=models.DO_NOTHING) ... EDIT-1 My Switches Model: class Switches(models.Model): name = models.CharField(max_length=32) desc = models.CharField(max_length=256) routerdevice = models.ForeignKey(to=RouterDevice, related_name="switches") gatewaydevice = models.ForeignKey(to=GatewayDevice, related_name="switches") ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) class Meta: ordering = ['-name'] def __str__(self): return self.name def __unicode__(self): return self.name and my SwitchesPort model code: class SwitchesPort(models.Model): name = models.Cha…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88405549
has answer: http://stackoverflow.com/a/50732532
accepted answer: http://stackoverflow.com/a/50732532
score: 7
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88379264
possible better answer: http://stackoverflow.com/a/50694079
has comment: http://stackoverflow.com/comment/88246323
has comment: http://stackoverflow.com/comment/88371038
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/88246368
has title: django.db.utils.OperationalError: (1052, "Column 'name' in field list is ambiguous")
favorite count: 0
has comment: http://stackoverflow.com/comment/88265944
has comment: http://stackoverflow.com/comment/88393125

http://stackoverflow.com/comment/120966247
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/68446599
type: Comment
has text: I think by default the installation installs the **rewrite** of discord.py

http://stackoverflow.com/comment/88157033
score: 3
comment on: http://stackoverflow.com/q/50573742
type: Comment
type: QuestionComment
has text: Please add a [mcve] of your code

http://stackoverflow.com/q/50648249
has answer: http://stackoverflow.com/a/50648449
possible better answer: http://stackoverflow.com/a/70466279
tagged with: python
tagged with: gspread
has answer: http://stackoverflow.com/a/70466279
upvote count: 14
has body: I'm using gspread and the Google Sheets API to update cell values, setting cell.value equal to a string of a specific formula. Example code: # Calculates sum of cells in current row from column B to H G_SHEETS_ROW_SUM_COMMAND = '''=SUM(INDIRECT(CONCATENATE("B",ROW(),":H",ROW())))''' for cell in cell_list: cell.value = G_SHEETS_ROW_SUM_COMMAND When my spreadsheet is populated, however, my command becomes prefixed with an apostrophe ('). This is presumably to keep the cell from being interpreted as a formula, but that's exactly what I'd like it to do. Here's an example from my spreadsheet: Is there a way to remove this apostrophe automatically? I've looked into value rendering options and input_value, though these options seem to be unavailable for writing to sheets.
accepted answer: http://stackoverflow.com/a/50648449
tagged with: google-sheets-api
score: 14
type: AnsweredQuestion
has title: Updating cell values with formulas results in apostrophe prefixes with Sheets API
type: Question
answer count: 2
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/50628872
has comment: http://stackoverflow.com/comment/88270933
answers question: http://stackoverflow.com/q/50628767
upvote count: 1
has comment: http://stackoverflow.com/comment/88269880
has comment: http://stackoverflow.com/comment/88270899
has body: Use join: from io import StringIO import csv txtfile = StringIO("""s,0,6,8,9,2,-,3,6,2,8,7,1,0,n,.,c,s,v s,0,5,9,6,0,-,3,6,7,0,1,6,0,n,.,c,s,v s,1,9,0,5,5,-,3,6,1,5,5,8,6,n,.,c,s,v s,2,8,0,7,9,-,3,2,5,1,8,2,7,n,.,c,s,v s,0,0,5,6,5,-,3,3,4,0,5,7,0,n,.,c,s,v s,3,0,3,4,8,-,3,5,9,1,2,2,6,n,.,c,s,v s,0,3,8,8,9,-,3,7,3,1,0,2,5,n,.,c,s,v""") reader = csv.reader(txtfile) for row in reader: k = row[1:6] print(''.join(k)) Output: 06892 05960 19055 28079 00565 30348 03889
has comment: http://stackoverflow.com/comment/88271021
score: 1
has comment: http://stackoverflow.com/comment/88269901
has comment: http://stackoverflow.com/comment/88270986
downvote count: 0
type: Answer

http://stackoverflow.com/a/50573697
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50573592
has body: Here's an example with numpy: import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(0, 5, (3, 10))) print(df) 0 1 2 3 4 5 6 7 8 9 0 3 0 0 2 2 4 0 2 1 2 1 3 4 0 4 4 1 1 0 2 3 2 4 1 3 4 4 4 0 3 1 0 res = [np.where(i == np.max(i)) for i in df.values] print(res) [array([5], dtype=int64), array([1, 3, 4], dtype=int64), array([0, 3, 4, 5], dtype=int64)]

http://stackoverflow.com/a/50584221
accepted answer of: http://stackoverflow.com/q/50581508
answers question: http://stackoverflow.com/q/50581508
has comment: http://stackoverflow.com/comment/88210562
has comment: http://stackoverflow.com/comment/88211373
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88229754
has comment: http://stackoverflow.com/comment/88212041
has body: Django provides constructs like select_related and prefetch_related to optimize the related object query operations. In your case, it should be : queryset = Venue.objects.all().prefetch_related('offer_set') For the latest item, have you tried with adding ordering meta value in Venue model as follows : class Offer(TimeStampedModel): ...... class Meta: ordering = ['created'] {% for venue in venue_list %} {{ venue.name }} {% with venue.offer_set|first as first_offer %} {{ first_offer.created }} {{ first_offer.content }} {% endwith %} {% endfor %}
has comment: http://stackoverflow.com/comment/88207224
type: Answer
has comment: http://stackoverflow.com/comment/88205983

http://stackoverflow.com/q/50685155
has body: I'm building a simple image segmentation network, based off the encoder/decoder architecture in TensorFlow and currently the model seems to run but it's not updating the weights. The inputs are my own dataset: images converted to numpy arrays of the shape [-1,200,200,1] with pixel-bu-pixel mask labels of shape [-1,40000,3]. The code for my model function is here def model(features, labels, mode): inpt = tf.reshape(features["x"], [-1,200,200,1]) #encoder x = tf.layers.conv2d( inputs = inpt, filters = 16, kernel_size = [2,2], padding = 'same', activation = tf.nn.relu) x = tf.layers.max_pooling2d(inputs = x, pool_size = [2,2], strides = 2) x = tf.layers.conv2d( inputs = x, filters = 32, kernel_size = [2,2], padding = 'same', activation = tf.nn.relu) x = tf.layers.max_pooling2d(inputs = x, pool_size = [2,2], strides = 2) x = tf.layers.conv2d( inputs = x, filters = 64, kernel_size = [2,2], padding = 'same', activation = tf.nn.relu) x = tf.layers.max_pooling2d(inputs = x, pool_size = [2,2], strides = 2) #decoder x = tf.keras.layers.UpSampling2D(size = (2,2))(x) x = tf.layers.conv2d( inputs = x, filters = 64, kernel_size = [2,2], padding = 'same', activation = tf.nn.relu) x = tf.keras.layers.UpSampling2D(size = (2,2))(x) x = tf.layers.conv2d( inputs = x, filters = 32, kernel_size = [2,2], padding = 'same', activation = tf.nn.relu) x = tf.keras.layers.UpSampling2D(size = (2,2))(x) x = tf.layers.conv2d( inputs = x, filters = 16, kernel_size = [2,2], padding = 'same', activation = tf.nn.relu) x = tf.layers.conv2d( inputs = x, filters = 3, kernel_size = [1,1], padding = 'valid', activation = tf.nn.relu) logits = tf.reshape(x, [-1,3]) predictions = { "classes": tf.argmax(input = logits, axis = 1), "probabilities": tf.nn.softmax(logits, name = "softmax_tensor") } if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec(mode = mode, predictions = predictions) labels = tf.reshape(labels, [-1,3]) loss = tf.losses.softmax_cross_entropy(onehot_labels = labels, logi…
score: 0
tagged with: machine-learning
tagged with: tensorflow
type: Question
has title: Tensorflow Image Segmentation weights not updating
has comment: http://stackoverflow.com/comment/88380247
has comment: http://stackoverflow.com/comment/88401992
answer count: 1
type: UnansweredQuestion
tagged with: python
tagged with: computer-vision
has answer: http://stackoverflow.com/a/50686804

http://stackoverflow.com/q/50652393
duplicate of: http://stackoverflow.com/q/390852
tagged with: python
duplicate of: http://stackoverflow.com/q/5384570
possible better answer: http://stackoverflow.com/a/50652427
has title: Itertools Combinations/Permutations size
has body: Is there anyway to see the len() of an itertools.Combination or other object, really, without materializing it to a list? I can get the cardinality of combs or permutations with the factorials,... but I want something that generalizes. Thanks
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/390852
tagged with: python-itertools
has answer: http://stackoverflow.com/a/50652431
upvote count: 5
accepted answer: http://stackoverflow.com/a/50652431
has comment: http://stackoverflow.com/comment/131431645
type: Question
has answer: http://stackoverflow.com/a/50652427
answer count: 3
score: 5
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50652429

http://stackoverflow.com/q/50615566
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88241402
tagged with: python
has title: Best practices for logging in python
tagged with: logging
has body: I have written a simple python package which has a set of functions that perform simple operations (data manipulation). I am trying to enhance the package and add more functionality for logging, which leads me to this question. Should I expect the user of the package to pass in a file descriptor or a file handler of the python logging module into the methods of the package, or should the package itself have its own logging module which the methods within the package employ. I can see benefits (user controls logging and can maintain a flow of function calls based on the same handler) and cons (users logger is not good enough) in both, however what is / are best practices in this case.
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88242380
has answer: http://stackoverflow.com/a/50615972
score: 0
has comment: http://stackoverflow.com/comment/88241181
answer count: 1

http://stackoverflow.com/comment/88195153
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50592844
has text: cheers Chrisz, will try this one although looks very complex to me :).
type: AnswerComment

http://stackoverflow.com/q/50667003
has body: I have a dataset which contain only one column (Pandas Series). Dataset is .dat file, which has about 2 000 000 rows and 1 column (166 MB). Reading this data with pd.read_csv takes about 7-8 minutes. This data is a signal, which need to be processed (using scipy.signal). So when I process the data I get MemoryError. Is there a way to speed up the loading of the file and increase the speed of its processing (scipy.signal.ellip) and bypass the memory problem? Thank you in advance. Loading the data: data = pd.read_csv('C:/Users/HP/Desktop/Python and programming/Jupyter/Filter/3200_Hz.dat', sep='\r\n', header=None, squeeze=True) Data processing (takes about 7 minutes too): b, a = signal.ellip(4, 5, 40, Wn, 'bandpass', analog=False) output = signal.filtfilt(b, a, data) #after that plotting 'output' with plt Example of input data: 6954 25903 42882 17820 3485 -11456 4574 34594 25520 26533 9331 -22503 14950 30973 23398 41474 -860 -8528
has comment: http://stackoverflow.com/comment/88344190
score: -1
has comment: http://stackoverflow.com/comment/88344010
has comment: http://stackoverflow.com/comment/88344151
tagged with: pandas
upvote count: 0
has title: Scipy processing large data
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/50667174
has comment: http://stackoverflow.com/comment/88343969
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50667174
downvote count: 1
tagged with: scipy
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88344054

http://stackoverflow.com/a/50696297
has comment: http://stackoverflow.com/comment/88412859
answers question: http://stackoverflow.com/q/50696080
accepted answer of: http://stackoverflow.com/q/50696080
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88419110
has comment: http://stackoverflow.com/comment/88411414
has comment: http://stackoverflow.com/comment/88408159
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/88409611
has comment: http://stackoverflow.com/comment/88409028
score: 1
has body: After plotting your original data use: ax = plt.gca() # get the axis handle of the current graphic artist data_2d = ax.lines[0] # this just extracts the first dataset x,y = data_2d.get_xdata(), data_2d.get_ydata() #this will be your x and y data Using your original code this can be plugged in like: ax.scatter3D(x, b, y) Second option Modify your original function to return the axis handle. import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def cumulative(moment): fig, ax = plt.subplots() bins = np.cumsum(np.arange(moment)) x = np.arange(moment) ax.plot(x, bins, c = 'b') ax.set_xlabel('grain size (um)') ax.set_ylabel('concentration (uL/L)') ax.set_title('grain size distribution over time') ax.set_ylim(ymax = bins.max()) return fig, ax b = 32 #just a random scalar to test fig, ax = cumulative(b) #call the function and assign the returning values data_2d = ax.lines[0] # get your data x,y = data_2d.get_xdata(), data_2d.get_ydata() #your data separated for x and y plot3d = plt.figure() ax3d = plot3d.add_subplot(111, projection='3d') ax3d.scatter(x,b,y)

http://stackoverflow.com/q/50659670
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/72019404
type: Question
has title: Getting data out of dictionary of lists from Spotify API request
accepted answer: http://stackoverflow.com/a/50659784
tagged with: spotipy
answer count: 2
upvote count: 1
tagged with: spotify
has body: Heyo, I need help getting the correct info out of a call to the Spotify API using Spotipy. I am relatively new to Python, so maybe I am missing something really obvious, but I have researched for a few hours and tried everything I could think of and still am not getting the results I want. I basically want to ask Spotify for a user's saved library and take out the track title and artist from the response and save them for later. Currently when I call tracks_response = spotify.current_user_saved_tracks(limit=1, offset=0) print(tracks_response) I receive something like this: {'href': 'https://api.spotify.com/v1/me/tracks?offset=0&amp;limit=1', 'items': [{'added_at': '2018-05-31T18:59:42Z', 'track': {'album': {'album_type': 'album', 'artists': [{'external_urls': {'spotify': 'https://open.spotify.com/artist/4AA8eXtzqh5ykxtafLaPOi'}, 'href': 'https://api.spotify.com/v1/artists/4AA8eXtzqh5ykxtafLaPOi', 'id': '4AA8eXtzqh5ykxtafLaPOi', 'name': 'What So Not', 'type': 'artist', 'uri': 'spotify:artist:4AA8eXtzqh5ykxtafLaPOi'}], 'available_markets': [...], 'external_urls': {'spotify': 'https://open.spotify.com/album/3XaUNjcSJ6oyhoaFTqRbLb'}, 'href': 'https://api.spotify.com/v1/albums/3XaUNjcSJ6oyhoaFTqRbLb', 'id': '3XaUNjcSJ6oyhoaFTqRbLb', 'images': [{'height': 640, 'url': 'https://i.scdn.co/image/3a6afacbac6870ec6025694f4f7d931fe3d0e383', 'width': 640}, {'height': 300, 'url': 'https://i.scdn.co/image/64e4b200281890ec57c239591666b31eba03e6b8', 'width': 300}, {'height': 64, 'url': 'https://i.scdn.co/image/f217a511095e82b4a34dbaa379e2d58b4f9fe9ef', 'width': 64}], 'name': 'Divide &amp; Conquer (Remixes)', 'release_date': '2017- 06-16', 'release_date_precision': 'day', 'type': 'album', 'uri': 'spotify:album:3XaUNjcSJ6oyhoaFTqRbLb'}, 'artists': [{'external_urls': {'spotify': 'https://open.spotify.com/artist/4AA8eXtzqh5ykxtafLaPOi'}, 'href': 'https://api.spotify.com/v1/artists/4AA8eXtzqh5ykxtafLaPOi', 'id': '4AA8eXtzqh5ykxtafLaPOi', 'name': 'What So Not', 'type': 'artist', 'uri': 'sp…
favorite count: 0
possible better answer: http://stackoverflow.com/a/72019404
has answer: http://stackoverflow.com/a/50659784
tagged with: python

http://stackoverflow.com/q/50680801
type: AnsweredQuestion
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88446313
type: Question
accepted answer: http://stackoverflow.com/a/50680818
possible better answer: http://stackoverflow.com/a/50681447
has answer: http://stackoverflow.com/a/50681447
tagged with: dataframe
has body: I have a data like this. I calculate the mean of each IDs df.groupby(['ID'], as_index= False)['A'].mean() Now, I want to drop all those Ids whose mean value is more than 3 df.drop(df[df.A &gt; 3].index) And this is here i am stucked. I want to save the file but in original format (without grouping and no mean value) and without those Ids whose means were more than 3. Any Idea How can i achieve this. Output something like this. Also I want to know how many unique Ids were removed while using drop.
answer count: 2
has title: Calculate Mean by Groupby, drop some rows with Boolean conditions and then save the file in original format
tagged with: pandas
has comment: http://stackoverflow.com/comment/88446049
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50680818
tagged with: python

http://stackoverflow.com/comment/96452614
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50645707
has text: Thank you guys, for helping me. I just reinstalled everything and it just works.

http://stackoverflow.com/comment/88314299
type: Comment
has text: Have you tried to access the server from Chrome browser?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50648222

http://stackoverflow.com/comment/88302785
has text: I tried to make my answer more explicit. Hope it helps
score: 1
comment on: http://stackoverflow.com/a/50640931
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88392971
type: Comment
type: QuestionComment
score: 1
has text: What prompted you to write that `if-elif` block? Is it only because you were not aware of existence of division?
comment on: http://stackoverflow.com/q/50690751

http://stackoverflow.com/comment/88102994
comment on: http://stackoverflow.com/q/50545990
has text: the issue is that once I start the application, it consumes 100% CPU
score: 0
type: QuestionComment
type: Comment

widget
tags question: http://stackoverflow.com/q/50581645
type: Tag
tags question: http://stackoverflow.com/q/50593326
tags question: http://stackoverflow.com/q/50661401
tag name: widget
tags question: http://stackoverflow.com/q/50651466
tags question: http://stackoverflow.com/q/50552486

http://stackoverflow.com/q/50651581
tagged with: python-3.x
has title: Is it possible to convert 3D image to one vector?
tagged with: python
has answer: http://stackoverflow.com/a/50651629
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88314093
has answer: http://stackoverflow.com/a/50651627
has comment: http://stackoverflow.com/comment/88314129
tagged with: machine-learning
possible better answer: http://stackoverflow.com/a/50651629
has body: In this code (courtesy to this answer): from PIL import Image import numpy as np def load_image(infilename): img = Image.open(infilename) img.load() data = np.asarray(img, dtype="int32") return data def save_image(npdata, outfilename): img = Image.fromarray(np.asarray(np.clip(npdata, 0, 255), dtype="uint8"), "L") img.save(outfilename) data = load_image('cat.0.jpg') print(data.shape) The value of print(data.shape) is a tuple of three dim (374, 500, 3). Thus, I have these questions: What does this tuple represent? To be used for machine learning classification purpose, does it make sense to convert such a tuple data into one dimension vector? If so, how? Thank you very much.
type: Question
tagged with: python-imaging-library
linked to: http://stackoverflow.com/q/7762948
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/50651627
tagged with: scikit-learn

conv-neural-network
tags question: http://stackoverflow.com/q/50630657
tags question: http://stackoverflow.com/q/50615415
tags question: http://stackoverflow.com/q/50615156
tags question: http://stackoverflow.com/q/50594194
tags question: http://stackoverflow.com/q/50639003
tags question: http://stackoverflow.com/q/50559654
tags question: http://stackoverflow.com/q/50690999
tags question: http://stackoverflow.com/q/50687651
tags question: http://stackoverflow.com/q/50665466
tags question: http://stackoverflow.com/q/50589333
type: Tag
tags question: http://stackoverflow.com/q/50677544
tags question: http://stackoverflow.com/q/50602043
tags question: http://stackoverflow.com/q/50549859
tag name: conv-neural-network
tags question: http://stackoverflow.com/q/50689494
tags question: http://stackoverflow.com/q/50663623
tags question: http://stackoverflow.com/q/50629620
tags question: http://stackoverflow.com/q/50669702
tags question: http://stackoverflow.com/q/50552806
tags question: http://stackoverflow.com/q/50608230
tags question: http://stackoverflow.com/q/50645828
tags question: http://stackoverflow.com/q/50653128
tags question: http://stackoverflow.com/q/50545596
tags question: http://stackoverflow.com/q/50556812
tags question: http://stackoverflow.com/q/50683039
tags question: http://stackoverflow.com/q/50559586

http://stackoverflow.com/comment/88107502
type: QuestionComment
has text: @Simeon Ikudabo yes, that is a good suggestion. For one file it might be good try that I will try. Any suggestions if I have many files with different row numbers?
comment on: http://stackoverflow.com/q/50548249
score: 0
type: Comment

http://stackoverflow.com/comment/88310213
type: QuestionComment
has text: please don't change the tag for `tempfile`, which is the python module being used. `temporary-files` can be misleading.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50649701

array-broadcasting
tags question: http://stackoverflow.com/q/50638524
tags question: http://stackoverflow.com/q/50623040
tag name: array-broadcasting
tags question: http://stackoverflow.com/q/50698063
type: Tag

http://stackoverflow.com/a/50580209
has comment: http://stackoverflow.com/comment/88178510
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88244936
has comment: http://stackoverflow.com/comment/88244615
has comment: http://stackoverflow.com/comment/88245012
has comment: http://stackoverflow.com/comment/88178560
accepted answer of: http://stackoverflow.com/q/50579959
has comment: http://stackoverflow.com/comment/88202739
answers question: http://stackoverflow.com/q/50579959
type: AcceptedAnswer
downvote count: 0
has body: You need to combine your query_string and geo_distance queries into a bool query. doc = { "query": { "bool": { "must": { "query_string": { "query": term, "fields": ['name', 'business_name', 'email', 'city', 'state', 'zip_code', 'business_keywords', 'phone_number', 'address', 'country' ], } }, "filter": { "geo_distance": { "distance": radius, "distance_unit": "km", "distance_type": "arc", "location": { "lat": latitude, "lon": longitude } } } } }
type: Answer
has comment: http://stackoverflow.com/comment/88203356

http://stackoverflow.com/q/50626573
possible better answer: http://stackoverflow.com/a/50626832
tagged with: http://stackoverflow.com/tag/csv
tagged with: sql
favorite count: 0
upvote count: 2
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50626716
has comment: http://stackoverflow.com/comment/88263325
tagged with: database
tagged with: mysql
has body: I am trying to read a CSV file and import the record into a mysql table. CSV file looks like, db_columns.csv :- ID,SCHOOL_CODE,DISTNAME,AC_YEAR,SCHOOL_NAME,STATE_NAME,BLOCK_NAME,CLUSTER_NAME,VILLAGE_NAME,PINCODE,RURURB,ELECTRIC_YN,SCHMGT,LOWCLASS,HIGHCLASS,COMPUTER,CAL_YN,MEDINSTR1,MEDINSTR2,MEDINSTR3,MEDINSTR4 0,35010103903,ANDAMANS,2015-16,PRIMARY SCHOOL INVENT PUBLIC (PU),Andaman And Nicobar,BRC- SOUTH ANDAMAN,"DIET, GARACHARMA",BATHUBASTHI,744105,2,1,5,1,5,4,1,19,98,98,98 1,35010101902,ANDAMANS,2015-16,GOVT PRIMARY SCHOOL MAKKA PAHAR,Andaman And Nicobar,BRC- SOUTH ANDAMAN,GSSS RANGACHANG,CALICUT,744105,1,1,1,1,5,0,2,16,19,98,98 MySQL Table looks like, +--------------+--------------+ | column_name | column_type | +--------------+--------------+ | ID | double | | SCHOOL_CODE | double | | DISTNAME | varchar(100) | | AC_YEAR | varchar(25) | | SCHOOL_NAME | varchar(300) | | STATE_NAME | varchar(100) | | BLOCK_NAME | varchar(200) | | CLUSTER_NAME | varchar(200) | | VILLAGE_NAME | varchar(200) | | PINCODE | varchar(100) | | RURURB | double | | ELECTRIC_YN | double | | SCHMGT | double | | LOWCLASS | double | | HIGHCLASS | double | | COMPUTER | double | | CAL_YN | double | | MEDINSTR1 | double | | MEDINSTR2 | double | | MEDINSTR3 | double | | MEDINSTR4 | double | +--------------+--------------+ 21 rows in set (1.20 sec) Python code that I have written , #!/usr/bin/python import MySQLdb import csv db = MySQLdb.connect(host="localhost", # your host, usually localhost user="admin", # your username passwd="admin", # your password db="School_Test") # name of the data base cur = db.cursor() csv_data = csv.reader(file('db_columns.csv')) for row in csv_data: cur.execute ("INSERT INTO part_table_test (ID,SCHOOL_CODE,DISTNAME,AC_YEAR,SCHOOL_NAME,STATE_NAME,BLOCK_NAME,CLUSTER_NAME,VILLAGE_NAME,PINCODE,RURURB,ELECTRIC_YN,SCHMGT,LOWCLASS,HIGHCLASS,COMPUTER,CAL_YN,MEDINSTR1,MEDINSTR2,MEDINSTR3,MEDINSTR4) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %…
has title: import CSV record into MySQL Database in Python
type: Question
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50626832
has comment: http://stackoverflow.com/comment/88263433
accepted answer: http://stackoverflow.com/a/50626716
has answer: http://stackoverflow.com/a/50626835
has comment: http://stackoverflow.com/comment/88263287
answer count: 3

http://stackoverflow.com/q/50551020
has title: Python 3.4- cant read specific lines into a box
has comment: http://stackoverflow.com/comment/88113172
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50551045
answer count: 1
has comment: http://stackoverflow.com/comment/88115521
has comment: http://stackoverflow.com/comment/88115718
has comment: http://stackoverflow.com/comment/88115156
linked to: http://stackoverflow.com/q/1466000
downvote count: 0
type: UnansweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/88115822
tagged with: python-3.4
has comment: http://stackoverflow.com/comment/88115750
type: Question
has comment: http://stackoverflow.com/comment/88115888
has comment: http://stackoverflow.com/comment/88113536
has body: I cant figure out how to read specific lines from text file, reading bit is not a problem really but then inserting that specific line to a box. I got this which seems like a step in direction but i would need help to figure this out as it doesn't read the data into the box. def show_team(): with open("data/tournamentdatae1.txt",'r') as f: event = combo_event.get() get_all=f.readlines() result =f.readline() if event == 'Event 1': with open('data/tournamentdatae1.txt', 'r') as f: for i,line in enumerate(get_all,1): if i == 1: team_1txt.insert(0.0, result)
score: 1
has comment: http://stackoverflow.com/comment/88115836
has comment: http://stackoverflow.com/comment/88113569

http://stackoverflow.com/q/50616633
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has title: Calculating opposite partition in median of two sorted lists
has comment: http://stackoverflow.com/comment/88524870
tagged with: python
score: 2
tagged with: algorithm
type: Question
has body: From: https://leetcode.com/problems/median-of-two-sorted-arrays/description/ There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). Example 1: nums1 = [1, 3] nums2 = [2] The median is 2.0 Example 2: nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5 I have the following solution (based off of this YouTube video: https://www.youtube.com/watch?v=LPFhl65R7ww): class Solution: def findMedianSortedArrays(self, x, y): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ x, y = (x, y) if len(x) &lt;= len(y) else (y, x) total_len_even = (len(x) + len(y)) % 2 == 0 left, right = 0, len(x) while left &lt;= right: partition_x = (left + right) // 2 # not sure why we add 1 below... half_el_count = (len(x) + len(y) + 1) // 2 partition_y = half_el_count - partition_x max_left_x = float('-inf') if partition_x == 0 else x[partition_x - 1] min_right_x = float('inf') if partition_x == len(x) else x[partition_x] max_left_y = float('-inf') if partition_y == 0 else y[partition_y - 1] min_right_y = float('inf') if partition_y == len(y) else y[partition_y] if max_left_x &lt;= min_right_y and max_left_y &lt;= min_right_x: return (max(max_left_x, max_left_y) + min(min_right_x, min_right_y)) / 2.0 if total_len_even else float(max(max_left_x, max_left_y)) elif max_left_x &gt; min_right_y: right = partition_x - 1 else: left = partition_x + 1 where partition_x and partition_y means all elements before this partition index are less than or equal to the overall median. My question revolves around this line: half_el_count = (len(x) + len(y) + 1) // 2 The idea is that we want to find partition y such that, if you take the total number of elements in the combined list, the number of elements before partition x + number of elements before partition y are half the total number of elements (since we are, after all, trying to find the median). However, shouldn't the …
has answer: http://stackoverflow.com/a/50758443
downvote count: 0
answer count: 1

jupyter
tags question: http://stackoverflow.com/q/50619722
tags question: http://stackoverflow.com/q/50658677
tags question: http://stackoverflow.com/q/50573241
type: Tag
tags question: http://stackoverflow.com/q/50621776
tags question: http://stackoverflow.com/q/50688694
tags question: http://stackoverflow.com/q/50634832
tags question: http://stackoverflow.com/q/50666176
tags question: http://stackoverflow.com/q/50665045
tags question: http://stackoverflow.com/q/50563964
tag name: jupyter
tags question: http://stackoverflow.com/q/50551637
tags question: http://stackoverflow.com/q/50612508
tags question: http://stackoverflow.com/q/50627444

http://stackoverflow.com/q/50679749
has body: Can anybody share a code where one has to read metadata from sas7bdat or xpt file? I have code for reading data in python with the help of the sas7bdat library but unable to figure out how to get metadata from the same file.
tagged with: pandas
has answer: http://stackoverflow.com/a/52010407
has title: How can I read metadata from sas7bdat file or xpt file in python?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88376251
tagged with: python
upvote count: 2
score: 0
downvote count: 2
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/comment/88200471
type: Comment
comment on: http://stackoverflow.com/a/50595536
has text: Thanks. It worked perfect and it is very efficient too. Hope to code like you one day. Best
type: AnswerComment
score: 0

http://stackoverflow.com/comment/114261334
score: 1
has text: Wow awesome to see you posting an answer to my old question, I had forgotten about this. But I do use your library (and other dry-python) for these kind of things. Keep the great work up! Would love to chat with you sometime :)
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/64607153

http://stackoverflow.com/q/50674011
answer count: 1
favorite count: 0
has body: I have a dataframe with a date column converted using pd.to_datetime(). When I inspected the data I found few of these dates with year mentioned as 2216, which should have been 2016. Can you please help me change the year for these dates from 2216 to 2016 Date 0 2216-12-21 1 2216-12-23 2 2216-01-31 3 2016-12-23 4 2216-12-27 5 2216-12-25 6 2016-12-23 I tried using str.replace df['Date'] = df['Date'].str.replace("2216","2016") but got the following error Can only use .str accessor with string values, which use np.object_ dtype in pandas Thanks In advance
has answer: http://stackoverflow.com/a/50674062
has comment: http://stackoverflow.com/comment/88357895
tagged with: python
accepted answer: http://stackoverflow.com/a/50674062
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88357701
type: Question
upvote count: 9
downvote count: 4
has title: Replace the year in pandas.datetime column
score: 5
tagged with: pandas

http://stackoverflow.com/q/50658641
has title: How do I access an element in a tuple that is stored in a dict?
tagged with: tuples
type: Question
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/50658693
score: 0
answer count: 3
has body: song_lyrics_per_year={year:[(song, singer, lyrics),(song2, singer2, lyrics2)...], year2: ....} Hello, I have a dict with year as keys and as values lists of tuples (consisting of song, singer, lyrics). No, I need to access all 3 elements separately and parse them into a list onlysongs=[] onlyartists=[] However, all my tries have failed so far, including list comprehensions and codes that were suggested here. Shouldn't this work? for item in song_lyrics_per_year.values(): onlyartists.append(item[1]) In response, I get an "IndexError: list index out of range" Only a few weeks into Python and I went through all old answers on this topic and tried the solutions...they did not work, unfortunately. Thanks for your help!
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50658759
has answer: http://stackoverflow.com/a/50658715
has comment: http://stackoverflow.com/comment/88327668

http://stackoverflow.com/a/50559799
score: 0
has comment: http://stackoverflow.com/comment/88130864
accepted answer of: http://stackoverflow.com/q/50559539
answers question: http://stackoverflow.com/q/50559539
type: AcceptedAnswer
has body: Python's import is going to look for the modules (.py files) in the python path. You can see what is in python path in the sys.path variable. By default, sys.path will include directory where the script you ran is located. It will also include everything defined in the PYTHONPATH environment variable. So, if you have two directories with .py files, you can either put both in python path, or you can make sure everything all of your source is under the same path entry. Option 1 (this syntax depends on your shell, here it is for windows) set PYTHONPATH=%PYTHONPATH%;\path\to\second_folder python \path\to\first_folder\a.py Then, you can simply import b. Option 2 Create an empty __init__.py in both directories and a run.py in the directory above them, so you have: root_dir run.py first_folder __init__.py a.py sedond_folder __init__.py b.py Make run.py your entry point (run python run.py) and then you can import any of the modules from any other module using their full module names: import first_folder.a import second_folder.b
type: Answer

http://stackoverflow.com/comment/88120291
has text: Is your objection to argparse merely that is raises `SystemExit`? If so, you can catch that in a `try: ... except SystemExit ...` structure and deal with it. Or is your objection that you don't want to predefine the allowed options? If so, argparse won't work so well.
comment on: http://stackoverflow.com/q/50554698
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88383108
has text: I think you're asking the same thing as another [recent question](https://stackoverflow.com/questions/50685522/remove-duplicate-rows-regardless-of-new-information-pyspark). The solution is the same as what Wen suggested- `mydf.groupBy(...).agg(...)...dropDuplicates(subset=["code"])`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50686007
score: 1

http://stackoverflow.com/comment/88245815
type: AnswerComment
has text: Thank you, Zero. Your answer is more advanced as it requires knowledge of regular expression.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50616648

http://stackoverflow.com/a/62758102
has body: From Github https://github.com/jupyter/notebook/issues/4079#issuecomment-429475420 go to directory: /python/share/jupyter/kernels/ open the file "kernel.json", and set the "argv": the python path for example. { "argv": [ "C:\Anaconda3\python.exe", "-m", "ipykernel_launcher", "-f", "{connection_file}" ], "display_name": "Python 3", "language": "python" } launch jupyter notebook. Everything is fine now.
type: Answer
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/50687077
score: 4

http://stackoverflow.com/comment/88375540
comment on: http://stackoverflow.com/a/50682350
type: AnswerComment
has text: thanks for the explanation. but, error appears: img = Image.open (StringIO (banner.read ())) AttributeError: object 'str' has no 'read' attribute
score: 0
type: Comment

http://stackoverflow.com/comment/88108070
type: QuestionComment
score: 2
has text: I expect the error is the `if Headlines:`, not the enumerate. The error traceback message should give you the exact line that caused the error; it would have been more helpful to post the entire message.
comment on: http://stackoverflow.com/q/50548607
type: Comment

http://stackoverflow.com/a/50636358
upvote count: 3
has body: You can't prevent the module being assigned under its real name. After all, the following has to set attributes foo and bar on the package module object: # pkg/__init__.py from .foo import bar You can of course del the name after it's been added (by importing it): # pkg/__init__.py from . import foo as bar del foo But watch out: it leads to strange situations like &gt;&gt;&gt; import pkg.foo &gt;&gt;&gt; from pkg.foo import a &gt;&gt;&gt; pkg.foo Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: module 'pkg' has no attribute 'foo' &gt;&gt;&gt; import pkg.bar Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named 'pkg.bar' &gt;&gt;&gt; pkg.bar.a is a True &gt;&gt;&gt; from pkg.bar import a Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named 'pkg.bar' Of course this doesn't matter so much if the status of pkg.bar as a module is considered an implementation detail, so that no one will be issuing imports like these. It also matters less if you're adding an alias without suppressing the true name. (In your case, why not call lex_c89.py just c89.py? The whole package is a lexer anyway&hellip;) Even then, such hiding precludes the performance benefit of importing only the modules that you need, since the user can't indicate what they need.
score: 3
has comment: http://stackoverflow.com/comment/88318681
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50633897
answers question: http://stackoverflow.com/q/50633897
type: Answer

http://stackoverflow.com/q/50558056
downvote count: 1
has comment: http://stackoverflow.com/comment/88127333
type: Question
has answer: http://stackoverflow.com/a/50558063
possible better answer: http://stackoverflow.com/a/50558168
has answer: http://stackoverflow.com/a/50558464
score: 0
linked to: http://stackoverflow.com/q/3416401
has body: I have a list a = ['https://example.co/embed/qACAB6TukkU/The.Ha-az.VOST.WEBRip.XviD-ZT.W.avi', 'https://example.co/embed/l31lsZilT2E/The.Ha-az-ndmaids.FR.HDTV.XviD-ZT.W.avi', 'https://example.com/embed/soslnnqnmccmplfa/The_Ha-az02_VOST_WEBRip_XviD-ZT_W_avi', 'https://example.com/embed/pffpmptfpdfqddap/The_Ha-az-_Tale_S2_FRENCH_HDTV_XviD-ZT_W_avi'] I want to remove every item in that list that contain word "VOST" in the link. This what I know and what I have tried: a.remove('VOST') print a
accepted answer: http://stackoverflow.com/a/50558063
favorite count: 0
has title: how to remove an item from a list in python if that item contains a word
has answer: http://stackoverflow.com/a/50558324
tagged with: web-scraping
upvote count: 1
tagged with: python
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50558168

http://stackoverflow.com/a/50547129
score: 1
upvote count: 1
has body: What you're looking for is all characters . that appear one or more times +. And you want to ensure that another pattern occurs afterwards without including it in the match, also known as a "positive lookahead" (?=). .+(?=HELLO WORLD) Demo 1 If you want to match newline characters, you can simply expand the meaning of . by using the s flag/modifier. Demo 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50546899

http://stackoverflow.com/q/50585523
has title: Python code run through VBA - want to output log to text file
tagged with: python
has body: I am trying to run the below VBA code that runs a python script and copies the log output to a text file. The script runs fine but the text files are not created. Please help. Dim wsh As Object Set wsh = VBA.CreateObject("WScript.Shell") Dim waitOnReturn As Boolean: waitOnReturn = True Dim windowStyle As Integer: windowStyle = 1 wsh.Run "C:\Users\mmodi1\AppData\Local\Continuum\anaconda3\python.exe Hello_World.py 1&gt;code_log.txt 2&gt;code_error.txt" I want to save the log to code_log.txt and errors to code_error.txt. The above code runs the python script but does not create the text files.
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/88183751
has comment: http://stackoverflow.com/comment/88183461
has comment: http://stackoverflow.com/comment/88288952
score: 0
has comment: http://stackoverflow.com/comment/88182732
tagged with: vba
has comment: http://stackoverflow.com/comment/88181958
type: UnansweredQuestion

http://stackoverflow.com/comment/88134454
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50558333
has text: It sounds like you are using the development server to run your site, which you **must not do**.

http://stackoverflow.com/comment/88215141
comment on: http://stackoverflow.com/a/50602875
score: 0
type: AnswerComment
type: Comment
has text: @jceg316 - are data numeric? What return `df.col2.dtype` ?

http://stackoverflow.com/q/50577029
type: Question
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/88164221
has body: I was doing deep run using Keras. However, the following error occurred in the process of storing the model after learning. TypeError: can't pickle NotImplementedType objects I had no problem when I ran the same code in another directory. The code below is the portion of the code that is causing the error. .... model.add(Dense(2, activation='relu')) model.add(Dense(1, activation='sigmoid')) model = multi_gpu_model(model, gpus=4) model.compile(loss='binary_crossentropy', optimizer = 'adam', metrics = ['accuracy']) model.fit(x_train,y_train,epochs = 3, batch_size =500) scores = model.evaluate(x_test,y_test) #print("%s:.2f%%"%(model.metrics_names[1], scores[1]*100)) model.save('/disk3/seaice/seaice_keras_model2.h5') Is the type error of pickle appearing in the storage method inside the keras? It's also the same environment, but I don't know why it works differently in different directories. I'd appreciate it if you could provide me with a solution to this problem.
answer count: 1
accepted answer: http://stackoverflow.com/a/50577351
tagged with: keras
favorite count: 0
has title: TypeError: can't pickle NotImplementedType objects (in keras, python)
has comment: http://stackoverflow.com/comment/88164251
tagged with: pickle
tagged with: python
has answer: http://stackoverflow.com/a/50577351
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/50664537
type: Question
has comment: http://stackoverflow.com/comment/88339130
has title: Stopping a while loop when a condition is met in a userinput list
has comment: http://stackoverflow.com/comment/88339107
tagged with: while-loop
downvote count: 3
accepted answer: http://stackoverflow.com/a/50664565
answer count: 1
favorite count: 0
tagged with: python-3.x
has body: Please I'm trying to create a register that appends to a list the user input, breaks and returns to the prompt for user to "input data" but only stops when a string "done" is inputed. userinput = input("Please Input price: ") price = [userinput] while True: if price.append(userinput) is True: print(price) if price.append("done") is True: break print(price)
has answer: http://stackoverflow.com/a/50664565
score: -3
tagged with: python
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/q/50542981
score: 2
type: AnsweredQuestion
upvote count: 2
has body: I have a dataset like this: user_id communication_type 7 Newsletter 7 Newsletter 7 Newsletter 7 Newsletter 7 Conference 7 Upcoming Events 7 Upcoming Events 7 Upcoming Events 7 Conference 7 Conference 7 Webinar 7 Hackathon Desired Output: user_id communication_type sent_past 7 Newsletter 0 7 Newsletter 1 7 Newsletter 2 7 Newsletter 3 7 Conference 0 7 Upcoming Events 0 7 Upcoming Events 1 7 Upcoming Events 2 7 Conference 1 7 Conference 2 7 Webinar 0 7 Hackathon 0 Basically get a counter at each level of communication_type for a particular user_id. The solutions which is working for me: train['sent_past'] = train.groupby(['user_id','communication_type']).apply(lambda x: x.reset_index()).index.get_level_values(1) But it's very slow on ~1m rows. How can I optimize it?
type: Question
has answer: http://stackoverflow.com/a/50543001
accepted answer: http://stackoverflow.com/a/50543001
tagged with: group-by
tagged with: counter
has title: Creating counter at group by level in pandas Dataframe, optimization
tagged with: optimization
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/88127410
has text: Thanks for finding the code that actually does this. :)
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50558082
type: Comment

http://stackoverflow.com/q/50551039
has comment: http://stackoverflow.com/comment/88114034
accepted answer: http://stackoverflow.com/a/50551184
upvote count: 1
answer count: 1
tagged with: group-by
has title: How to obtain the row number of a Pandas DataFrame after groupby
tagged with: dataframe
has body: uid label 0 1 0 2 1 1 7 1 0 I group the DataFrame by uid to get the above group. How can I obtain the row number [0,2,7]? I tried group.index().tolist() but got TypeError:'Int64Index' object is not callable Thanks a lot !
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/50551184
has comment: http://stackoverflow.com/comment/88112925
favorite count: 0
type: Question
tagged with: pandas
tagged with: python
score: 1

http://stackoverflow.com/q/50547975
has comment: http://stackoverflow.com/comment/88108665
type: Question
has comment: http://stackoverflow.com/comment/88125627
has comment: http://stackoverflow.com/comment/88106894
has comment: http://stackoverflow.com/comment/88199337
score: 0
has comment: http://stackoverflow.com/comment/88106876
has body: I am making webscraper of a sort, and i made simple function where you pars xpath of an element and if its a multiple elements a number for list index. But i want to do some debugging, some times function isnt working, and i made simple try/except so it will give me some sort of info why it failed instead of whole code going to dead stop this is the function: def getting_company(xpath, number): try: data_element = driver.find_elements_by_xpath(str(xpath)) all_elements = len(data_element) elemet_text = data_element[int(number)].text print(" this is range of a list : " + str(all_elements)) return elemet_text except: data_element = driver.find_elements_by_xpath(str(xpath)) print(" this is range of a list : " + str(all_elements)) return "not found" Now, i am interested, when i use that function and assing it to some variable lets say random_varriable = getting_company(xpath, number) is there any way to include name "random variable" into the function automaticly, somehow to parse that paticular name without adding string "random variable"? So i want if i call: variable1 = getting_company(xpath, number) variable2 = getting_company(xpath, number) and if function fails: "variable 1 had x len of elements" "variable 2 had x len of elements" but without typing "variable 1 " + function return after the function rather to have that incoporated into the function. I am hoping that i was clear... i dont know how to explane it better since english isnt my first language.
tagged with: python
tagged with: parsing
has title: parsing variable name into functions, python
answer count: 0
type: UnansweredQuestion
tagged with: selenium
tagged with: web-scraping

http://stackoverflow.com/a/50659763
has body: You should be able to do: data = base64.b64encode(myFile) dataToSend = json.dumps({"id":"1283","filename":"cat.jpeg", "file":data}) and then send through the socket. When you receive the data on the other end of the socket, just do: jsonDict = json.loads(dataReceived) data = base64.b64decode(jsonDict["file"]) A better way might be to just use bson, https://github.com/py-bson/bson. from gevent import monkey, socket monkey.patch_all() import bson bson.patch_socket() with open("cat.jpeg", "rb") as f: myFile = f.read() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("127.0.0.1", 12345)) s.sendobj({u"id": "1283", u"filename": "cat.jpeg", u"file": myFile})
answers question: http://stackoverflow.com/q/50659391
type: Answer
has comment: http://stackoverflow.com/comment/88329724
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88333720
upvote count: 1

http://stackoverflow.com/comment/88385114
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50687364
has text: Yeah but this only make fields "read_only" and i cant write on them. I'm searching something like: my input is 'uuid' server gives me 'name', 'content' and 'rating'.
type: AnswerComment

http://stackoverflow.com/q/50580196
tagged with: arrays
has title: numpy create array of all coordinates
favorite count: 0
possible better answer: http://stackoverflow.com/a/50580350
has body: I want to create a list of all possible (x,y) values. For example - for input (x=2,y=3) the output should be: np.array([ [0,0], [0,1], [0,2], [1,0], [1,1], [1,2]]) The order doesn't really matter
tagged with: python
has comment: http://stackoverflow.com/comment/88169628
has answer: http://stackoverflow.com/a/50580350
upvote count: 3
has answer: http://stackoverflow.com/a/50580272
linked to: http://stackoverflow.com/q/1208118
type: AnsweredQuestion
score: -1
has comment: http://stackoverflow.com/comment/88170741
has comment: http://stackoverflow.com/comment/88169633
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/45857465
answer count: 2
downvote count: 4
has comment: http://stackoverflow.com/comment/88169626
accepted answer: http://stackoverflow.com/a/50580272

http://stackoverflow.com/comment/88129334
has text: I get same error - `python: 3.6.4.final.0, pandas: 0.23.0, numpy: 1.14.3`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50559330

http://stackoverflow.com/q/50692113
has body: I'm trying to install cvxpy on Windows 10 with Python 3.6.5. I've installed Anaconda 5.2 but the package website says that, given my version I should go with pip. I tried doing so but I'm stuck with these errors. Any help? (base) C:\WINDOWS\system32&gt;pip install cvxpy Collecting cvxpy Using cached https://files.pythonhosted.org/packages/a1/59/2613468ffbbe3a818934d06b81b9f4877fe054afbf4f99d2f43f398a0b34/cvxpy-1.0.3.tar.gz Requirement already satisfied: osqp in c:\users\aimmi\anaconda3\lib\site-packages (from cvxpy) (0.3.0) Collecting ecos&gt;=2 (from cvxpy) Using cached https://files.pythonhosted.org/packages/b6/b4/988b15513b13e8ea2eac65e97d84221ac515a735a93f046e2a2a3d7863fc/ecos-2.0.5.tar.gz Collecting scs&gt;=1.1.3 (from cvxpy) Using cached https://files.pythonhosted.org/packages/b3/fd/6e01c4f4a69fcc6c3db130ba55572089e78e77ea8c0921a679f9da1ec04c/scs-2.0.2.tar.gz Collecting multiprocess (from cvxpy) Requirement already satisfied: fastcache in c:\users\aimmi\anaconda3\lib\site-packages (from cvxpy) (1.0.2) Requirement already satisfied: six in c:\users\aimmi\anaconda3\lib\site-packages (from cvxpy) (1.11.0) Requirement already satisfied: toolz in c:\users\aimmi\anaconda3\lib\site-packages (from cvxpy) (0.9.0) Requirement already satisfied: numpy&gt;=1.13 in c:\users\aimmi\anaconda3\lib\site-packages (from cvxpy) (1.14.3) Requirement already satisfied: scipy&gt;=0.19 in c:\users\aimmi\anaconda3\lib\site-packages (from cvxpy) (1.1.0) Requirement already satisfied: future in c:\users\aimmi\anaconda3\lib\site-packages (from osqp-&gt;cvxpy) (0.16.0) Collecting dill&gt;=0.2.6 (from multiprocess-&gt;cvxpy) Collecting pyreadline&gt;=1.7.1 (from dill&gt;=0.2.6-&gt;multiprocess-&gt;cvxpy) Building wheels for collected packages: cvxpy, ecos, scs Running setup.py bdist_wheel for cvxpy ... done Stored in directory: C:\Users\aimmi\AppData\Local\pip\Cache\wheels\2b\60\0b\0c2596528665e21d698d6f84a3406c52044c7b4ca6ac737cf3 Running setup.py bdist_wheel for ecos ... error Complete ou…
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50698293
type: Question
has title: CVXPY installation issues
linked to: http://stackoverflow.com/q/50591149
score: 2
tagged with: cvxpy
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50698293
upvote count: 2
tagged with: python

http://stackoverflow.com/q/50585828
type: AnsweredQuestion
tagged with: root
upvote count: 1
downvote count: 1
type: Question
tagged with: parallel-ssh
has answer: http://stackoverflow.com/a/66667839
has answer: http://stackoverflow.com/a/50637461
has answer: http://stackoverflow.com/a/50585976
score: 0
possible better answer: http://stackoverflow.com/a/66667839
answer count: 3
has body: I want to log in to two hosts using parallel-ssh and execute su command. Then I want to confirm that I am the root user by printing out whoami Code: hosts = ['myHost1', 'myHost2'] client = ParallelSSHClient(hosts, user='myUser', password='myPassword') output = client.run_command('su') for host in output: stdin = output[host].stdin stdin.write('rootPassword\n') stdin.flush() client.join(output) output = client.run_command('whoami') for host, host_output in output.items(): for line in host_output.stdout: print("Host [%s] - %s" % (host, line)) Result: Host [myHost1] - myUser Host [myHost2] - myUser Obviously, I expect root in the output. I am following the documentation. I've tried using all different line endings instead of \n and nothing has changed. How can I execute su command using parallel-ssh?
favorite count: 0
tagged with: stdin
tagged with: linux
accepted answer: http://stackoverflow.com/a/50637461
tagged with: python
has title: How to execute 'su' command using parallel-ssh

http://stackoverflow.com/a/50614910
has comment: http://stackoverflow.com/comment/88239802
has comment: http://stackoverflow.com/comment/88239950
has comment: http://stackoverflow.com/comment/88239760
has comment: http://stackoverflow.com/comment/88239913
has comment: http://stackoverflow.com/comment/88240210
type: Answer
has body: You can try something like follows: folders = ['../folder2/','../folder1/'] checked =[] for folder in folders: for filename in os.listdir(folder): if filename not in checked: checked.append(filename) path = os.path.join(folder, filename) if os.path.isdir(path): continue with open(folder + filename, 'r') as myfile: data = myfile.read() query_name = filename.replace(".sql", "") exec (query_name + " = data")
has comment: http://stackoverflow.com/comment/88239723
has comment: http://stackoverflow.com/comment/88240233
answers question: http://stackoverflow.com/q/50614844
score: 0
has comment: http://stackoverflow.com/comment/88239780
has comment: http://stackoverflow.com/comment/88239861

http://stackoverflow.com/comment/88243788
comment on: http://stackoverflow.com/q/50616566
has text: You can uninstall those packages first. See [this answer](https://stackoverflow.com/a/42299244/2011147)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50642176
answers question: http://stackoverflow.com/q/50641788
has comment: http://stackoverflow.com/comment/88297090
has comment: http://stackoverflow.com/comment/88295533
accepted answer of: http://stackoverflow.com/q/50641788
has comment: http://stackoverflow.com/comment/88296812
has comment: http://stackoverflow.com/comment/88294976
score: 1
has comment: http://stackoverflow.com/comment/88298181
has comment: http://stackoverflow.com/comment/88295216
has comment: http://stackoverflow.com/comment/88296094
has comment: http://stackoverflow.com/comment/88294657
has comment: http://stackoverflow.com/comment/88298223
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You should compare the list with the actual values with a bitwise exclusive or (^): differences = set(one["1iG5NDGVre"]["118"]) ^ set(two["1iG5NDGVre"]["118"]) print differences

http://stackoverflow.com/q/50568880
has title: can't pickle _tkinter.tkapp objects error when trying to create multiple instances of the same class
has comment: http://stackoverflow.com/comment/88171255
has comment: http://stackoverflow.com/comment/88156174
has body: I'm becoming really frustrated because of this problem. I had it before and i fixed it, but it came back again when i changed something in my code. To be precise i'm trying to create multiple instances of a class when i'm pressing a button. I am using python 3.6 with tkinter. When i was first writing my class i was using a rectangle (created by using create_rectangle method) for visual representation. After my class was behaving the way i wanted it to i wanted to use a photo to apear on my canvas instead of the rectangle. As the title sugested my main error is "can't pickle _tkinter.tkapp objects" and before that there are a lot of errors about deepcopy. This is the full error https://pastebin.com/nAQifmnA Before using an image this fix worked Can&#39;t pickle _tkinter.tkapp objects I forgot to mention, for the image i am using PhotoImage class. This is where i try to create more instances of the class. This method is inside the actual class, maybe that's the problem? I tried different things but they are not working. def newAdd(): global And_list test=AND(10,10) And_list.append(deepcopy(test)) And_list =listRecord()
answer count: 1
downvote count: 0
favorite count: 0
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/50571179
tagged with: pickle
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88150253
linked to: http://stackoverflow.com/q/39987858
has comment: http://stackoverflow.com/comment/88151622
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50571179
type: Question

http://stackoverflow.com/q/50559586
downvote count: 0
accepted answer: http://stackoverflow.com/a/50570204
tagged with: keras
has title: Deep Learning YOLO Object Detection: How to iterate over cells in a grid defined over the image
tagged with: deep-learning
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50570204
favorite count: 0
upvote count: 3
type: AnsweredQuestion
score: 3
tagged with: conv-neural-network
tagged with: tensorflow
type: Question
has body: I am trying to implement the YOLOv2 Object Detection algorithm myself, just to learn how the algorithm works. Of course I will use pre-trained weights to make things faster. I was using the code from the keras-yolo2 repository as a basis for my own code, but I had a question about how the code related back to the underlying YOLO algorithm. As I understand it--from a high level--YOLO (You Only Look Once) will: Break the image into an SxS grid. For each cell in the grid, conduct classification and assign probabilities to each potential label. Prune the classified boxes based upon whether the box/class confidence exceeds some threshold. Multiple other things happen after this point, including non-max suppression, etc. I was looking at some code in the aforementioned repository to try and figure out how the author actually breaks the image into the SxS grid in order to execute the object classification within the cells. Can anyone see where that piece of the algorithm happens in the code below. It could be that my knowledge of tensorflow is lacking, but I could not tell where this is implemented in the code below. Seems like the initial call to cell_x = tf.to_float(tf.reshape(tf.tile(tf.range(GRID_W), [GRID_H]), (1, GRID_H, GRID_W, 1, 1))) would break down the image into cells, but I don't understand how this would work without looping over each grid cell? I also don't understand how tf.reshape and tf.tile and tf.range work in concert with each other to break down the picture to a cell. Any help would be appreciated. IMAGE_H, IMAGE_W = 416, 416 GRID_H, GRID_W = 13 , 13 BOX = 5 CLASS = len(LABELS) CLASS_WEIGHTS = np.ones(CLASS, dtype='float32') OBJ_THRESHOLD = 0.3#0.5 NMS_THRESHOLD = 0.3#0.45 ANCHORS = [0.57273, 0.677385, 1.87446, 2.06253, 3.33843, 5.47434, 7.88282, 3.52778, 9.77052, 9.16828] NO_OBJECT_SCALE = 1.0 OBJECT_SCALE = 5.0 COORD_SCALE = 1.0 CLASS_SCALE = 1.0 BATCH_SIZE = 16 WARM_UP_BATCHES = 0 TRUE_BOX_BUFFER = 50 def custom_loss(y_true, y_pred): mask_shape = t…

http://stackoverflow.com/a/50643848
downvote count: 0
answers question: http://stackoverflow.com/q/50641866
score: 3
has comment: http://stackoverflow.com/comment/88304975
has body: Two things I see from looking at your network: Sigmoid activation in the hidden layers is usually a bad choice. The sigmoid function saturates for large (positive or negative) inputs, resulting in the gradient becoming smaller and smaller as it is backpropagated through the networks. This is commonly referred to as the "vanishing gradient" problem. It could be that the gradient for variables near the output is "healthy" and thus the upper layers are learning, however if the lower layers don't receive any gradient they will simply keep returning random values that the higher layers can't work with. You could try replacing the sigmoid activations with e.g. tf.nn.relu. Sigmoid in the output layer is okay (and kinda necessary if you want your outputs to be 0/1), however consider using cross entropy instead of squared error as a loss function instead. Your weight initialization likely results in excessively large weights. Standard deviation of 1.0 is way too high. This can lead to numerical issues as well as saturating the activations even more (since due to the large weights you can expect to have large activation values from the start). Try something like an std of 0.1, and consider using truncated_normal instead to prevent outliers (or use a uniform random initalization). It's difficult to say whether this will fix your issues, however I believe both of these are things you should definitely change about your network as it is right now.
upvote count: 3
type: Answer

http://stackoverflow.com/comment/88301214
comment on: http://stackoverflow.com/a/50643870
type: Comment
has text: I would guess the downvote might be because although you answered the question you should also have advised them against using string formatting at all to produce JSON.
score: 0
type: AnswerComment

http://stackoverflow.com/q/50664839
tagged with: python-3.x
has body: I have gone through many posts but did not found the exact way to do the below. Sorry for attaching screenshot(Just for better visibility) as well , I will write it also. Basically it looks like - Name_of_the_Man Address_of_Man City Jordan NC LMN Input csv looks like Output Needed I have this code with me that picks the csv and attach as sheet in excel. writer = pd.ExcelWriter('final.xlsx'), engine='xlsxwriter') for f in glob.glob(os.path.join(Path, "*.csv")): df = pd.read_csv(f) df.to_excel(writer, sheet_name=os.path.basename(f)) writer.save() I want my csv file - having good space in between and color for the column header.I have went through this link Python - change header color of dataframe and save it to excel file but it's not serving the purpose - It is coloring the sheet itself apart from column. Update: Got the answer below . Also wondering if that can be possible just a thought
has title: Format Excel Column header for better visibility and Color
has answer: http://stackoverflow.com/a/50665603
tagged with: python
tagged with: excel
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88339982
linked to: http://stackoverflow.com/q/17326973
type: Question
accepted answer: http://stackoverflow.com/a/50665603
downvote count: 0
linked to: http://stackoverflow.com/q/41339701
upvote count: 8
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
favorite count: 0
score: 8

http://stackoverflow.com/comment/88228472
type: Comment
has text: Thank you, Daniel. It works. The code I put is : encoder2 = Model(inputs=autoencoder.input, outputs=autoencoder.get_layer("max_pooling2d_3").output) y = encoder2.predict(x_test)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50597047

http://stackoverflow.com/a/54376598
score: 4
upvote count: 4
downvote count: 0
has body: It seems you can do slightly faster by using a uniform sampling and then "inverting" the cumulative distrubtion using np.searchsorted: # assume arbitrary probabilities weights = np.random.randn(1000)**2 weights /= weights.sum() def weighted_random(w, n): cumsum = np.cumsum(w) rdm_unif = np.random.rand(n) return np.searchsorted(cumsum, rdm_unif) # first method %timeit np.random.choice(a = 1000, size = 1000, replace = True, p = weights) # 10000 loops, best of 3: 220 µs per loop # proposed method %timeit weighted_random(weights, n) # 10000 loops, best of 3: 158 µs per loop Now we can check empirically that the probabilities are correct: samples =np.empty((10000,1000),dtype=int) for i in xrange(10000): samples[i,:] = weighted_random(weights) empirical = 1. * np.bincount(samples.flatten()) / samples.size ((empirical - weights)**2).max() # 3.5e-09
type: Answer
answers question: http://stackoverflow.com/q/50548775

http://stackoverflow.com/comment/88387679
type: QuestionComment
has text: so, I should have access to all the methods of the mocked function correct? ie; how can I call the cursor method of the connection function?
comment on: http://stackoverflow.com/q/50688660
score: 0
type: Comment

http://stackoverflow.com/comment/88319410
comment on: http://stackoverflow.com/a/50651267
type: AnswerComment
has text: Heads up, for fairness. VLQs and duplicates that you've answered in the past are appearing, one after the other, in the deletion queue. Search "user:me deleted:1" to see what answers of yours are being deleted along with them. If you notice you're leaking rep, this is the reason. I also presume that this answer is the cause of the targeted deletion.
score: 0
type: Comment

http://stackoverflow.com/comment/88107210
comment on: http://stackoverflow.com/q/50546760
score: 0
has text: No need to visualize, or make your own inaccurate pictures. See RFC 2246. Does your server have a private key?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50604451
has answer: http://stackoverflow.com/a/66515275
tagged with: django-admin
downvote count: 0
tagged with: django-models
score: 4
has comment: http://stackoverflow.com/comment/88218324
has comment: http://stackoverflow.com/comment/88219550
answer count: 1
has comment: http://stackoverflow.com/comment/88220616
tagged with: django-oscar
has comment: http://stackoverflow.com/comment/88221991
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88220216
has body: I have configured some django signals on the pre_delete, post_save and pre_delete receivers for some models which are stored in a signals.py file in the same package as the models. Saving from an API call or directly in the terminal triggers the signals but when saving from the Admin dashboard they are not fired. I have imported the signals in the ready() method of the AppConfig which changes nothing. Any help on this issue? PS: Using django-oscar if that helps. from django.db.models.signals import post_delete, post_save, pre_delete from django.dispatch import receiver from oscar.core.loading import get_model MyModel = get_model('mypackage', 'MyModel') @receiver(post_save, sender=MyModel) def do_stuff(sender, instance=None, created=False, **kwargs): update_stuff()
has title: Django signals not fired when saving from admin interface
has comment: http://stackoverflow.com/comment/88218805
type: Question
upvote count: 4

http://stackoverflow.com/a/50761312
has body: It was harded than i thought so , using regex was more practical way to solve this problem.
accepted answer of: http://stackoverflow.com/q/50666586
type: AcceptedAnswer
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50666586

http://stackoverflow.com/comment/88313838
has text: Possible duplicate of [Linux: Prevent a background process from being stopped after closing SSH client](https://stackoverflow.com/questions/285015/linux-prevent-a-background-process-from-being-stopped-after-closing-ssh-client)
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50651416

http://stackoverflow.com/comment/88155616
score: 0
has text: @Blckknght can you show me an example for get? I'm new to the multiprocessing library ,,,
comment on: http://stackoverflow.com/q/50572875
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88480702
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50696038
has text: Is *demo.log* in the printed list?

http://stackoverflow.com/comment/88231959
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50611024
has text: What is your intended/expected output?
score: 0

http://stackoverflow.com/comment/88182254
has text: Do you want to print the structure of if/else control structure?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50586329

http://stackoverflow.com/comment/88199451
comment on: http://stackoverflow.com/q/50595150
has text: Why is the first entry not deleted?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50614240
type: Question
has comment: http://stackoverflow.com/comment/88238459
has title: module 'networkx' has no attribute 'minimum_cycle_basis'
score: 0
has comment: http://stackoverflow.com/comment/88238350
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88238347
tagged with: networkx
has comment: http://stackoverflow.com/comment/88238438
has body: I installed networkx v. 2.1, but when I want to use minimum_cycle_basis, python shows this error module 'networkx' has no attribute 'minimum_cycle_basis' Thanks for helping

http://stackoverflow.com/q/50612215
has answer: http://stackoverflow.com/a/61631370
upvote count: 10
tagged with: tensorflow
type: Question
score: 10
has body: Is there a way to modify the composition of my images within a batch? At the moment, when I'm creating e.g. a batch with the size of 4, my batches will look like that: Batch1: [Img0 Img1 Img2 Img3] Batch2: [Img4 Img5 Img6 Img7] I need to modify the composition of my batches so that it will only shift once to the next image. Then it should look like that: Batch1: [Img0 Img1 Img2 Img3] Batch2: [Img1 Img2 Img3 Img4] Batch3: [Img2 Img3 Img4 Img5] Batch4: [Img3 Img4 Img5 Img6] Batch5: [Img4 Img5 Img6 Img7] I'm using in my code the Dataset API of Tensorflow which looks as follows: def tfrecords_train_input(input_dir, examples, epochs, nsensors, past, future, features, batch_size, threads, shuffle, record_type): filenames = sorted( [os.path.join(input_dir, f) for f in os.listdir(input_dir)]) num_records = 0 for fn in filenames: for _ in tf.python_io.tf_record_iterator(fn): num_records += 1 print("Number of files to use:", len(filenames), "/ Total records to use:", num_records) dataset = tf.data.TFRecordDataset(filenames) # Parse records read_proto = partial(record_type().read_proto, nsensors=nsensors, past=past, future=future, features=features) # Parallelize Data Transformation on available GPU dataset = dataset.map(map_func=read_proto, num_parallel_calls=threads) # Cache data dataset = dataset.cache() # repeat after shuffling dataset = dataset.repeat(epochs) # Batch data dataset = dataset.batch(batch_size) # Efficient Pipelining dataset = dataset.prefetch(2) iterator = dataset.make_one_shot_iterator() return iterator
has answer: http://stackoverflow.com/a/50612726
accepted answer: http://stackoverflow.com/a/50612726
answer count: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/61631370
has answer: http://stackoverflow.com/a/58172021
favorite count: 0
tagged with: tensorflow-datasets
tagged with: python
has title: Sliding window of a batch in Tensorflow using Dataset API
type: AnsweredQuestion

http://stackoverflow.com/a/50628131
has comment: http://stackoverflow.com/comment/88266696
has comment: http://stackoverflow.com/comment/88266582
type: AcceptedAnswer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88266611
has comment: http://stackoverflow.com/comment/88266654
type: Answer
upvote count: 1
has body: This might be what you are looking for: a = 'first' b = 'second' '{0} {0} {0} {1}'.format(a, b) #first first first second
accepted answer of: http://stackoverflow.com/q/50628061
has comment: http://stackoverflow.com/comment/88266724
answers question: http://stackoverflow.com/q/50628061

http://stackoverflow.com/a/50600191
upvote count: 0
answers question: http://stackoverflow.com/q/50599838
downvote count: 2
has comment: http://stackoverflow.com/comment/88209633
score: -2
has body: you can do do something like below: validInput = set(['+','-','*','/']) checkString = '12-23+23*12*12' def checkInput(input): if input not in validInput: raise Exception return input def findSign(sign,string): sign = checkInput(sign) if sign in string: return string.find(sign) return -1 print(findSign('/',checkString))
type: Answer
has comment: http://stackoverflow.com/comment/88209657

http://stackoverflow.com/a/50612409
has body: In the first version of your code, you append the same list that it's being updated at every iteration. In the end, all the lisc you appended will be a reference to the same list In the second version, you append a new copy of the modified list. Those copies are all different object
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50612212

http://stackoverflow.com/comment/93280592
comment on: http://stackoverflow.com/q/50568252
type: QuestionComment
has text: Possible duplicate of [Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4](https://stackoverflow.com/questions/17610732/error-dictionary-update-sequence-element-0-has-length-1-2-is-required-on-dj)
score: 0
type: Comment

http://stackoverflow.com/comment/88228957
type: QuestionComment
comment on: http://stackoverflow.com/q/50609615
has text: When you say you have an `array`, are you referring to Python's `array.array` type or a `numpy.ndarray` type? Or - do you have a native Python list of lists?
score: 0
type: Comment

http://stackoverflow.com/comment/89506175
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50675532
has text: Stop editing your post to say it's resolved. The content stays on the site, as you agreed to by posting here.
score: 0

rate-limiting
tags question: http://stackoverflow.com/q/50614671
type: Tag
tag name: rate-limiting
tags question: http://stackoverflow.com/q/50559630

http://stackoverflow.com/a/50543804
accepted answer of: http://stackoverflow.com/q/50542608
type: AcceptedAnswer
score: 1
answers question: http://stackoverflow.com/q/50542608
type: Answer
upvote count: 1
has body: The import should be relative to the package. from calendarlib.database import db instead of from database import db From looking at the github repo it looks like the line is correct there... Maybe you should re-install with pip?
downvote count: 0

http://stackoverflow.com/a/50543126
has body: You should definitely look into updating your modules if they have known vulnerabilities. A quick Google of tools that might help you with this turned out a couple of interesting hits: OWASP Dependency Check safety OSS Index Typically open source software use semantic versioning (or semver) to provide some idea on how upgrading to a specific version will affect you. Specifically the guidelines for what "part" of the version to change depends on how backwards-compatible the change is going to be: Given a version number MAJOR.MINOR.PATCH, increment the: MAJOR version when you make incompatible API changes, MINOR version when you add functionality in a backwards-compatible manner, and PATCH version when you make backwards-compatible bug fixes. Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format. But then again, this will always be left to the discretion of the author of the module so I suggest that you start taking time to write unit tests for your code. This way, you'll quickly be able to see if an upgrade to one of the modules will break your code. This should be a good starting point for a list of tools that may help you with writing your tests. If you do decide to upgrade, make sure that you are following good practices in making sure that you specify the correct versions of your dependencies properly and colidyre's answer should help you with that.
score: 4
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/50542620
downvote count: 0

http://stackoverflow.com/q/50591126
has comment: http://stackoverflow.com/comment/88192186
answer count: 0
has comment: http://stackoverflow.com/comment/88191766
score: 0
type: UnansweredQuestion
tagged with: reshape
has comment: http://stackoverflow.com/comment/88192290
type: Question
has body: I have a numpy array, images, of shape (100,) which contains images of shape (72, 72): images.shape # returns (100,) images[0].shape # returns (72, 72) images[42].shape # returns (72, 72) I want to reshape my array to an array of shape = (100, 72, 72), so that the array stores the images "stacked". How do I do this?
tagged with: image
has comment: http://stackoverflow.com/comment/88192138
tagged with: numpy
tagged with: arrays
has comment: http://stackoverflow.com/comment/88191952
has comment: http://stackoverflow.com/comment/88191938
has comment: http://stackoverflow.com/comment/88192129
has comment: http://stackoverflow.com/comment/88191912
has comment: http://stackoverflow.com/comment/88192019
has comment: http://stackoverflow.com/comment/88191740
tagged with: python
has title: Reshaping a numpy array containing images of different sizes

http://stackoverflow.com/q/50655689
favorite count: 0
tagged with: c++
has title: server python client c++ 10061
has body: I have: 1) TCP Server on python, TCP Client on Python - it works (Python 3.6.2 #import socket) 2) TCP Server on C++, TCP Client on C++ - it works (Ws2_32.dll) 3) Trying to connect C++ Client with Python Server - error 10061. Server port is the same everywhere. Cannot understand why. Some suggestions?
type: UnansweredQuestion
upvote count: 1
tagged with: server
downvote count: 3
type: Question
score: -2
has answer: http://stackoverflow.com/a/50664188
answer count: 1
tagged with: python
tagged with: client

http://stackoverflow.com/q/50588279
answer count: 0
type: UnansweredQuestion
downvote count: 1
has comment: http://stackoverflow.com/comment/88186106
has title: Python Wedding Seating plan
score: 3
has body: I am getting married in three months and what to attempt create a python code that will pick my seating plan for me as a project to improve my coding further. On the day there will be 10 tables for 100 guests. I want to build a sample to see how effective it is but struggling with ideas on how best to do it as I am fairly new to python coding. I decided to start with a matrix which determines how much each guest knows each other. The more positive the number the better, the more negative the number the more they dislike each other. Below is an example: 12 guests try would like to try and get 3 tables. Any suggestions on how to optimize this or a better way to go about it would be greatly appreciated.
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/88186063
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88185880
has comment: http://stackoverflow.com/comment/88186224

http://stackoverflow.com/comment/88238859
type: Comment
comment on: http://stackoverflow.com/a/50614447
score: 0
type: AnswerComment
has text: Thanks. But am looking for the last link only.

http://stackoverflow.com/a/50545167
has comment: http://stackoverflow.com/comment/88101522
has comment: http://stackoverflow.com/comment/88101472
type: Answer
has comment: http://stackoverflow.com/comment/88101550
accepted answer of: http://stackoverflow.com/q/50545075
has body: You can accomplish this very quickly with .shift, which shifts an entire DataFrame. Just use pd.concat to combine them together; the axis=1 argument specifies that you want to append new columns instead of rows. import pandas as pd pd.concat([df, df.shift(-1).rename(columns=dict((elem, elem+'1') for elem in df.columns))], axis=1) The above code gives you the following output: Glucosa Insulina Carbs Glucosa1 Insulina1 Carbs1 Hour 2018-05-16 06:43:00 156.0 7.0 65.0 170.0 0.0 65.0 2018-05-16 07:43:00 170.0 0.0 65.0 185.0 2.0 0.0 2018-05-16 08:45:00 185.0 2.0 0.0 150.0 0.0 0.0 2018-05-16 09:45:00 150.0 0.0 0.0 80.0 0.0 0.0 2018-05-16 10:45:00 80.0 0.0 0.0 NaN NaN NaN
answers question: http://stackoverflow.com/q/50545075
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/50652770
answers question: http://stackoverflow.com/q/50648212
has comment: http://stackoverflow.com/comment/88321740
score: 1
accepted answer of: http://stackoverflow.com/q/50648212
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88317089
has comment: http://stackoverflow.com/comment/88381280
upvote count: 1
has body: In the cas of the example you give with df = pd.DataFrame({'V1':[100000,50000, 20000, 30000, 150000, 30000, 20000, 200000]}, index=range(1,9)) Of what I understand of "get the indexes where each time the sum of V1 reaches 50k exactly", you can do it by creating a column with the number of exactly 50k you have in the sum until each row : ser_50k = (df.V1.cumsum()/50000).astype(int) df['nb_50'] = (ser_50k - ser_50k.shift()).fillna(ser_50k).astype(int) Now, you can use stack to create rows with same index when 50k reach several times: df_join = (df['nb_50'].apply(lambda x: pd.Series(range(x))) .stack().reset_index(level=1).drop('level_1',1)) df = df.join(df_join).dropna().drop(['nb_50',0],1) And you get the expected output with your input example. Problem is, when you have df= pd.DataFrame({'V1':[180000, 20000, 30000, 50000]}) My method gives you: V1 0 180000 0 180000 0 180000 1 20000 3 50000 and some errors might happens later, while when you say "when the value V1 is greater than the limit of 50k, then the index repeats as much times the limit is reached, or if the value V1 is lower than the limit of 50k, groups rows until the limit of 50k is reached or passed" and I understand you would expect: V1 0 180000 0 180000 0 180000 2 30000 3 50000 In this case, if you don't want to use a loop, for when the number is above 50K, you can do (about the same idea than before): df = df.join(df['V1'].apply(lambda x: pd.Series(range(x/50000))) .stack().reset_index(level=1).drop('level_1',1)).drop(0,1) But I could not figure out an easy way to do the case where the number is under 50k so your loop for might be enough. otherwise, I thought about this way: def nb_group_under(v1): global nb_group if v1 &lt; 50000: return nb_group else: nb_group += 1 nb_group = 1 df['under_50'] = df['V1'].apply(nb_group_under) then you try to find where 50k is passed in the group created: df['sum_under50'] = (df.groupby('under_50').V1.cumsum()/50000).astype(int) df['sum_under50'] = df.sum_under50 - (df.…

http://stackoverflow.com/comment/88487619
type: AnswerComment
has text: Of Course not! cv2.UMat object doesn't allow index slicing.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50699105

http://stackoverflow.com/comment/88227400
type: Comment
has text: why not just reset_index :-)
type: QuestionComment
comment on: http://stackoverflow.com/q/50608749
score: 0

http://stackoverflow.com/a/50667428
has comment: http://stackoverflow.com/comment/88345364
has body: One way is to align indices and then use a mask. # align indices df1 = df1.set_index(['Company', 'SKU']) df2 = df2.set_index(['Company', 'SKU']) # calculate &amp; apply mask df2 = df2[df2.index.isin(df1.index)].reset_index() Resetting index is not required, but needed to elevate Company and SKU to columns.
upvote count: 5
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/50655370
score: 5

http://stackoverflow.com/q/50548046
tagged with: bash
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88108005
has comment: http://stackoverflow.com/comment/88106919
has comment: http://stackoverflow.com/comment/88106975
has comment: http://stackoverflow.com/comment/88107212
has comment: http://stackoverflow.com/comment/88107106
has comment: http://stackoverflow.com/comment/88107300
has comment: http://stackoverflow.com/comment/88106855
tagged with: linux
type: Question
accepted answer: http://stackoverflow.com/a/50553425
tagged with: python
tagged with: subprocess
has comment: http://stackoverflow.com/comment/88107248
has comment: http://stackoverflow.com/comment/88184798
score: 0
has comment: http://stackoverflow.com/comment/88107303
answer count: 1
has answer: http://stackoverflow.com/a/50553425
has title: Command working in bash terminal but not in Python subprocess.Popen(); getting a 'paths must precede expression: `%p' error
has body: I'm trying to find the location of the file that has been most recently modified. In bash, you can do this through find /media/tiwa/usb/ -not -path '*/\.*' -type f -printf '%T@ %p\n' 2&gt; &gt;(grep -v 'Permission denied' &gt;&amp;2) | sort -k1,1nr | head -1` Indeed, on my system, this returns 1527379702.1060795850 /media/tiwa/usb/hi.txt I intend to take the output of this command (within Python), split it on the first space, and parse the file path (yes, I could use awk, but the same errors get thrown regardless). So I did import subprocess bashCommand = "find /media/tiwa/usb/ -not -path '*/\.*' -type f -printf '%T@ %p\n' 2&gt; &gt;(grep -v 'Permission denied' &gt;&amp;2) | sort -k1,1nr | head -1" process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE) output, error = process.communicate() print(output) but this prints out find: paths must precede expression: `%p' Escaping the backslashes doesn't appear to help either. What is causing this issue, and how do I solve it?
has comment: http://stackoverflow.com/comment/88107177
has comment: http://stackoverflow.com/comment/88106934

http://stackoverflow.com/comment/88329901
type: Comment
type: QuestionComment
has text: id resolve it with: for i in range(3): matrix.append([]) for j in range(4): matrix[i].append(list_[list_index]) list_index += 1
comment on: http://stackoverflow.com/q/50659469
score: 0

http://stackoverflow.com/q/50693322
downvote count: 0
tagged with: keras
has answer: http://stackoverflow.com/a/50695688
accepted answer: http://stackoverflow.com/a/50695688
possible better answer: http://stackoverflow.com/a/50693949
upvote count: 1
tagged with: python
has body: I want to use keras.applications.resnet50 to train a Resnet for a two class problem using the following setup: from keras.layers import Dropout, Flatten, Dense from keras.applications.resnet50 import ResNet50 from keras.models import Model resNet = ResNet50(include_top=False, weights=None) y = resNet.output y = Flatten()(y) y = Dense(2, activation='softmax')(y) model = Model(inputs=resNet.input, outputs=y) opt = keras.optimizers.Adam() model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy']) epochs = 15 model.fit(train_tensors, train_targets, validation_data=(valid_tensors, valid_targets), epochs=epochs, batch_size=10, callbacks=[checkpointer], verbose=1) Running the code throws the error Exception: The shape of the input to "Flatten" is not fully defined So there must be something wrong with the input tensor to the output layer, which in my case is a one-hot encoded vector, i.e. a one-dimensional array of size 2. What am I doing wrong?
favorite count: 0
tagged with: resnet
tagged with: tensorflow
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50693949
score: 1
type: Question
answer count: 2
tagged with: deep-learning
has title: Exception training Resnet50: "The shape of the input to "Flatten" is not fully defined"

http://stackoverflow.com/comment/88127722
comment on: http://stackoverflow.com/q/50558108
score: 0
has text: Filter the dataframe into lesser ones by `Group` and process them. https://chrisalbon.com/python/data_wrangling/filter_dataframes/
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50632848
downvote count: 1
type: AnsweredQuestion
score: -1
has answer: http://stackoverflow.com/a/50632933
linked to: http://stackoverflow.com/q/45349470
type: Question
upvote count: 0
tagged with: sparse-matrix
has comment: http://stackoverflow.com/comment/88276049
tagged with: matrix
accepted answer: http://stackoverflow.com/a/50632933
has comment: http://stackoverflow.com/comment/88276069
answer count: 1
has body: I've tried all of these and had either memory error or some kind of other error. Matrix1 = csc_matrix((130000,130000)).todense() Matrix1 = csc_matrix((130000,130000), dtype=float_).todense() Matrix1 = csc_matrix((130000,130000), dtype=float16).todense() How can I create a huge sparse matrix with float type of data?
favorite count: 0
has title: How to create huge sparse matrix with dtype=float16?
has comment: http://stackoverflow.com/comment/88276012
tagged with: python

http://stackoverflow.com/comment/88321110
comment on: http://stackoverflow.com/q/50655132
has text: @RoryDaulton It was just a thought not any blame :)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50625364
has title: Syntax of Google Drive API requests in Python
answer count: 1
has body: Trying to use the Google Drive API with Python for the first time. This script lists the files in my Google Drive folder. from __future__ import print_function from apiclient import discovery from httplib2 import Http from oauth2client import file, client, tools SCOPES = 'https://www.googleapis.com/auth/drive.readonly.metadata' store = file.Storage('storage.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_id.json', SCOPES) creds = tools.run_flow(flow, store) DRIVE = discovery.build('drive', 'v3', http=creds.authorize(Http())) # List files Google Drive files = DRIVE.files().list().execute().get('files', []) for f in files: print(f['name'], f['mimeType'], f['sharedWithMeTime']) Going through the docs, I'm confused regarding the syntax here: files = DRIVE.files().list().execute().get('files', []) What I (think I) understand: DRIVE is the drive instance; Files is as explained here; List can be called on files, as explained here; What I don't understand: From reading the docs, how could I tell files is a method? Same for list; What is execute() and how would I know to use it from reading the docs? Same question for get() Where can I find the explanation for the parameters to pass to get()? Btw, I figure execute() executes the request, and get() makes an HTTP get request. However, I would like to know it from the docs so I can use these correctly.
score: 0
tagged with: python
tagged with: google-drive-api
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50642109
type: Question

http://stackoverflow.com/comment/88327078
comment on: http://stackoverflow.com/q/50658453
score: 0
type: Comment
type: QuestionComment
has text: Welcome to SO. Please take the time to read [ask] and [mcve]

http://stackoverflow.com/comment/88236639
type: Comment
has text: @InesMontani it might be I am not sure where and how I can setup the `virtualenv` config correct, I just know how to install and run it on the server as if it is local but I know there should be some config that I tried googling but having hard time not sure how to google it. Do you have any idea for examples?
comment on: http://stackoverflow.com/q/50598070
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88103312
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50545735
type: Comment
has text: @MiniMiloe `{k: colors.cnames[k] for k in ['red', 'green', 'blue', 'black', 'yellow']}`

http://stackoverflow.com/q/50584860
has comment: http://stackoverflow.com/comment/88182671
answer count: 0
tagged with: flask
tagged with: buffer
has comment: http://stackoverflow.com/comment/88179380
type: Question
has comment: http://stackoverflow.com/comment/88179298
tagged with: python
score: 0
has title: Storing a file inside a temporary buffer before uploading to S3 bucket. Python Flask
has body: I have an endpoint that gets a parameter "address". Using this parameter I am generating an image and saving it on the OS, uploading it to an s3 - bucket and serve it using the s3-bucket. I feel like the image generation on the OS step is redundant as I do not even serve the image from the OS but It is needed because Amazon s3 askes for the image file to upload. Is there a way to pass it? Maybe storing the image in some kind of buffer? Thanks.
tagged with: amazon-s3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88179684
has comment: http://stackoverflow.com/comment/88181007

http://stackoverflow.com/q/50569710
has title: Command "python setup.py egg_info" failed with error code ,pip install
type: UnansweredQuestion
tagged with: pip
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/88149655
type: Question
has comment: http://stackoverflow.com/comment/88149674
has body: I failed to install my requirements pip install -r requirements.txt Collecting Flask==0.10.1 (from -r requirements.txt (line 1)) Using cached https://files.pythonhosted.org/packages/db/9c/149ba60c47d107f85fe52564133348458f093dd5e6b57a5b60ab9ac517bb/Flask-0.10.1.tar.gz Collecting flask-sqlalchemy==1.0 (from -r requirements.txt (line 2)) Using cached https://files.pythonhosted.org/packages/d7/bc/c02a52b382519c1bbfaf872e311489be40a0d7212eb151c3470b44e6d6c4/Flask-SQLAlchemy-1.0.tar.gz Collecting flask-migrate==1.2.0 (from -r requirements.txt (line 3)) Using cached https://files.pythonhosted.org/packages/3e/f6/3b96aa6beec503e8912df2f4c1c978603b234f673ba231026783adb2a96e/Flask-Migrate-1.2.0.tar.gz Collecting psycopg2==2.5.4 (from -r requirements.txt (line 4)) Using cached https://files.pythonhosted.org/packages/63/c3/802668cb3cfc2880c2a8364623e7105a0257724a2612bb66ec733aaddb8c/psycopg2-2.5.4.tar.gz Complete output from command python setup.py egg_info: running egg_info creating pip-egg-info/psycopg2.egg-info writing pip-egg-info/psycopg2.egg-info/PKG-INFO writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt' Error: b'You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application.\n' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-s4tk6lod/psycopg2/ I can install python-psycopg2 with apt-get python-psycopg2 ,but latter I have import problems ./manage.py db upgrade from flask.ext.sqlalchemy import SQLAlchemy ModuleNotFoundError: No module named 'flask' I am using venv as virtual env. Why did my pip install failed?
score: 0

http://stackoverflow.com/a/50547446
type: Answer
score: 0
has body: In this case you don't seem to want to deal with a class object, but just want to get the output. This you can do like so: class bread: def __init__(self, grain, cost, number): self.grain = (grain) self.cost = int(cost) self.number = int(number) return self.price() def price(self): p = self.cost * self.number print("%s : %d" % (self.grain, p)) bread("wholemeal", 2, 12) As a beginner you should not worry too much about things like property but keep it as simple (and verbose) as possible. Also because you're making the input for the grain type, I'm guessing you want to print that out together with the value. To unpack the changes I made to your code as an example for some basic coding practices: note the spacing between functions note the spacing between individual items note how the output is produced with print() Once all this is done, all we have to do is make the call we would otherwise have to make ourselves everytime, inside __init__. Good luck, and have fun learning python!
answers question: http://stackoverflow.com/q/50547298

http://stackoverflow.com/a/50573129
has body: Each time you call the function it returns a generator object. And each time you call the next on it you'll get the first item which is 0 * 0 because you're not calling the next on same object (each time a new one). But in second case you're looping over one generator object and it will continue to consuming the generator until it hit the StopIteration. For a better demonstration you can create two iterator objects from your generator function and loop over them simultaneously: In [17]: g = gen() In [18]: k = gen() In [19]: for i, j in zip(g, k): ...: print(i, j) ...: 0 0 1 1 4 4
upvote count: 6
type: Answer
answers question: http://stackoverflow.com/q/50573100
downvote count: 0
score: 6

http://stackoverflow.com/comment/88238503
comment on: http://stackoverflow.com/q/50613383
type: Comment
type: QuestionComment
has text: Meanwhile, even for a single line, there are two problems with your code: (1) you need to call `ljust` on the string you get back from formatting in the value, not from the format string, and (2) you need to call `ljust` on both halves of the line, not just the first half, or you end up with the same problem you started with.
score: 0

http://stackoverflow.com/q/50611273
upvote count: 1
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/88232887
tagged with: pandas
answer count: 1
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50611467
has body: I have a huge data file which looks like this. I have shown only a few parameters in the column 'Name'. I have 24 of them which keep repeating. Name Value Date Time 0 FAN_RFB 1 2018-04-07 02:34:43 1 KW_TOTAL 186 2018-04-08 23:59:58 2 ME_POW_1 8618 2018-04-08 23:59:56 3 ME_POW_2 8315 2018-04-08 23:59:56 4 FAN_RFB 1 2018-04-07 02:34:43 5 KW_TOTAL 185 2018-04-09 00:00:07 6 ME_POW_1 8467 2018-04-09 00:00:09 7 ME_POW_2 8350 2018-04-09 00:00:09 8 FAN_RFB 1 2018-04-07 02:34:43 9 KW_TOTAL 182 2018-04-09 00:00:15 10 ME_POW_1 8783 2018-04-09 00:00:16 11 ME_POW_2 8422 2018-04-09 00:00:16 12 FAN_RFB 1 2018-04-07 02:34:43 13 KW_TOTAL 184 2018-04-09 00:00:26 14 ME_POW_1 8545 2018-04-09 00:00:28 15 ME_POW_2 8370 2018-04-09 00:00:28 There are two things I want to do with this: The right date and time for each set is the one recorded for ME_POW_1. So for the index 0 to 3 I want to correct the date and time of all with the data and time for ME_POW_1 and I want to do it for all of the data. The names in the Column 'Name' should be pivoted to individual columns. The desired output is: Date Time FAN_RFB KW_TOTAL ME_POW_1 ME_POW_2 2018-04-08 23:59:56 1 186 8618 8315 2018-04-09 00:00:09 1 185 8467 8350 2018-04-09 00:00:16 1 182 8783 8422 2018-04-09 00:00:28 1 184 8545 8370 I think the second may be possible by using pd.pivot (index='date', columns='Name', values='Values'). Once I can get the dates of sets similar then I can use this piece of code to get the desired output: raw=pd.read_csv('example.csv', parse_dates=True, usecols=[0,1,2,3]) raw['Date']=pd.to_datetime(raw['Date']+''+raw['Time']) raw=raw.drop(['Time'], axis=1) raw1=raw.pivot(index='Date', columns='Name', values='Value') But I have no idea of how to accomplish the first task to change the date of each set as per the date and time of ME_POW_1. Could anyone please guide me?
type: UnansweredQuestion
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/88244974
has title: Read csv file with columns names as rows and edit date time

http://stackoverflow.com/comment/88308896
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50625363
score: 2
has text: The problem was with rules. The rule ATTRS{idVendor}=="0683", MODE="0666" works.

http://stackoverflow.com/comment/88342357
comment on: http://stackoverflow.com/q/50665866
type: Comment
has text: Could I ask you to remove all that stuff about a matrix and rows and columns from the question and reduce the question to just *"How can I remove elements from this dict without creating gaps"*? There's *a lot* of unnecessary information here that makes the question needlessly difficult to understand.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88316514
comment on: http://stackoverflow.com/q/50652847
score: 0
type: Comment
type: QuestionComment
has text: If this is for something like an in-place quicksort, there are lots of existing solutions.

http://stackoverflow.com/q/50616978
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88243745
has title: Python - pick a value from a list basing on another list
type: UnansweredQuestion
tagged with: python
has body: I've got a dataframe. In column A there is a list of integers, in column B - an integer. I want to pick n-th value of the column A list, where n is a number from column B. So if in columns A there is [1,5,6,3,4] and in column B: 2, I want to get '6'. I tried this: result = [y[x] for y in df['A'] for x in df['B'] But it doesn't work. Please help.
has answer: http://stackoverflow.com/a/50617082
score: 2
has answer: http://stackoverflow.com/a/50617325
upvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/88243858

http://stackoverflow.com/comment/88326711
has text: That works, but I would like a pure python solution, as I need to do this without starting up excel.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50657977

http://stackoverflow.com/a/50587342
type: Answer
accepted answer of: http://stackoverflow.com/q/50582130
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88184236
answers question: http://stackoverflow.com/q/50582130
has body: However, is there a way to refer to the path, only using only wbk No. The Workbook object only sees, and stores, the filename that is passed to it by the user. So if the user doesn't pass the path then the object can't store it. I'd suggest using os.getcwd() like in your example.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88188958
downvote count: 0

class-variables
tag name: class-variables
type: Tag
tags question: http://stackoverflow.com/q/50639137

http://stackoverflow.com/comment/88357131
type: Comment
type: QuestionComment
has text: These are two different things. Access is denied is that you dont have administrative privileges to modify that directory. The other one about the pip is just a warning about older version. It doesnt solve the access denied error.
comment on: http://stackoverflow.com/q/50673632
score: 0

http://stackoverflow.com/a/50596414
has comment: http://stackoverflow.com/comment/88202428
has comment: http://stackoverflow.com/comment/88202513
answers question: http://stackoverflow.com/q/50596383
has comment: http://stackoverflow.com/comment/88202116
has body: stack-based Split your To column, stack everything and then do a value_counts: v = pd.concat([df.From, df.To.str.split(', ', expand=True)], axis=1).stack() v[v.isin(lst)].value_counts() stranger2@gmail.com 2 person1@gmail.com 2 person3@gmail.com 1 dtype: int64 melt Another option is to use melt: v = (df.set_index('From') .To.str.split(', ', expand=True) .reset_index() .melt()['value'] ) v[v.isin(lst)].value_counts() stranger2@gmail.com 2 person1@gmail.com 2 person3@gmail.com 1 Name: value, dtype: int64 Note that set_index + str.split + reset_index is synonymous to pd.concat([...])...
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50596383
has comment: http://stackoverflow.com/comment/88202443
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88202475

http://stackoverflow.com/q/50697388
answer count: 3
has comment: http://stackoverflow.com/comment/88404068
has body: This is my input string: C:\Company\ProjectList\ProjectName\Requriment\..etc I would like expected output string: ProjectName I want to print only project name from the string. Is this possible in Python?
tagged with: string
has comment: http://stackoverflow.com/comment/88403837
favorite count: 0
has title: How to print only specific name from the string in Python
tagged with: python
possible better answer: http://stackoverflow.com/a/50697473
has answer: http://stackoverflow.com/a/50697476
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50697476
upvote count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/50697473
type: Question
has answer: http://stackoverflow.com/a/50697510
score: 0

http://stackoverflow.com/a/50625194
score: 2
accepted answer of: http://stackoverflow.com/q/50597847
answers question: http://stackoverflow.com/q/50597847
has comment: http://stackoverflow.com/comment/88327292
upvote count: 2
has comment: http://stackoverflow.com/comment/88318820
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88288882
has comment: http://stackoverflow.com/comment/88296329
type: Answer
downvote count: 0
has body: you may be able to do some fancy footwork with a distance transform, but not sure how I would do that atm, so just gonna state it and leave it as I said I would give a numerical methodology Also, be careful saying "processing time is not critical" as everything gets relative when you are doing a numerical solve on a data set that big. IE small changes in your inner loop could change processing time from minutes to hours to days... Everything I am describing below is "off grid", what I mean by that is: you have a structured point cloud, but the spatial vector generation and propagation is in free space. So in order to, for instance, test a point for inside or outside along a given free space vector, you will look up the nearest voxel coordinate inside the structured cloud. Usually, the easiest way to do this is simply to scale things to "floor" to the nearest resolution unit. Although this is easier if you use integer resolution and can actually use floor, you can also just do it with division, rounding and re-multiplication along primary axes. First step would be to set up a function to generate an arbitrary cross section. To do this, you will take a vector (A), then generate a perpendicular vector (C) to this vector (A) (this can be done in a number of ways, but easiest is to just create another non-parallel vector (B) and cross that with the original to create a perpendicular vector (C). For vector (B) you could just use (0,0,1) or (0,1,0) *using the former unless the test vector is parallel to (0,0,1) in which case you use the latter. Now that you have the vector (A), and a vector (C) in its perpendicular plane, you need to test your data along that vector (C). Basically, test origin point and then move along the vector (C) by your smallest resolution unit and keep testing until you reach the edge of your dataset or if you reach the edge of your object depending if you have a concave hull or not. Then rotate your vector (C) about vector (A) and radially sample th…
has comment: http://stackoverflow.com/comment/88284297

http://stackoverflow.com/comment/88392018
has text: ah ok, thanks Ryan and Juanpa. I'll make sure to do that instead in the future.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50690876

http://stackoverflow.com/q/50595746
tagged with: import
type: Question
type: AnsweredQuestion
has title: NameError: name is not defined. Circular Importing
score: 0
has body: I am having difficulty with a circular import problem. I have 2 class files like so: --/service service_module.py settings.py service_module imports other various files used throughout the project and acts as a container for various functions throughout the project. I want to assert in my settings.py file that it is properly passed an instance of the service_module parent class. Removing the assert statement in settings.py fixes the issue and I am able to properly call methods in the service_module class. For code completion and error checking it makes my life easier to assert. I have always struggled with understanding python imports but is this the right direction to handle my particular case? service_module.py from PyQt5.QtCore import QObject from sqlalchemy import * from sqlalchemy.orm import scoped_session, Session, sessionmaker from service.logger import logger from sqlalchemy.orm.exc import NoResultFound from database.tables import * from database.load_db import load_db from service.settings import settings from service.web_listener import web_listener from service.character_manager import character_manager class Service_Module(QObject): def __init__(self): super(Service_Module, self).__init__() load_database = load_db() self.sc_session: scoped_session = load_database.get_scoped_session() tb_scopes.make_default_scopes(service_module=self) self.logger = logger(service_module=self) self.settings = settings(service_module=self) self.characters = character_manager(service_module=self) self.callback_listener: web_listener = web_listener(service_module=self) self.callback_listener.start() assert isinstance(self.sc_session, scoped_session) assert isinstance(self.logger, logger) assert isinstance(self.settings, settings) assert isinstance(self.callback_listener, web_listener) settings.py from service.service_module import * class settings(QObject): def __init__(self, service_module): super(settings, self).__init__() self.service = service_module assert isinstance(sel…
answer count: 1
has comment: http://stackoverflow.com/comment/129649836
tagged with: python
has answer: http://stackoverflow.com/a/50595843
accepted answer: http://stackoverflow.com/a/50595843

http://stackoverflow.com/a/50631956
has comment: http://stackoverflow.com/comment/88275101
has comment: http://stackoverflow.com/comment/88274781
has comment: http://stackoverflow.com/comment/88274558
has comment: http://stackoverflow.com/comment/88275546
type: Answer
has comment: http://stackoverflow.com/comment/88275484
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88275393
has comment: http://stackoverflow.com/comment/88274922
has comment: http://stackoverflow.com/comment/88275559
accepted answer of: http://stackoverflow.com/q/50631849
has comment: http://stackoverflow.com/comment/88275416
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88275317
answers question: http://stackoverflow.com/q/50631849
has body: You do not need to iterate over the list of tuples. Use .merge() instead. Assuming you have one entry in rankings for each entry in dfYou need: ranking_df = pd.DataFrame(rankings, columns=['team', 'ranking', 'year']) new_df = df.drop(['ranking'], axis=1).merge(ranking_df, on=['team', 'year'], how='left') Input: year team tr_diff ranking 0 2010 ADO Den Haag 3.947368 NaN 1 2011 ADO Den Haag 1.512027 NaN 2 2012 ADO Den Haag -1.232033 NaN 3 2013 ADO Den Haag -3.757829 NaN Output: year team tr_diff ranking 0 2010 ADO Den Haag 3.947368 12.0 1 2011 ADO Den Haag 1.512027 16.0 2 2012 ADO Den Haag -1.232033 NaN 3 2013 ADO Den Haag -3.757829 NaN

http://stackoverflow.com/q/50641788
has comment: http://stackoverflow.com/comment/88293765
has body: Trying to compare two dictionaries with this code: def dict_compare(d1, d2): d1_keys = set(d1.keys()) d2_keys = set(d2.keys()) intersect_keys = d1_keys.intersection(d2_keys) added = d1_keys - d2_keys removed = d2_keys - d1_keys modified = {o: (d1[o], d2[o]) for o in intersect_keys if d1[o] != d2[o]} same = set(o for o in intersect_keys if d1[o] == d2[o]) return added, removed, modified, same one = {"1iG5NDGVre": {"118": ["test1", "test2", "test3", "tcp", "22", "Red", "0.0.0.0/0"]}} two = {"1iG5NDGVre": {"118": ["test1", "test2", "test3", "tcp", "22", "Red", "Blue", "0.0.0.0/0"]}} added, removed, modified, same = dict_compare(one,two) print added print removed print modified print same However, it prints the modified key/values wrongly. Output: set([]) set([]) {'1iG5NDGVre': ({'118': ['test1', 'test2', 'test3', 'tcp', '22', 'Red', '0.0.0.0/0']}, {'118': ['test1', 'test2', 'test3', 'tcp', '22', 'Red', 'Blue', '0.0.0.0/0']})} set([]) Any ideas how to correct it? I just want that it prints "Blue" in modified. Update 1: Works but not when the dicts have different keys number i.e one = {"1iG5NDGVre": {"118": ["test1", "test2", "test3", "tcp", "22", "Red", "0.0.0.0/0"]}} two = {"1iG5NDGVre": {"118": ["test1", "test2", "test3", "tcp", "22", "Red", "Blue", "0.0.0.0/0"]},"119": ["test10","test11"]} Will not show up test10 and test11 as added. Dict could also have less keys, key can be also removed. Want to also cover that case. Big thanks!
has title: Python 2.7 - Show only modified dictionary key/value while comparing dictionaries
has comment: http://stackoverflow.com/comment/88294474
has comment: http://stackoverflow.com/comment/88293631
has comment: http://stackoverflow.com/comment/88293962
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88294320
has comment: http://stackoverflow.com/comment/88293572
has comment: http://stackoverflow.com/comment/88293761
favorite count: 0
has answer: http://stackoverflow.com/a/50642176
linked to: http://stackoverflow.com/q/50641447
type: Question
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/88294216
score: 0
upvote count: 1
linked to: http://stackoverflow.com/q/50643953
accepted answer: http://stackoverflow.com/a/50642176
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/88641293
type: AnswerComment
score: 0
type: Comment
has text: I doubt your data has that level of precision (presumably micrometers, or greater, as you are suggesting). Rather, CloudCompare likely offset your data when you imported it. If you are using the point picker, then it reports the coordinates in both offset and global space. Try running again with the actual coordinates.
comment on: http://stackoverflow.com/a/50700051

http://stackoverflow.com/comment/90495570
score: 0
type: AnswerComment
type: Comment
has text: @nehaj Hey! Sorry what (+) signs are you referring to? I think you should open a new question with some data! :)
comment on: http://stackoverflow.com/a/50642800

http://stackoverflow.com/comment/88362147
type: QuestionComment
has text: Yes. Of course. I'd defined it.
score: 0
comment on: http://stackoverflow.com/q/50648521
type: Comment

http://stackoverflow.com/q/50550887
answer count: 2
upvote count: 1
accepted answer: http://stackoverflow.com/a/50551071
has title: Does creating a tuple of a set in python always result in the same tuple
favorite count: 0
tagged with: tuples
has comment: http://stackoverflow.com/comment/88112825
has answer: http://stackoverflow.com/a/50551071
tagged with: python
has comment: http://stackoverflow.com/comment/88113105
has comment: http://stackoverflow.com/comment/88112862
has answer: http://stackoverflow.com/a/50551163
has comment: http://stackoverflow.com/comment/88117208
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88112746
has comment: http://stackoverflow.com/comment/88112838
downvote count: 0
score: 1
possible better answer: http://stackoverflow.com/a/50551163
tagged with: set
has body: In my code, i convert a set to a tuple in order to use it as a dictionary key. Since a set does not have an order and a tuple is, it would seem that: tuple(some_set) does not guarantee the same tuple every time, since an order has to be created. However, by testing this in practice it seems that a given set is converted to the same tuple each time, as demonstrated by the following code printing 1. my_tuples = set() for i in range(100000000): my_tuples.add(tuple(set(range(100)))) print(len(my_tuples)) I could not find any documentation about this, but does the tuple() function always return the same tuple on a given set? And is this somewhere explicitly stated?
type: Question

http://stackoverflow.com/comment/88235783
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50612682
score: 1
has text: Seems like you're trying to access a column that doesn't exist

group-by
tags question: http://stackoverflow.com/q/50594852
tags question: http://stackoverflow.com/q/50552448
tags question: http://stackoverflow.com/q/50584887
tags question: http://stackoverflow.com/q/50580408
tags question: http://stackoverflow.com/q/50692842
tags question: http://stackoverflow.com/q/50629943
tags question: http://stackoverflow.com/q/50551039
tags question: http://stackoverflow.com/q/50542981
tag name: group-by
tags question: http://stackoverflow.com/q/50692000
tags question: http://stackoverflow.com/q/50662469
tags question: http://stackoverflow.com/q/50637603
type: Tag
tags question: http://stackoverflow.com/q/50598984
tags question: http://stackoverflow.com/q/50596307
tags question: http://stackoverflow.com/q/50594049
tags question: http://stackoverflow.com/q/50558458
tags question: http://stackoverflow.com/q/50679272
tags question: http://stackoverflow.com/q/50592401

http://stackoverflow.com/q/50680355
has comment: http://stackoverflow.com/comment/88397030
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
downvote count: 1
has answer: http://stackoverflow.com/a/50682383
has comment: http://stackoverflow.com/comment/88374353
type: Question
tagged with: random
answer count: 1
has comment: http://stackoverflow.com/comment/88392887
score: 1
favorite count: 0
tagged with: series
has title: looping through dataframe and generating random dataframe
tagged with: pandas
has body: I have a lookup dataframe as follows: String Length 0 A 2 1 B 4 2 C 3 3 D 2 I have an input dataframe as follows: Input 0 A20 1 B1611 2 C001 3 D18 I want to get an output like: Output 0 C300 1 B2718 2 C421 3 A17 Where B2718 is B concatenated with a random value 2718 which is a 4 digit int, and the length 4 is obtained from "Length" column of lookup. I have written the following code: def random_with_N_digits(n): range_start = 10**(n-1) range_end = (10**n)-1 return randint(range_start, range_end) def r_funct(lookup): r_list = [] for index, row in lookup.iterrows(): r_int= random_with_N_digits(row.Length) r_str=row.String+str(r_int) r_list.append(r_str) return r_list out_df = r_funct(lookup) out_df = pd.DataFrame(out_df, columns=['Output']) out_df = out_df.sample(n=in_df.size) print(out_df) But I'm unable to get the same output dataframe (out_df) on every run. Please suggest.
tagged with: python

http://stackoverflow.com/q/50553042
tagged with: virtualenv
favorite count: 0
duplicate of: http://stackoverflow.com/q/45944241
tagged with: python
accepted answer: http://stackoverflow.com/a/50553063
type: AnsweredQuestion
has title: make virtualenv use python3
score: 1
upvote count: 1
type: Question
has body: I have a virtualenv called "my_repo", when I workon this virtualenv, I get this error: The path python3 (from --python=python3) does not exist How can I make this env use python3? Im on windows.
has answer: http://stackoverflow.com/a/50553063
linked to: http://stackoverflow.com/q/45944241
answer count: 1
downvote count: 0

http://stackoverflow.com/q/50561455
has comment: http://stackoverflow.com/comment/88135044
score: 0
tagged with: concurrency
has body: I am trying to use parallel processing on my list , which have this format : [ (key , { three values } )] I want to group those keys which have any similar values : example : [ (1 , { 22,31,21 } ) , (2, {19,98,11}) , (3, {1,22,4})] Expected output : (1,3) because { 22,31,21 }.intersection({1,22,4} ) have 22 Now I am benchmarking it with nested loop vs parallel processing : from multiprocessing import Pool from tqdm import tqdm by parallel processing : def check_values(value): result=[] for j in fake_data: if len(value[1].intersection(j[1]))!=0: if j[0]!=value[0]: result.append((value[0],j[0])) return result if __name__ == "__main__": agents= 5 chunksize=1 with Pool(processes=agents) as pool: result=pool.map(check_values,fake_data,chunksize) datar=[tuple(sorted(j)) for i in result for j in i] print(len(sorted(set(datar)))) By nested loop {serial processing } : def without_pool(): datar=[] for ivalue in tqdm(fake_data): for jvalue in fake_data: if len(ivalue[1].intersection(jvalue[1]))!=0: if ivalue[0]!=jvalue[0]: datar.append((ivalue[0],jvalue[0])) return datar sorted_result=[tuple(sorted(i)) for i in without_pool()] print(len(sorted(set(sorted_result)))) I am expecting faster execution in parallel method but i am getting slower speed in parallel and fast speed in serial method , Am i doing wrong somewhere please suggest: Here is notebook file which have data and all the code , You can run it :
tagged with: multiprocessing
duplicate of: http://stackoverflow.com/q/45256953
answer count: 0
has comment: http://stackoverflow.com/comment/88134751
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88134941
has comment: http://stackoverflow.com/comment/88134876
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/88133420
linked to: http://stackoverflow.com/q/45256953
has title: Parallel Processing Python : Why parallel processing is slower than serial processing?
has comment: http://stackoverflow.com/comment/88135731
has comment: http://stackoverflow.com/comment/88134816
tagged with: python
tagged with: parallel-processing

http://stackoverflow.com/q/50574693
score: -3
type: Question
downvote count: 3
has body: So I got this MIT Scraper program to get it working. Somebody worked on it before and has been told that it's functioning and the coding is correct. I just have to fix some config issue and should be written. First of all here is the link to the full program: https://github.com/ByteAcademyCo/mit_scraper {take a look at the ocw_upload and those main three files config.py, mit_ocw_scraper.py and read_imsmanifest.py If you can take a look at it and explain what everything does that would more than amazing, cause I don't count myself as an expert at python yet. To generate schemas for courses... Download and unzip a course's content from the ocw site and add its path to COURSE_FOLDERS in the config file located in the ocw_upload folder. By running read_imsmanifest.py, every imsmanifest file included in the course's content folder will be parsed and important information, including the sections into which the course is organized, paths to the course's resources (but not the actual data for those resources), and other specifications of the course, will be written to a json file as specified in build_schema.py. The exact schema used to organize each course's content can be found in schema_dict.py I have done all those stuff and got a little idea on how things work so in my opinion, I feel that something is either wrong with this part of the code import xml.etree.ElementTree as ElementTree import xmltodict import os import config from build_schema import SchemaBuilder class Director: def __init__(self, builder, config, course_folder): self.full_path = os.path.join(config.COURSES_DIR, course_folder) self.file_full_path = os.path.join(self.full_path, config.IMS_MANIFEST) self._builder = builder self.imsmanifest_reader = IMSManifestReader(self._builder, self.file_full_path) def construct(self): """ Instruct reader to process input and pass specified data to the builder for the product to be constructed. """ self.imsmanifest_reader.process() class IMSManifestReader: XMLNAMESPAC…
tagged with: scraper
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50634243
has comment: http://stackoverflow.com/comment/88158809
tagged with: python
has comment: http://stackoverflow.com/comment/88202356
favorite count: 0
has title: Python MIT Course OCW Web Page SCraper
type: UnansweredQuestion

http://stackoverflow.com/comment/88283433
has text: @MatiasValdenegro I am not sure it is a BIGGER problem, it is a different (and, I agree, fatal, for this little experiment) problem, but the point of my post was that this behavior makes no semantic sense to me: it seems akin to a text editor plugging completely random objects into functions I am writing - figuring out what is going on might make future projects less painful.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50634986
score: 0

http://stackoverflow.com/a/50619258
upvote count: 1
has body: I think need glob for all file names and then in list comprehension create DataFrame: from functools import reduce import glob files = glob.glob('files/*.csv') dfs = [pd.read_csv(fp) for fp in files] Last merge together: df = reduce(lambda left,right: pd.merge(left,right,on='ID'), dfs) For outer join is possible use concat: import glob files = glob.glob('files/*.csv') dfs = [pd.read_csv(fp, index_col=['ID']) for fp in files] df = pd.concat(dfs, axis=1)
answers question: http://stackoverflow.com/q/50618621
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50618621
score: 1

http://stackoverflow.com/q/50664449
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88339257
has title: How best to Implement Linked Variables?
has comment: http://stackoverflow.com/comment/88342094
has body: I am implementing a geometry solver program, which will try to solve for all the other measurements in the figure with the data that is given (see image link) In such a figure, the lengths or measurements of the shapes are implicitly linked. For example, if one knows the length of rectangle A, one knows the length of rectangle B, because the figure description says rectangle A and B are identical. And if one knows the diamater of semicircle C , one also knows the width of rectangle A and B.Finally, the diameter of semicircle C is related to its area by Area = pi* (D/2)^2 Hence, I would like to implement a algorithm such that, the moment one of the linked variables (e.g area,length, diamater, radius) is changed, the remaining linked variables also change appropriately. What in your opinion is the best way to implement this? Could I use, for example, recursion to update through all linked variables, or getter and setter properties, for example? I use python as my preferred language. Thanks.
answer count: 1
downvote count: 0
favorite count: 0
tagged with: geometry
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50952092
score: 1

http://stackoverflow.com/comment/88346006
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50657352
type: Comment
has text: sorry, try with `self.cursor = self.textEdit.textCursor()`

http://stackoverflow.com/comment/88322942
type: Comment
has text: You can also check the library [here](https://bashtage.github.io/linearmodels/panel/models.html#linearmodels.panel.model.FamaMacBeth)
type: QuestionComment
comment on: http://stackoverflow.com/q/50656274
score: 0

http://stackoverflow.com/q/50691375
has title: Is Scipy's distance.cdist function only single thread or is it possible to make it multithread?
has comment: http://stackoverflow.com/comment/88406088
answer count: 0
has body: Is Scipy's distance.cdist function only single thread or is it possible to make it multithread? I have tested it on my computer with very large matrices on both sides ((1000000,100) and (10, 100)) and only one of the CPU is used. My setting as follows, which shows that I have BLAS installed: &gt;&gt;&gt; import scipy &gt;&gt;&gt; scipy.__config__.show() openblas_info: library_dirs = ['/usr/local/lib'] language = f77 libraries = ['openblas'] openblas_lapack_info: library_dirs = ['/usr/local/lib'] language = f77 libraries = ['openblas'] blas_opt_info: library_dirs = ['/usr/local/lib'] language = f77 libraries = ['openblas'] lapack_opt_info: library_dirs = ['/usr/local/lib'] language = f77 libraries = ['openblas'] blas_mkl_info: NOT AVAILABLE
type: UnansweredQuestion
tagged with: multithreading
tagged with: python
score: 3
upvote count: 3
tagged with: scipy
type: Question
tagged with: numpy
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/50604349
has comment: http://stackoverflow.com/comment/88218153
has comment: http://stackoverflow.com/comment/88218573
type: Question
answer count: 2
has title: Plottng a graph for multiple attributes + matplotlib
has comment: http://stackoverflow.com/comment/88218395
has comment: http://stackoverflow.com/comment/88218629
has comment: http://stackoverflow.com/comment/88218480
accepted answer: http://stackoverflow.com/a/50606261
has comment: http://stackoverflow.com/comment/88218603
has comment: http://stackoverflow.com/comment/88218024
score: 0
has answer: http://stackoverflow.com/a/50608183
favorite count: 0
has comment: http://stackoverflow.com/comment/88217950
upvote count: 2
possible better answer: http://stackoverflow.com/a/50608183
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/88218875
has answer: http://stackoverflow.com/a/50606261
has comment: http://stackoverflow.com/comment/88218249
type: AnsweredQuestion
tagged with: matplotlib
has body: I have data in following fashion: efficiency = [{'weights': '25', 'sets': '5', 'time': '8.48', 'machine': 'a'}, {'weights': '100', 'sets': '25', 'time': '7.43', 'machine': 'a'}, {'weights': '25', 'sets': '5', 'time': '8.70', 'machine': 'b'}, {'weights': '100', 'sets': '25', 'time': '7.73', 'machine': 'b'}, {'weights': '25', 'sets': '5', 'time': '7.14', 'machine': 'c'}, {'weights': '100', 'sets': '25', 'time': '8.38', 'machine': 'c'}, {'weights': '25', 'sets': '5', 'time': '6.11', 'machine': 'd'}...] It denotes time required in minutes for a machine to achieve the task with given weights and sets. I am new to matplotlib so not getting how to plot a graph along the X and Y axis as shown in this plot . Its not necessary that graph should be similar to this graph. Please suggest any graph which should represent the time required for a machine, Basically, I want to denote time required for a machine for the given weights and sets. I am not getting how to represent the features(time, machine, weights and sets)

http://stackoverflow.com/q/50612866
tagged with: python
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88236690
type: Question
has comment: http://stackoverflow.com/comment/88236004
tagged with: flask
has title: Using subprocess to run a command via Flask throws KeyError: 'PWD'
has answer: http://stackoverflow.com/a/50626612
has comment: http://stackoverflow.com/comment/88236534
upvote count: 1
answer count: 1
favorite count: 0
has body: I am attempting to use Flask to run a command using subprocess. At a high level what I am trying to do is create a way that a user can hit a URL and pass in a 'test_name' [for PoC I am using smoke]. That test name then gets passed along to flask_test_runner(). In flask_test_runner I am attempting to run the following pytest command pytest -m test_name -html=report.html --self-contained-html using subprocess command = subprocess.Popen(["pytest", "-m", test_name, "-html=report.html", "--self-contained-html"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) All of this is running inside a docker container. I have done my best to validate that docker is not the root cause. At one point I included a RUN pytest at the end of the dockerfile and it kicked off the tests. My server starts up as expected: * Serving Flask app "webserver" (lazy loading) * Environment: development * Debug mode: on * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 282-250-075 When I hit the URL http://localhost:5000/apitesting/smoke I get the following back in the Response: Content-Type: text/html; charset=utf-8 Content-Length: 0 Server: Werkzeug/0.14.1 Python/3.6.4 Date: Wed, 30 May 2018 20:20:39 GMT and this error in my console: File "/usr/local/lib/python3.6/site-packages/pytest_cloud/plugin.py", line 77, in pytest_addoption os.path.basename(os.environ['PWD']) File "/usr/local/lib/python3.6/os.py", line 669, in __getitem__ raise KeyError(key) from None KeyError: 'PWD' I do not understand why this is happening, so any help is appreciated. Thank you for your time. For reference my app route is as follows: @app.route('/apitesting/&lt;test_name&gt;', methods=['GET', 'POST']) def runsmoketests(test_name): ''' :param test_name: test type passed in by the user ''' flask_app_cmd = api_flask_test_runner.flask_test_runner(test_name) print(flask_app_cmd[0]) print(flask_app_cmd[1]) return flask_app_cmd The flask_test_runner that I call is:…
type: UnansweredQuestion

http://stackoverflow.com/comment/88336081
type: Comment
comment on: http://stackoverflow.com/q/50662745
score: 0
has text: good to have more wisdom to be added. go ahead
type: QuestionComment

http://stackoverflow.com/a/54443282
has comment: http://stackoverflow.com/comment/96845557
upvote count: 6
has comment: http://stackoverflow.com/comment/103206245
type: Answer
has comment: http://stackoverflow.com/comment/103457669
score: 6
has body: I have used Google Vision API - DOCUMENT_TEXT_DETECTION for getting the line by line data. The data which is returned has the following structure: The structure might change for different APIs. { 'description': 'Some Text', 'coordinates': [ P1, P2, P3, P4] } The approach I used was calculating the mid-point of all the words. { 'description': 'Some Text', 'center': { x: (P1.x + P2.x + P3.x + P4.x)/4, y: (P1.y + P2.y + P3.y + P4.y)/4 } } Now I sorted these words on the basis of their center coordinates. In both X and Y axis. But for sorting in Y-Coordinates you will need some Y-Tolerance Variable. For example, word_1.center.y = 15 word_2.center.y = 18 word_3.center.y = 28 Now, you have to decide how much difference in Y-Coordinate value is needed to change lines (which depends upon the font-size used in the document). (word_2.center.y - word_1.center.y) &lt; Y-Tolerance # True ~ In same line (word_3.center.y - word_2.center.y) &lt; Y-Tolerance # False ~ In different line After you get the list of words in the same line. Sort them according to their X-Coordinates. Please reach out in case of any other query.
answers question: http://stackoverflow.com/q/50673749
downvote count: 0

ejbca
type: Tag
tag name: ejbca
tags question: http://stackoverflow.com/q/50692814

django-views
tags question: http://stackoverflow.com/q/50665192
tags question: http://stackoverflow.com/q/50660335
tags question: http://stackoverflow.com/q/50643767
tags question: http://stackoverflow.com/q/50623606
tags question: http://stackoverflow.com/q/50602670
tags question: http://stackoverflow.com/q/50659173
tags question: http://stackoverflow.com/q/50645519
tag name: django-views
tags question: http://stackoverflow.com/q/50621829
type: Tag
tags question: http://stackoverflow.com/q/50584249
tags question: http://stackoverflow.com/q/50678057
tags question: http://stackoverflow.com/q/50664672
tags question: http://stackoverflow.com/q/50582519
tags question: http://stackoverflow.com/q/50688071
tags question: http://stackoverflow.com/q/50659964
tags question: http://stackoverflow.com/q/50585110
tags question: http://stackoverflow.com/q/50649654
tags question: http://stackoverflow.com/q/50678954
tags question: http://stackoverflow.com/q/50555501
tags question: http://stackoverflow.com/q/50567585

http://stackoverflow.com/q/50674448
downvote count: 0
favorite count: 0
type: UnansweredQuestion
score: 6
has answer: http://stackoverflow.com/a/50969026
tagged with: python
upvote count: 6
tagged with: tensorflow
type: Question
has body: I've read the paper MobileNetV2(arXiv:1801.04381) and ran the model from Tensorflow model zoo. I noticed that the inference time of SSD Lite MobileNetV2 is faster than SSD MobileNetV2. At the MobileNetV2 paper, there is only a short explanation about SSD Lite in the following sentence: 'We replace all the regular convolutions with separable convolutions (depthwise followed by 1 × 1 projection) in SSD prediction layers'. So my question is, what is the difference between SSD and SSD Lite? I don't understand the difference because when the MobileNetV1(arXiv:1704.04861v1) was published and applied to SSD, it has already replaced all the convolutional layers to depthwise separable convolutions that were mentioned above.
has answer: http://stackoverflow.com/a/51167619
has title: What is the different between SSD and SSD Lite ??(Tensorflow)
answer count: 2

http://stackoverflow.com/a/50632361
upvote count: 3
has body: You're currently searching for the element by a hardcoded class name. If the class name is randomized, you cannot hardcode it any longer. You have to either: Search the element by some other characteristics (e.g. element hierarchy, some other attributes, etc; XPath can do that) In [10]: driver.find_elements_by_xpath('//article//img') Out[10]: [&lt;selenium.webdriver.firefox.webelement.FirefoxWebElement (session="1ab4eeb4-10c4-4da4-996c-ee6744445dcc", element="55c48964-8cd0-4472-b35b-214a5a9bfbf7")&gt;, &lt;selenium.webdriver.firefox.webelement.FirefoxWebElement (session="1ab4eeb4-10c4-4da4-996c-ee6744445dcc", element="b7f7c8a4-e343-49ca-b416-49f72e67ae07")&gt;, &lt;selenium.webdriver.firefox.webelement.FirefoxWebElement (session="1ab4eeb4-10c4-4da4-996c-ee6744445dcc", element="728f6148-6a03-4c9a-9933-36859d65eb51")&gt;] You can also search by the element's visual characteristics: size, visibility, position. This cannot be done solely by XPath though, you'll have to get all &lt;img&gt; tags and inspect each one with JS by hand. (See an example below because it's long.) Learn this class name somehow from other page logic (it must be present somewhere else if the page's logic itself can find and use it, and that logic must be found by something else, etc etc) In this case, the class name is a part of a local variable in the renderImage function, so it's only salvageable via DOM by exploring its AST. The function itself is buried somewhere inside webpack machinery (it seems to pack all resources into a few global objects with one-letter names). Alternatively, you can read all included JS files as raw data and look for the definition of renderImage in them. So, in this case, it's disproportionally hard, though theoretically possible still. Example of getting elements by visual characteristics On any page whatsoever, this would find 3 images of the same size, located side by side (this is the way they are at https://www.instagram.com/kitties). Since HTMLElements can't be …
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88276569
type: Answer
has comment: http://stackoverflow.com/comment/88315021
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50632242
has comment: http://stackoverflow.com/comment/88310667
answers question: http://stackoverflow.com/q/50632242

http://stackoverflow.com/comment/88294535
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50641849
has text: Yeah. I am using the db.commit. I already reviewed my code, my db connection is working but I can't insert successfully my data.
score: 0

http://stackoverflow.com/q/50578481
tagged with: pandas
downvote count: 1
has body: In a dataframe I want to compute an additional column "desired_output" (default of "desired column" is 123456) that combines the values from another 6 columns (c_flow 1,c_flow 2,c_flow 3,c_flow 4,c_flow 5,c_flow 6) as follows: if in a row in column 1=0.0 and column 4=0.0 then the "desired_output" becomes: x23x56. "try1" is what I can output at the moment. c_flow_1 = [1, 20, 0, 3, 0, 2] c_flow_2 = [10, 20, 5, 10, 0, 0] c_flow_3 = [10, 20, 0, 10, 1, 2] c_flow_4 = [0, 20, 0, 10, 1, 2] c_flow_5 = [10, 0, 1, 10, 1, 5] c_flow_6 = [10, 0, 0, 10, 1, 2] desired_output = ['123x56', '1234xx', 'x2xx5x', '123456','xx3456','1x3456'] data = pd.DataFrame({'c_flow 1': c_flow_1, 'c_flow 2': c_flow_2, 'c_flow 3': c_flow_3, 'c_flow 4': c_flow_4, 'c_flow 5': c_flow_5, 'c_flow 6': c_flow_6, 'desired_output': desired_output }) conditions = [data['c_flow 1'] == 0, data['c_flow 2'] == 0, data['c_flow 3'] == 0, data['c_flow 4'] == 0, data['c_flow 5'] == 0, data['c_flow 6'] == 0 ] choices = ['x23456', '1x3456', '12x456', '123x56', '1234x6', '12345x'] data['try1'] = np.select(conditions, choices, default ='123456')
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/50578834
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50578834
tagged with: conditional-statements
tagged with: dataframe
type: Question
accepted answer: http://stackoverflow.com/a/50578649
answer count: 2
upvote count: 1
has title: pandas: create column with string value based on conditions in other columns
has answer: http://stackoverflow.com/a/50578649
score: 0

http://stackoverflow.com/q/50555379
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88121547
upvote count: 2
has body: I have a (geo)dataframe with a column with location names and column with floats and I would like to merge them. Example with cities dataset in geopandas (with an extra column): Name geometry GDP Vatican City POINT(...) 20353.42 I want to merge them so I have: Vatican City: 20353.42 What I tried: cities['name-gdp'] = cities['name'].astype(str).str.cat(cities['GDP'], sep =': ') But I get the following error: TypeError: sequence item 1: expected str instance, float found
type: Question
tagged with: pandas
score: 2
tagged with: geopandas
answer count: 1
downvote count: 0
has title: Merge a column containing strings with a column containing floats
has answer: http://stackoverflow.com/a/50555396
favorite count: 0
accepted answer: http://stackoverflow.com/a/50555396

http://stackoverflow.com/q/50632220
linked to: http://stackoverflow.com/q/35316250
has comment: http://stackoverflow.com/comment/88278717
downvote count: 0
has body: I have the following code: def map_per_image(class_index_array): def index_to_label_f(index): index_to_label = {0:label_Vehicles, 1:label_Roads, 2:label_None} #print(index.eval()) label = index_to_label[index] return label translated = tf.map_fn(index_to_label_f, class_index_array) return translated Outside of Tensorflow environment, using ordinary map it would have worked. But the value of the argument class_index_array is a tensor, thus is its element, index also tensor. I need somehow to convert the tensor index to an int value, in order to look up the dictionary. I tried index.eval() but got an error: ValueError: Operation 'map_8/while/map/while/TensorArrayReadV3' has been marked as not fetchable. Without such conversion, I would get a different error due to using a tensor value to look up the dictionary: KeyError: &lt;tf.Tensor 'map_9/while/map/while/TensorArrayReadV3:0' shape=() dtype=int32&gt; I wonder what's the proper way to express my above implementation logic in Tensorflow execution (session) environment?
has comment: http://stackoverflow.com/comment/88275697
has title: What is the Tensorflow equivalent of looking up dictionary?
score: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
upvote count: 1
tagged with: tensorflow
type: Question

http://stackoverflow.com/q/50570299
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
has title: Python integer refusing to increment (+=) during debug
type: Question
tagged with: debugging
tagged with: visual-studio-code
has comment: http://stackoverflow.com/comment/88174823
has body: I am debugging a complicated Python program (VSCode Python debugger) and there is a very baffling behavior that I am noticing: &gt; type(self.i) &lt;class 'int'&gt; &gt; self.i 1 &gt; self.i+1 2 &gt; self.i += 1 None &gt; self.i 1 &gt; self.i = self.i + 1 None &gt; self.i 1 The variable self.i just refuses altogether to increment. I have highlighted a debugging session but even without any breakpoint, if the execution is inside a debug session, a loop that should take 5 iterations takes a random, longer, number of iterations. This behavior happens: only when some external code is modified in a specific way only when using the debugger. Just running the script via python makes the problem go away The context is that we are inside a __next__ method of an iterator, the snippet is def __next__(self): if self.i &lt; self.num_samples: i = self.i self.i += 1 # &lt;- here is a breakpoint .... The code that toggles the behavior is inside a for loop using an instance of said iterator. There should really be no relation between it and what happens inside the iterator, but when a computationally expensive line that involves pytorch backpropagation is decommented the problem happens. This is puzzling me because it is so mysterious. I can't understand why a variable should refuse to increment, whether there is a bug, and if so where it is (in the VSCode debugger, in my code, in Python, in PyTorch, ...?). So I would be very grateful if someone could shed a bit of light on the issue EDIT: The class where this happens is called SpectraDataLoader and is an iterator. The only references to i are in __iter__ and __next__ (shown before): def __iter__(self): ... self.i = 0 ... return self
has comment: http://stackoverflow.com/comment/88191379
downvote count: 0
has comment: http://stackoverflow.com/comment/88160726
has comment: http://stackoverflow.com/comment/88150478
favorite count: 0

http://stackoverflow.com/q/50618924
has body: After installing caffe from source, while running sample test projects I am facing above issue. What might be the cause of this error.
has title: KeyError: "Couldn't find enum caffe.EmitConstraint.EmitType"
has answer: http://stackoverflow.com/a/50619224
type: Question
tagged with: caffe
tagged with: deep-learning
upvote count: 1
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: computer-vision
tagged with: c++
score: 1

http://stackoverflow.com/comment/88309596
type: QuestionComment
comment on: http://stackoverflow.com/q/50649236
score: 0
has text: Hi, welcome to StackOverflow! Providing a could example of your code will make it much more likely for someone to be able to help you. If possible provide a [Minimal, Complete and Verifiable example](https://stackoverflow.com/help/mcve).
type: Comment

http://stackoverflow.com/comment/88404594
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50696442
has text: @san - yes, and it is problem. need numeric values.

http://stackoverflow.com/a/61631370
type: Answer
answers question: http://stackoverflow.com/q/50612215
has comment: http://stackoverflow.com/comment/117976255
upvote count: 5
downvote count: 0
has body: With tensorflow >= 2.1, it is possible to use the window(), flat_map() and batch() functions to get desired results. Example: ## Sample data list x_train = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90] ## Constants batch_size = 10 shift_window_size = 1 ## Create tensor slices train_d = tf.data.Dataset.from_tensor_slices(x_train) ## Create dataset of datasets with a specific window and shift size train_d = train_d.window(size=batch_size,shift=shift_window_size, drop_remainder=True) ## Define a function to create a flat dataset from the dataset of datasets def create_seqeunce_ds(chunk): return chunk.batch(batch_size, drop_remainder=True) ## Create a dataset using a map with mapping function defined above train_d = train_d.flat_map(create_seqeunce_ds) ## Check the contents for item in train_d: print(item) Output: tf.Tensor([ 1 2 3 4 5 6 7 8 9 10], shape=(10,), dtype=int32) tf.Tensor([ 2 3 4 5 6 7 8 9 10 20], shape=(10,), dtype=int32) tf.Tensor([ 3 4 5 6 7 8 9 10 20 30], shape=(10,), dtype=int32) tf.Tensor([ 4 5 6 7 8 9 10 20 30 40], shape=(10,), dtype=int32) tf.Tensor([ 5 6 7 8 9 10 20 30 40 50], shape=(10,), dtype=int32) tf.Tensor([ 6 7 8 9 10 20 30 40 50 60], shape=(10,), dtype=int32) tf.Tensor([ 7 8 9 10 20 30 40 50 60 70], shape=(10,), dtype=int32) tf.Tensor([ 8 9 10 20 30 40 50 60 70 80], shape=(10,), dtype=int32) tf.Tensor([ 9 10 20 30 40 50 60 70 80 90], shape=(10,), dtype=int32) More details can be found here: TF Data Guide
score: 5

http://stackoverflow.com/q/50558333
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88134454
tagged with: django
tagged with: python
has body: I programed my Django site, and when I upload in Amazon server, the site only works in mysite.com:8000. How can I change to work in normal mysite.com? It is a configuration in my code or in the server?
downvote count: 1
has comment: http://stackoverflow.com/comment/88127527
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/88127491
type: Question
upvote count: 0
has title: How can I change the port in production?
has answer: http://stackoverflow.com/a/50558439
tagged with: amazon-web-services
answer count: 1
favorite count: 0
score: -1
tagged with: python-3.x

http://stackoverflow.com/q/50553290
favorite count: 0
tagged with: while-loop
tagged with: break
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88117335
has body: so this is my code, creating a rock paper scissors game. i dont have anything else to say but the system here says i need more details because there is too much code so im randomly typing. thank you though. options=["rock","paper","scissors"] your_wins=0 my_wins=0 while input!="exit": turn = input("Please choose rock,paper or scissors:") print("you chose:" + turn) import random my_choice = random.choice(options) print("I chose:" + my_choice) if my_choice=="rock" and turn=="rock": print("its a tie!") if my_choice=="paper" and turn=="rock": print("you lose!") if my_choice=="scissors" and turn=="rock": print("you win!") if my_choice=="paper" and turn=="paper": print("its a tie!") if my_choice=="scissors" and turn=="paper": print("you lose!") if my_choice=="rock" and turn=="paper": print("you win!") if my_choice=="paper" and turn=="scissors": print("you win!") if my_choice=="scissors" and turn=="scissors": print("its a tie!") if my_choice=="rock" and turn=="scissors": print("you lose!") if "you lose": my_wins+=1 else: your_wins+=1 if input=="exit": break why do i get this error? Its on the break. I tried different things, but it just wont work.. thank you for the help!!
has answer: http://stackoverflow.com/a/50553350
has title: python - expected an indented block while loop
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/88117349
downvote count: 3
type: Question
upvote count: 0

http://stackoverflow.com/a/50708321
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50638682
accepted answer of: http://stackoverflow.com/q/50638682
type: Answer
has comment: http://stackoverflow.com/comment/88479519
score: 2
downvote count: 0
has body: You problem is here In [4]: mapping = dict(zip(np.arange(50000), np.random.random(size=50000))) In [5]: import pickle In [6]: %time len(pickle.dumps(mapping)) CPU times: user 2.24 s, sys: 18.6 ms, total: 2.26 s Wall time: 2.25 s Out[6]: 6268809 So mapping is big and unpartitioned - the scatter operation is the one giving you the problem in this case. Consider the alternative def make_mapping(): return dict(zip(np.arange(50000), np.random.random(size=50000))) mapping = client.submit(make_mapping) # ships the function, not the data # and requires no serialisation future = client.submit(ds.map, mapping) This will not show the warning. However, it seems strange to me to use a dictionary here to do the mapping, a series of straight array seems to encode the nature of the data better.

http://stackoverflow.com/comment/88209650
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50599850
has text: @Chris_Rands *tee basically does exhaust the entire iterator to create the new iterators* – this is totally not true.
score: 0

http://stackoverflow.com/q/50578978
score: 1
has body: I have done the following code. Timer is working properly in console. can any one please update my code so that it appears on my created Dialog screen. I am using PyQt5 in Python 3.6 in Windows. I want to create normal login-user button. When clicked on login initially I want to see timer is counting down like stopwatch. Thanks in advance! # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'login.ui' # # Created by: PyQt5 UI code generator 5.5.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtWidgets, QtCore, QtGui, Qt from PyQt5.QtCore import * from PyQt5.QtGui import * # from relogio import Ui_relogiocc class Ui_Dialog(QtWidgets.QMainWindow): def logincheck(self): print("loged") self.my_qtimer = QtCore.QTimer(self) print("timer created") self.my_qtimer.timeout.connect(self.timerTick) self.my_qtimer.start(1000) self.updateTimerDisplay() def timerTick(self): print("Control came") self.inicio -= 1 if self.inicio &lt;= 0: self.timer.stop() sys.exit(1) self.updateTimerDisplay() def updateTimerDisplay(self): print("control to timer") text = "%d:%02d" % (self.inicio / 60, self.inicio % 60) print("value is ", text) self.time_passed_qll.setText(str(text)) def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(564, 461) self.inicio = 180 # self.central_widget = QtWidgets.QWidget(Dialog) # self.setCentralWidget(self.central_widget) self.vbox = QtWidgets.QVBoxLayout() # self.central_widget.addLayout(self.vbox) self.time_passed_qll = QtWidgets.QLabel() # self.timerStatus = QtWidgets.QGroupBox('time Status') # self.timerStatusLayout = QtWidgets.QGridLayout() # self.timerStatus.setLayout(self.timerStatusLayout) # self.timerStatusLayout.addWidget(self.time_passed_qll, 0, 0) # self.vbox.addWidget(self.time_passed_qll) self.username_label = QtWidgets.QLabel(Dialog) self.username_label.setGeometry(QtCore.QRect(27, 60, 91, 16)) self.username_label.setObjectName("username_label") self.password_label = QtWidgets.QL…
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/88168484
upvote count: 1
has comment: http://stackoverflow.com/comment/88168714
type: Question
has answer: http://stackoverflow.com/a/50582449
has title: In PyQt5 on screen timer is not appearing
has comment: http://stackoverflow.com/comment/88168375
accepted answer: http://stackoverflow.com/a/50582449
has comment: http://stackoverflow.com/comment/88168541
has comment: http://stackoverflow.com/comment/88168207
tagged with: pyqt
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88168167
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88168427
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/88268207
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50622568
has text: Again, you might want to check out some of the pickle variants in `dill.settings` -- there are at least three variants that cover the range between "aggressive" (pickle everything, the default), to pickle only referenced items (e.g. `joblib` pickling), to pickle by reference (e.g. the way `pickle` does it).
score: 0

fen
tag name: fen
type: Tag
tags question: http://stackoverflow.com/q/50672945

http://stackoverflow.com/comment/88386125
has text: Thanks for the suggestion. I've made `word_obj` and `opt` into private variables that use placeholders to take inputs. I have another method that uses the same kind of logic that takes in a tensor that needs to be dynamically built in the loop. I need to call this method and the other method for each sentence in my training set. I will update my question shortly.
comment on: http://stackoverflow.com/q/50672336
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/137088920
score: 0
type: AnswerComment
has text: This is the right answer in short. I only added an answer to show this with my own json errors.
type: Comment
comment on: http://stackoverflow.com/a/68030022

http://stackoverflow.com/comment/88153621
type: Comment
comment on: http://stackoverflow.com/q/50572004
type: QuestionComment
has text: @RafaelC That does not apply to this
score: 0

http://stackoverflow.com/comment/88122701
comment on: http://stackoverflow.com/q/50555932
score: 0
type: Comment
type: QuestionComment
has text: What do you expext for output?

http://stackoverflow.com/comment/88688185
has text: If that works then you should either post your answer (self-answered questions are allowed) or delete this question. If it doesn't work I would edit this question with the new problem and sample code showing how you are executing the Jenkins call from python.
comment on: http://stackoverflow.com/q/50617459
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51682367
score: 1
answers question: http://stackoverflow.com/q/50576617
upvote count: 1
downvote count: 0
type: Answer
has body: Adding on to this answer, since it feels incomplete to a person installing this for the first time. Doing a pip install python-pdfbox points to the project https://pypi.org/project/python-pdfbox/, that is the expected behavior. The usage instructions indicate to instantiate the pdfbox object like so: p = pdfbox.PDFbox(). At this point, some of us seeking answers may encounter said HTTP Error in this question. Looking into the repository, notice that the version of pdfbox to download is hardcoded. This would imply anyone who pip installs this package will need to be "lucky" enough to have the version of apache pdfbox (which is a java library) at the same version as that. Solution: Disclaimer: I sought to make this work for Windows 10. The package init looks for pdfbox-app on the environment variable. If it does not find it, it tries to download one. Hence the error. Download the latest pdfbox-app-{version}.jar from pdfbox apache. Set the environment variable for PDFBOX e.g set PDFBOX=C:\Dev\pdfbox-app-2.0.11.jar Start a new command line and try: import pdfbox p = pdfbox.PDFBox() p.extract_text("some_filename") Caveat: extract_text() does not recognize spaces file names with spaces, somehow...

http://stackoverflow.com/q/50648127
has comment: http://stackoverflow.com/comment/88385228
has comment: http://stackoverflow.com/comment/88384099
has comment: http://stackoverflow.com/comment/88384793
has comment: http://stackoverflow.com/comment/88389695
has comment: http://stackoverflow.com/comment/88390763
has comment: http://stackoverflow.com/comment/88390635
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/47666679
tagged with: animation
has comment: http://stackoverflow.com/comment/88313644
tagged with: python
has comment: http://stackoverflow.com/comment/88310124
has body: How can we close a python animation after its execution automatically so that the rest of the program can be executed? For example, I have the following code which shows the first animation, but I have to close it manually before the code proceeds to the second animation. Updated import matplotlib.pyplot as plt import numpy as np from PIL import Image from matplotlib.animation import FuncAnimation plt.style.use('classic') def update(step,arr,axis,max_step): print(step,max_step) for i in range(5): for j in range(5): axis[i, j].xaxis.set_major_locator(plt.NullLocator()) axis[i, j].yaxis.set_major_locator(plt.NullLocator()) if arr[step][i, j] == 10: axis[i, j].imshow(Image.open('A.jpg'), cmap="bone") else: axis[i, j].imshow(Image.open('B.jpg'), cmap="bone") if step&gt;=max_step: plt.close() return axis if __name__ == '__main__': a = [] for i in xrange(5): temp = np.zeros((5, 5)) temp[i, i] = 10 a.append(temp) fig, ax = plt.subplots(5, 5, figsize=(5, 5)) fig.subplots_adjust(hspace=0, wspace=0) # FuncAnimation will call the 'update' function for each frame; here # animating over 10 frames, with an interval of 200ms between frames. anim = FuncAnimation(fig, update, frames=5, fargs=(a, ax,4), interval=200, repeat=False) plt.show() # repeat the above procedure a = [] for i in xrange(5): temp = np.zeros((5, 5)) temp[i, i] = 10 a.append(temp) fig, ax = plt.subplots(5, 5, figsize=(5, 5)) fig.subplots_adjust(hspace=0, wspace=0) # FuncAnimation will call the 'update' function for each frame; here # animating over 10 frames, with an interval of 200ms between frames. anim = FuncAnimation(fig, update, frames=5, fargs=(a, ax,4), interval=200, repeat=False) plt.show() Using the suggestion in the comment, the above code actually works but I also get this error: (0, 4) (0, 4) (1, 4) (2, 4) (3, 4) (4, 4) Exception in Tkinter callback Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1536, in __call__ …
has comment: http://stackoverflow.com/comment/88308839
has comment: http://stackoverflow.com/comment/88314135
answer count: 0
tagged with: matplotlib
has title: How to automatically close a python animation after its execution
has comment: http://stackoverflow.com/comment/88384569
has comment: http://stackoverflow.com/comment/88385173
type: Question
has comment: http://stackoverflow.com/comment/88385753
has comment: http://stackoverflow.com/comment/88385724
has comment: http://stackoverflow.com/comment/88389934
duplicate of: http://stackoverflow.com/q/47666679
has comment: http://stackoverflow.com/comment/88390493
score: 0
has comment: http://stackoverflow.com/comment/88312070
has comment: http://stackoverflow.com/comment/88389733
has comment: http://stackoverflow.com/comment/88390547

http://stackoverflow.com/comment/88111047
score: 0
has text: I got Read-only file system: '/var/task/gitpull'
type: Comment
comment on: http://stackoverflow.com/a/50549796
type: AnswerComment

import
type: Tag
tags question: http://stackoverflow.com/q/50618151
tag name: import
tags question: http://stackoverflow.com/q/50660120
tags question: http://stackoverflow.com/q/50595746
tags question: http://stackoverflow.com/q/50673212
tags question: http://stackoverflow.com/q/50587901
tags question: http://stackoverflow.com/q/50625882
tags question: http://stackoverflow.com/q/50547222
tags question: http://stackoverflow.com/q/50580427
tags question: http://stackoverflow.com/q/50622903
tags question: http://stackoverflow.com/q/50633488
tags question: http://stackoverflow.com/q/50633220
tags question: http://stackoverflow.com/q/50585202
tags question: http://stackoverflow.com/q/50552644
tags question: http://stackoverflow.com/q/50609924
tags question: http://stackoverflow.com/q/50683385

http://stackoverflow.com/comment/88212468
type: AnswerComment
has text: Thanks for your help! I will try to work on some code
type: Comment
comment on: http://stackoverflow.com/a/50582978
score: 0

http://stackoverflow.com/a/50546783
upvote count: 1
has comment: http://stackoverflow.com/comment/88153329
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88122052
type: Answer
has body: Your code is unnecessarily messy and very hard to read. You didn't need to create two containers at all because one container is sufficient to fetch you the required data. Try the below way and find the csv with data filled in accordingly: import requests, csv from bs4 import BeautifulSoup url = 'https://www.billboard.com/charts/r-b-hip-hop-songs' with open('Billboard_Hip_Hop_Charts.csv', 'w', newline='') as f: writer = csv.writer(f) writer.writerow(['Billboard Number','Artist Name','Song Title','Last Week Number','peak_position','weeks_on_chart']) res = requests.get(url) soup = BeautifulSoup(res.text, "html.parser") for container in soup.find_all("article",class_="chart-row"): billboard_number = container.find(class_="chart-row__current-week").text artist_name_a_tag = container.find(class_="chart-row__artist").text.strip() song_title = container.find(class_="chart-row__song").text last_week_number_tag = container.find(class_="chart-row__value") last_week_number = last_week_number_tag.text peak_position_tag = last_week_number_tag.find_parent().find_next_sibling().find(class_="chart-row__value") peak_position = peak_position_tag.text weeks_on_chart_tag = peak_position_tag.find_parent().find_next_sibling().find(class_="chart-row__value").text print(billboard_number,artist_name_a_tag,song_title,last_week_number,peak_position,weeks_on_chart_tag) writer.writerow([billboard_number,artist_name_a_tag,song_title,last_week_number,peak_position,weeks_on_chart_tag]) Output are like: 1 Childish Gambino This Is America 1 1 2 2 Drake Nice For What 2 1 6 3 Drake God's Plan 3 1 17 4 Post Malone Featuring Ty Dolla $ign Psycho 4 2 12 5 BlocBoy JB Featuring Drake Look Alive 5 3 14 6 Ella Mai Boo'd Up 10 6 8
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50546401
score: 1
answers question: http://stackoverflow.com/q/50546401

http://stackoverflow.com/q/50631873
favorite count: 0
type: UnansweredQuestion
has body: I receive SSID, password, IP, netmask, DHCP, and DNS on my server. I would like to run a script to connect to wifi with this information. Do you have any suggestions or example to achieve this goal? I'd like to receive this info -> run from command line ./script.sh ssid password ... Then script tries to connect to wifi with this informations. Can you help me?
has title: Run script for auto connection with wifi
score: -1
type: Question
downvote count: 2
has answer: http://stackoverflow.com/a/51221646
answer count: 1
tagged with: javascript
upvote count: 1
tagged with: python

http://stackoverflow.com/a/50561612
answers question: http://stackoverflow.com/q/50561412
type: Answer
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/88133613
has body: What you need is not mapping but replacing i.e df['Device'] = df['Device'].replace(f) 0 Asus 1 Xiaomi 2 Xiaomi 3 Asus 4 Samsung Name: Device, dtype: object ​
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50561412
has comment: http://stackoverflow.com/comment/88133602

http://stackoverflow.com/comment/88349268
type: Comment
comment on: http://stackoverflow.com/a/50669493
has text: @The42ndTurtle: any GPIO pin that's not used otherwise should be fine. Taking https://pinout.xyz/ any BCMxx pin without special function (stated in parentheses) should work.
score: 0
type: AnswerComment

http://stackoverflow.com/a/70312357
type: Answer
has body: import fitz filepath = "C:\\user\\docs\\aPDFfile.pdf" text = '' with fitz.open(filepath ) as doc: for page in doc: text+= page.get_text() print(text)
upvote count: 3
downvote count: 2
score: 1
answers question: http://stackoverflow.com/q/50682486
has comment: http://stackoverflow.com/comment/124306267

wsgi
type: Tag
tags question: http://stackoverflow.com/q/50555370
tags question: http://stackoverflow.com/q/50557795
tags question: http://stackoverflow.com/q/50696031
tag name: wsgi

http://stackoverflow.com/q/50678319
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88366737
tagged with: python
tagged with: utf-8
has comment: http://stackoverflow.com/comment/88366383
answer count: 0
has comment: http://stackoverflow.com/comment/88367265
has body: I've been trying to use read a .xlsx file using pandas.read_excel, but the output only shows a question mark in the place of non-English characters like í. I've tried: df = pandas.read_excel(u"C:\MyFile.xlsx") and df = pandas.read_excel("C:\MyFile.xlsx", encoding='utf-8') I also tried other encoding formats like utf-16,utf-32, utf-8-sig, iso-8859-1, etc. None of these seem to work. Kindly help. UPDATE: It works perfectly on cmd, but not when i run it using visual studio code. In cmd, BeautifulSoup is giving a similar error for the html file which works fine on visual studio!
tagged with: excel
type: Question
has comment: http://stackoverflow.com/comment/88366219
score: 0
has comment: http://stackoverflow.com/comment/88366342
tagged with: encoding
tagged with: pandas
has comment: http://stackoverflow.com/comment/88366397
has title: pandas_read.excel() not able to read non-English characters

http://stackoverflow.com/comment/88386410
type: Comment
comment on: http://stackoverflow.com/a/50687964
score: 0
type: AnswerComment
has text: Also, I see no reason you need to convert to `float`. If it's not possible, it should be caught by `ValueError`.

http://stackoverflow.com/comment/88188747
comment on: http://stackoverflow.com/q/50588350
score: 0
has text: No images but code/ text that we can copy and paste, please.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50662220
upvote count: 2
has title: Print Lines from .csv based off criteria inputted from user
has comment: http://stackoverflow.com/comment/88334697
possible better answer: http://stackoverflow.com/a/50662297
has answer: http://stackoverflow.com/a/50662297
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/50662332
has answer: http://stackoverflow.com/a/50666080
downvote count: 0
favorite count: 0
has body: I am new to python and am looking for guidance on the task I am working on. I am importing a csv file that looks like the list below. invoice_id,customer_first_name,customer_last_name,part_number,quantity,total 18031,Hank,Scorpio,367,1,2.63 54886,Max,Power,171,3,50.79 19714,Jonathan,Frink,179,2,7.93 19714,Jonathan,Frink,378,2,32.34 22268,Gil,Gunderson,165,2,47.15 87681,Lionel,Hutz,218,1,50.83 84508,Lurleen,Lumpkin,257,1,81.95 34018,Lionel,Hutz,112,3,88.88 34018,Lionel,Hutz,386,3,86.04 34018,Lionel,Hutz,216,1,53.54 66648,Patty,Bouvier,203,3,70.47 I only want to print each line if its based off the criteria inputted by the user. For example, if the user inputs lname and then inputs Hutz the following would be printed out. 87681,Lionel,Hutz,218,1,50.83 34018,Lionel,Hutz,112,3,88.88 34018,Lionel,Hutz,386,3,86.04 34018,Lionel,Hutz,216,1,53.54 4 records found. This is what I have so far... salesdatafile= None while True: salesdatafilename=input("Enter the name of the file:") try: salesdata= open(salesdatafilename, 'r') break except FileNotFoundError: print("{0} was not found".format ( salesdatafilename )) search=input("Do you want to search by invoice id or lname? Please type id or lname: ") idsearch=salesdata.readline() if search== 'id': idnumber=print(int(input('Please enter Id to search: '))) while idsearch != '': if idsearch== idnumber: print(idsearch) else: lname=print(input('Please enter your last name: ')) while idsearch != '': if idsearch== lname: print(idsearch) All that is printing out is lname or id inputted by the user.
answer count: 3
tagged with: python
score: 2
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50662332

http://stackoverflow.com/q/50676472
answer count: 1
has comment: http://stackoverflow.com/comment/88364341
has comment: http://stackoverflow.com/comment/88364348
has comment: http://stackoverflow.com/comment/88362778
tagged with: python
has comment: http://stackoverflow.com/comment/88363628
has body: I would like to use SSL over something other than sockets. The ssl TLS/SSL wrapper is only for socket objects. For example I have my own IPC class such as: class MyIPC: def recv(self): return self.received_data if self.data else None def send(self, message): self._send(message) In these scheme I would like to wrap this above class to the ssl Python module. Is this something possible. Notice this MyIPC class is p2p communication. In the real world. I would like to use MQTT for the data exchange. I guess one option is to write a duck-type class to mimic a Socket Object, but I am sure there is a better option.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88363520
has comment: http://stackoverflow.com/comment/88363554
has title: SSL over anything?
type: Question
has answer: http://stackoverflow.com/a/50679227
accepted answer: http://stackoverflow.com/a/50679227
has comment: http://stackoverflow.com/comment/88364224
has comment: http://stackoverflow.com/comment/88363548
tagged with: ssl
score: 0
has comment: http://stackoverflow.com/comment/88395228

http://stackoverflow.com/comment/88219542
comment on: http://stackoverflow.com/q/50595508
score: 0
type: Comment
type: QuestionComment
has text: @ziiiro, it working as expected, thanks

http://stackoverflow.com/comment/88302271
type: Comment
comment on: http://stackoverflow.com/q/50645806
has text: in other words, you want to connect (for example) green and blue dots, then red and orange ones? scatter is specifically not to connect data points. You just want to stack two variables and sort them
score: 0
type: QuestionComment

http://stackoverflow.com/q/50632275
has answer: http://stackoverflow.com/a/50638526
type: Question
tagged with: automation
upvote count: 1
has title: Action on detection of object
answer count: 1
favorite count: 0
has body: Today I successfully build a custom object detection system using tensorflow (deep learning) and cv2. Now for the next step, I want to implement an Action(or trigger) like if this object is detected then do this. example: if a baseball bat is detected then print "let's try to make a home run" Actually, after a particular object is detected then I want to send a message to my android app using google firebase. # coding: utf-8 # # Object Detection Demo # Welcome to the object detection inference walkthrough! This notebook will walk you step by step through the process of using a pre-trained model to detect objects in an image. Make sure to follow the [installation instructions] # # Imports import numpy as np import os import six.moves.urllib as urllib import sys import tarfile import tensorflow as tf import zipfile from collections import defaultdict from io import StringIO from matplotlib import pyplot as plt from PIL import Image import cv2 cap = cv2.VideoCapture(0) # ## Env setup # This is needed since the notebook is stored in the object_detection folder. sys.path.append("..") sys.path.append("D:\work\O_detection\models") sys.path.append("D:\work\O_detection\models\slim") # ## Object detection imports # Here are the imports from the object detection module. from utils import label_map_util from utils import visualization_utils as vis_util # # Model preparation # ## Variables # Any model exported using the `export_inference_graph.py` tool can be loaded here simply by changing `PATH_TO_CKPT` to point to a new .pb file. # By default we use an "SSD with Mobilenet" model here. See the [detection model zoo] # What model to download. / load from memory MODEL_NAME = 'gun_detection_graph' #MODEL_FILE = MODEL_NAME + '.tar.gz' #DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/' # Path to frozen detection graph. This is the actual model that is used for the object detection. PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb' # List of the strings …
type: UnansweredQuestion
tagged with: python
tagged with: computer-vision
tagged with: opencv
downvote count: 0
score: 1
tagged with: tensorflow

http://stackoverflow.com/q/50575794
tagged with: python
has comment: http://stackoverflow.com/comment/88162613
linked to: http://stackoverflow.com/q/50484676
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88339816
tagged with: tensorflow
type: Question
has body: Thanks for your help. This question has bothered me for 2 days. I searched many sites and did not solve. Background: I am learning mnist, and it goes right at first, but when I save the model and restore, there is an Error, told me placeholder_1 must be fed. I am confused. Code: Below code goes right. import tensorflow.examples.tutorials.mnist.input_data as input_data mnist = input_data.read_data_sets("mnist data/", one_hot=True) import tensorflow as tf # 操作符号变量来描述这些可交互的操作单元 x = tf.placeholder(tf.float32, [None, 784]) # 权重值和偏置量 W = tf.Variable(tf.zeros([784,10])) b = tf.Variable(tf.zeros([10])) # 实现模型 y = tf.nn.softmax(tf.matmul(x,W) + b) # 添加一个新的占位符用于输入正确值 y_ = tf.placeholder("float", [None,10]) # 计算交叉熵: cross_entropy = -tf.reduce_sum(y_*tf.log(y)) # 要求TensorFlow用梯度下降算法（gradient descent algorithm）以0.01的学习速率最小化交叉熵 train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) # 添加一个操作来初始化我们创建的变量 init = tf.initialize_all_variables() saver = tf.train.Saver() sess = tf.Session() sess.run(init) for i in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100) sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) save_path = saver.save(sess, "./model_mnist.ckpt",write_meta_graph=False) print("Model saved in life:", save_path) import cv2 import numpy as np img = cv2.imread('lena.png') img = cv2.resize(img, (28,28)) img = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY) arr = [] for i in range(28): for j in range(28): gray = 1 - img[i,j]/255 arr.append(gray) arr_mnist = np.array([arr]) #print(arr_mnist) result = sess.run(y, feed_dict={x:arr_mnist}) print(result) #print(np.argmax(result[0])) #print(np.sum(result[0])) print("预测值为：",np.argmax(result[0]),"；概率为：",np.max(result[0])/np.sum(result[0])) #print(tf.argmax(result,1)) But, when I want to use the model to restore. it goes wrong. import cv2 import numpy as np import tensorflow as tf img = cv2.imread('lena.png') img = cv2.resize(img, (28,28)) img = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY) arr = [] for i in range(…
has title: tensorflow model save and restore issue
answer count: 1
has answer: http://stackoverflow.com/a/50576073
score: 0

http://stackoverflow.com/a/50639541
upvote count: 7
type: Answer
has body: From my previous experiences, you are probably consuming the map object before printing it out. map returns a consumable iterator so if you want to print the values of it, make sure you don't consume it. For example, &gt;&gt;&gt; n = map(int, input().strip().split()) 1 2 3 4 5 &gt;&gt;&gt; for i in n: ... print(i) ... 1 2 3 4 5 &gt;&gt;&gt; for i in n: ... print(i) # prints nothing
downvote count: 0
score: 7
has comment: http://stackoverflow.com/comment/88289096
answers question: http://stackoverflow.com/q/50639430

http://stackoverflow.com/comment/88147246
comment on: http://stackoverflow.com/a/50568544
score: 0
type: Comment
has text: glad to help you!
type: AnswerComment

http://stackoverflow.com/a/50547264
upvote count: 4
answers question: http://stackoverflow.com/q/50546740
score: 4
downvote count: 0
has body: I agree with RafaelC that padding your list for 2018 data with NaNs for missing values is the best way to do this. You can use np.nan from Numpy (which you will already have installed since you have Pandas) to generate NaNs. import pandas as pd import numpy as np months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] index_yrs = [2016, 2017, 2018] As a small change to your code I've put data for all three years into a years list which we can pass as the data parameter for pd.DataFrame. This eliminates the need to append each row to the previous ones. r2016 = [26, 27, 25, 22, 20, 23, 22, 20, 20, 18, 18, 19] r2017 = [20, 21, 18, 16, 15, 15, 15, 15, 13, 13, 14, 15] r2018 = [16, 18, 18, 18, 17] years = [r2016] + [r2017] + [r2018] This is what years looks like: [[26, 27, 25, 22, 20, 23, 22, 20, 20, 18, 18, 19], [20, 21, 18, 16, 15, 15, 15, 15, 13, 13, 14, 15], [16, 18, 18, 18, 17]]. As for padding your year 2018 with NaNs something like this might do the trick. We are just ensuring that if a year only has values for the first n months that the remaining months will be filled out with NaNs. for year in years: if len(year) &lt; 12: year.extend([np.nan] * (12 - len(year))) Finally we can create your dataframe using the one liner below instead of appending row by row. df = pd.DataFrame(years, columns=months, index=index_yrs).astype(float) Output: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 2016 26.0 27.0 25.0 22.0 20.0 23.0 22.0 20.0 20.0 18.0 18.0 19.0 2017 20.0 21.0 18.0 16.0 15.0 15.0 15.0 15.0 13.0 13.0 14.0 15.0 2018 16.0 18.0 18.0 18.0 17.0 NaN NaN NaN NaN NaN NaN NaN You may notice that I converted the dtype of the values in the dataframe to float using .astype(float). I did this to make all of your columns as the same dtype. If we don't call .astype(float) then Jan-May will be dtype int and Jun-Dec will be dtype float64.
type: Answer

cryptography
tag name: cryptography
type: Tag
tags question: http://stackoverflow.com/q/50655774

http://stackoverflow.com/comment/88250042
comment on: http://stackoverflow.com/q/50619859
has text: It's not easy to debug code that one can't see. :-)
score: 0
type: Comment
type: QuestionComment

data-science
tags question: http://stackoverflow.com/q/50542635
tags question: http://stackoverflow.com/q/50664480
tags question: http://stackoverflow.com/q/50647450
type: Tag
tags question: http://stackoverflow.com/q/50689823
tags question: http://stackoverflow.com/q/50658576
tags question: http://stackoverflow.com/q/50627444
tags question: http://stackoverflow.com/q/50634919
tags question: http://stackoverflow.com/q/50621614
tags question: http://stackoverflow.com/q/50557129
tags question: http://stackoverflow.com/q/50614761
tags question: http://stackoverflow.com/q/50595924
tags question: http://stackoverflow.com/q/50693921
tag name: data-science
tags question: http://stackoverflow.com/q/50667735
tags question: http://stackoverflow.com/q/50636819
tags question: http://stackoverflow.com/q/50665704

http://stackoverflow.com/comment/88120112
type: QuestionComment
has text: The traceback shows `is_numeric_dtype` is being imported from `pandas.core.common` but as far as I know it is currently under `pandas.api.types`. See the [docs](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.api.types.is_numeric_dtype.html). Maybe you've updated your pandas but not the other libraries that depend on older versions of pandas? It seems the error is coming from `pandas_summary` package. Is that up to date?
comment on: http://stackoverflow.com/q/50554428
score: 0
type: Comment

http://stackoverflow.com/comment/88313446
type: Comment
type: QuestionComment
has text: I don't think this is a dupe. The linked question is about how to use `findall` in the first place, not about this question's issue about too many capturing groups.
score: 1
comment on: http://stackoverflow.com/q/50651146

http://stackoverflow.com/q/50603433
upvote count: 1
has comment: http://stackoverflow.com/comment/88216132
linked to: http://stackoverflow.com/q/423379
has comment: http://stackoverflow.com/comment/88216152
has comment: http://stackoverflow.com/comment/88547232
duplicate of: http://stackoverflow.com/q/370357
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88216095
has body: I have this code which works as expected: foo = 123 def fooBar(): print(foo) ### cannot find foo from local scope, checks prev and prints 123 #foo = 987 #print(foo) fooBar() But when I change the code to the following, foo = 123 def fooBar(): print(foo) ### blows up here... foo = 987 print(foo) fooBar() it blows up on the print statement: Traceback (most recent call last): File "python", line 9, in <module> File "python", line 4, in fooBar UnboundLocalError: local variable 'foo' referenced before assignment I know I can get around the problem using global foo inside my function, but the error I was expected was not on line number I was expecting. I was assuming it would still print 123 and then blow up when I try to assign another value to foo. It seems as if Python parses fooBar() and knows I do an assignment of foo later in local function and then blows up on the print, instead of grabbing the global value? Is that right?
linked to: http://stackoverflow.com/q/49538724
has comment: http://stackoverflow.com/comment/88216135
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/88218660
score: 1
favorite count: 0
type: Question
tagged with: python
has title: Python global variable/dynamic interpreted?

http://stackoverflow.com/comment/88296171
type: Comment
has text: With YAML, you could invent your own `!include` tag. In PyYAML you can define what to do when loading a node with such a tag.
type: QuestionComment
comment on: http://stackoverflow.com/q/50641988
score: 0

http://stackoverflow.com/comment/88344836
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50667212
has text: Thanks bro. I did it.
score: 0

http://stackoverflow.com/comment/88355867
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50672781
type: Comment
has text: Thank you dude i was waste a lot of time thinking in a way of doing this i really apreciate for your help

http://stackoverflow.com/a/50694887
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50684496
downvote count: 0
type: Answer
has body: I would strongly recommend you to have a look at Cloud Machine Learning Engine. This product of the Google Cloud Platform family looks like a really nice fit for what you want to do, as it allows you to train models in the cloud, keep them there, and run predictions based on the input data of your choice, with the models you already trained. As of now, it works with TensorFlow (which I think is what you are planning on using, as you are working with Neural Networks), and just recently, scikit-learn and XGBoost were introduced as a beta release. Let me share with you some documentation references that you may find useful in order to start working with ML Engine, but I encourage you to navigate through the documentation in order to get more familiar with this service: Training Models: a list of requirements, best-practices, and processes to train a model in Cloud ML Engine. You can configure your trainer to use GPUs (or even the recently released TPUs) in order to improve performance, and you can use hyperparameter tuning to obtain the best of your models. Deploying Models: you can export your trained model to a SavedModel, load it into the Cloud and get it ready for serving prediction requests. Running Predictions: you can run two types of prediction jobs: batch (optimized to handle high volumes of data with complex models) or online (optimized to minimize latency). Batch prediction can also be used to run models stored in Cloud Storage locations. Use Google Cloud Storage as your main storage location. ML Engine is optimized to work with GCS. You will be able to upload your input data and models in GCS, and process that data using ML Engine.

http://stackoverflow.com/q/50630657
has answer: http://stackoverflow.com/a/50632321
type: UnansweredQuestion
score: 1
upvote count: 1
tagged with: machine-learning
type: Question
tagged with: neural-network
has body: I have 1000, 28*28 resolution images. I converted those 1000 images into numpy array and formed a new array with size of (1000,28,28). So, while creating convolution layer using keras, input shape(X value) is specified as (1000,28,28) and output shape(Y value) as (1000,10). Because I ha ve 1000 examples are inputs and 10 categories of output. model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3),activation='relu',kernel_initializer='he_normal',input_shape=(1000,28,28))) . . . model.fit(train_x,train_y,batch_size=32,epochs=10,verbose=1) So, while using fit function, it shows ValueError: Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (1000, 28, 28) as error. Pls help me guys to provide proper input and output dimension for CNN. Code: model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3),activation='relu',kernel_initializer='he_normal',input_shape=(4132,28,28))) model.add(MaxPooling2D((2, 2))) model.add(Dropout(0.25)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Conv2D(128, (3, 3), activation='relu')) model.add(Dropout(0.4)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.3)) model.add(Dense(10, activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy,optimizer=keras.optimizers.Adam(),metrics=['accuracy']) model.summary() train_x = numpy.array([train_x]) model.fit(train_x,train_y,batch_size=32,epochs=10,verbose=1)
has title: Error in Convolutional Neural network for input shape
answer count: 3
tagged with: deep-learning
downvote count: 0
has answer: http://stackoverflow.com/a/50630693
favorite count: 0
has answer: http://stackoverflow.com/a/50792664
tagged with: python
tagged with: conv-neural-network

http://stackoverflow.com/comment/88339149
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50658983
has text: Great!! what if i don't want dict style output but single units?

http://stackoverflow.com/comment/88128453
comment on: http://stackoverflow.com/a/50558927
has text: Why plagiarise an answer when you can flag as duplicate?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50639381
has comment: http://stackoverflow.com/comment/88290623
tagged with: cython
has comment: http://stackoverflow.com/comment/88289008
has title: Anaconda3 Cython: gcc cannot find -lpthread, -lc
tagged with: anaconda
score: 4
type: Question
upvote count: 4
tagged with: pthreads
downvote count: 0
has comment: http://stackoverflow.com/comment/88360017
favorite count: 0
has comment: http://stackoverflow.com/comment/88291321
has body: I'm running Anaconda3 with python3.6.5 on Xubuntu 16.04. I want to run the simple Cython example here but ran straight into a wall. $ cat helloworld.pyx print("Hello World") $ cat setup.py from distutils.core import setup from Cython.Build import cythonize setup( ext_modules = cythonize("helloworld.pyx") ) $ python setup.py build_ext --inplace Compiling helloworld.pyx because it changed. [1/1] Cythonizing helloworld.pyx running build_ext building 'helloworld' extension creating build creating build/temp.linux-x86_64-3.6 gcc -pthread -B /home/j/OFFICIAL/anaconda3/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/j/OFFICIAL/anaconda3/include/python3.6m -c helloworld.c -o build/temp.linux-x86_64-3.6/helloworld.o gcc -pthread -shared -B /home/j/OFFICIAL/anaconda3/compiler_compat -L/home/j/OFFICIAL/anaconda3/lib -Wl,-rpath=/home/j/OFFICIAL/anaconda3/lib -Wl,--no-as-needed -Wl,--sysroot=/ build/temp.linux-x86_64-3.6/helloworld.o -o /home/j/gits/proj/fitting_multipoles/test/helloworld.cpython-36m-x86_64-linux-gnu.so /home/j/OFFICIAL/anaconda3/compiler_compat/ld: cannot find -lpthread /home/j/OFFICIAL/anaconda3/compiler_compat/ld: cannot find -lc collect2: error: ld returned 1 exit status error: command 'gcc' failed with exit status 1 Tried to update all conda packages with conda update --all, didn't help. Did conda install cython, didn't help. I tried to run the gcc commands from the output message in the terminal. The first is fine, only the second one raises the errors. What is the problem?
tagged with: linker
tagged with: python
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/88167151
type: AnswerComment
score: 0
type: Comment
has text: @PaulaThomas I did. No luck. Maybe I'm not feeding it corectly, that's why I asked for a full code, or a guide where to place it inside my code. Thank you Paula
comment on: http://stackoverflow.com/a/50578871

http://stackoverflow.com/comment/88156049
type: QuestionComment
comment on: http://stackoverflow.com/q/50573171
has text: no, thanks, I'm happy your problem is solved
score: 0
type: Comment

http://stackoverflow.com/q/50675671
favorite count: 0
has answer: http://stackoverflow.com/a/50675749
has comment: http://stackoverflow.com/comment/88361035
tagged with: python
has body: How can I match the string which starts with C88 and ends with 03D using regex in Python from the text below: 0:d=0 hl=4 l= 266 cons: SEQUENCE 4:d=1 hl=4 l= 257 prim: INTEGER :C88C87D325BFC86211ED38A05F04F90A92F252E9D6E5425D54F1B27F3888F95B123BFBB634864DEDF0A6B8636830B6AB70011C6B4C6D8368BCD6FC72D1C341B97130737F0BA520D4C44982EA4554AE19CD54F21DA48ECF634C38E3586253FFC815633510FA4FA8B7B1E07E4E2EABF48603EDFB2E53DFA6CC1F894F892B742B84A2CEA29837B1047D7CC401365B3091B6C7DED09CD3BFECD8EAF66F198A80B27DB9DB334CAE200410AE984D3CE413D8BA04833AB5CE7B7FA43CC848143F82B542343D537E4C79DB30FDFDB66B01259CACE9C3D430A38574F3A09278DD4263CACB8A12175CE7A082FBA63A565F31CBA2176C710008C1781E50C5270FE18142B03D 265:d=1 hl=2 l= 3 prim: INTEGER :010001 As it is clearly seen, there are also some whitespace between the string and the keyword 'INTEGER'. If needed, we know the exact length of the match which is 512 characters.
tagged with: regex
type: AnsweredQuestion
downvote count: 3
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50675749
score: -2
has title: Find an exact length match in a string using regex in python
answer count: 1

http://stackoverflow.com/a/67898465
type: Answer
has body: Another way using json! import pandas as pd import json with open('File_location.json') as f: data = json.load(f) df=pd.DataFrame(data)
upvote count: 2
has comment: http://stackoverflow.com/comment/137088359
downvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/120017407
answers question: http://stackoverflow.com/q/50653973

http://stackoverflow.com/comment/88146479
type: Comment
score: 0
type: QuestionComment
has text: @HitLuca I will add more comments
comment on: http://stackoverflow.com/q/50567930

http://stackoverflow.com/a/50656049
has comment: http://stackoverflow.com/comment/88324702
type: Answer
score: 1
answers question: http://stackoverflow.com/q/50655955
has body: From the docs: class int(x=0) class int(x, base=10) [...] If the argument is outside the integer range, the function returns a long object instead. With PEP 237, ints and longs were mostly unified. There is little difference between the two types and python automatically converts big numbers to long when necessary. See also How does Python manage int and long?.
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/50568495
has title: TemplateSyntaxError with static django 2
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: AnsweredQuestion
has body: I have this code: HTML {% load static %} &lt;!--[if lte IE 8]&gt;&lt;script src="{% static game_reviews/css/ie/html5shiv.js %}"&gt;&lt;/script&gt;&lt;![endif]--&gt; settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'game_reviews',] STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder',] STATIC_URL = '/static/' i had a folder inside my app called static/game_reviews, and inside have multiple folder (js, css, etc.). and i getting this error : TemplateSyntaxError at /game_reviews/ Could not parse the remainder: '/css/ie/html5shiv.js' from 'game_reviews/css/ie/html5shiv.js' Any help?. Thanks in advance.
accepted answer: http://stackoverflow.com/a/50568544
tagged with: django
type: Question
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50568544

http://stackoverflow.com/a/50553386
answers question: http://stackoverflow.com/q/50553261
score: -1
upvote count: 0
type: Answer
has body: You can do this by defining the ACE as a class class ACE(): value = 1 def set_value(self, value): self.value = value And then you can change the value of array element like this ace = ACE() # in this step you have ace value = 1 array = [ace, 1, 2, 3, ...] for a in array: if type(a) == type(ACE): # Your desired conditions a.set_value(14)
downvote count: 1

http://stackoverflow.com/comment/88245752
has text: No no. I mean how to increase the contrast of an image?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50617077
type: Comment

http://stackoverflow.com/a/50606412
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/50606139
has comment: http://stackoverflow.com/comment/89547371
type: AcceptedAnswer
has body: I have found the issue. As base_estimator I have set 'DecisionTreeClassifier'. THIS is a sting and has no fit() method. The AdaBoost IS NOT a string. from sklearn.ensemble import AdaBoostClassifier from sklearn.preprocessing import LabelEncoder for label in dataset.columns: dataset[label] = LabelEncoder().fit(dataset[label]).transform(dataset[label]) X = dataset.drop(['target'],axis=1) Y = dataset['target'] AdaBoost = AdaBoostClassifier(n_estimators=400,learning_rate=0.01,algorithm='SAMME') AdaBoost.fit(X,Y) prediction = AdaBoost.score(X,Y) print(prediction) 0.9182668636139832
score: 0
accepted answer of: http://stackoverflow.com/q/50606139
upvote count: 1

http://stackoverflow.com/q/50641843
tagged with: amazon-dynamodb
has answer: http://stackoverflow.com/a/50647274
has body: I'm posting a simple JSON structure to Amazon Gateway API from Python. Here's the JSON structure: payload = { 'ping': '1.967', 'download': '570.01', 'upload': '697.85', 'timestamp': '1527845073' } And here's the python code: headers = {'content-type':'application/json'} r = requests.post("https:xxx.execute-api.us-east-1.amazonaws.com/beta/device", data = payload ,headers=headers) print(r.status_code, r.reason) print(r.text) r.status_code is returned as '200' r.reason is returned as 'Ok' r.text is returned as {"__type":"com.amazon.coral.validate#ValidationException","message":"One or more parameter values were invalid: An AttributeValue may not contain an empty string"} The parameters are clearly not empty so I'm not sure why I'm getting that error. I have a Body Mapping Template in the Integration Request that looks like this: { "TableName": "device", "Item": { "id": { "S": "$context.requestId" }, "ping": { "S": "$input.path('$.ping')" }, "download": { "S": "$input.path('$.download')" }, "upload": { "S": "$input.path('$.upload')" }, "timestamp": { "S": "$input.path('$.timestamp')" } } } And when I run the test from within AWS Gateway API Console, the data inputs into the DynamoDB just fine. However, it won't work from Python. Any idea what I could be doing wrong? I'm betting it's a silly mistake. Thank you.
type: Question
has title: POST to AWS Gateway API from Python into Dynamodb
tagged with: amazon-web-services
accepted answer: http://stackoverflow.com/a/50647274
answer count: 1
has comment: http://stackoverflow.com/comment/88300349
tagged with: python
has comment: http://stackoverflow.com/comment/88320218
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/50578544
favorite count: 0
has title: Tensorflow: using argmax to slice a tensor
upvote count: 2
has body: I have a tensor with shape tf.shape(t1) = [1, 1000, 400] and I obtain the indices of the maxima on the 3rd dimension using max_ind = tf.argmax(t1, axis=-1) which has shape [1, 1000]. Now I have a second tensor that has the same shape as t1: tf.shape(t2) = [1, 1000, 400]. I want to use the maxima indices from t1 to slice t2 so the output has the form [1, 1000] A more visual description: The resulting tensor should be like the result of tf.reduce_max(t2, axis=-1) but with the location of the maxima in t1
tagged with: python
has answer: http://stackoverflow.com/a/50579716
type: AnsweredQuestion
score: 1
downvote count: 1
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/50579716
possible better answer: http://stackoverflow.com/a/74087795
has answer: http://stackoverflow.com/a/74087795
answer count: 2

http://stackoverflow.com/q/50632367
score: 0
has comment: http://stackoverflow.com/comment/88275098
has title: Python3.5 : Send datas through in tread socket
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88274985
tagged with: python
has body: Edit : I changed title and question to be more related to my problem : I try to exchange datas (dictionnaries mostly) between a server and a client, using a socket connexion. Size of exchanged datas is not always the same, so i made this class to do the operation : bsfc.py: class Reseau(): msg_sent = False @classmethod def snd_data(cls, connexion, data): print('22') pdata = pickle.dumps(data) print('22') len_msg = len(pdata) plen = pickle.dumps(len_msg) print('22') while cls.msg_sent is not True : connexion.sendall(plen) time.sleep(0.1) cls.msg_sent=False print('22') while cls.msg_sent is not True : connexion.sendall(pdata) time.sleep(0.1) cls.msg_sent = False print('22') @classmethod def get_data(cls, connexion): print('00') plen_msg=connexion.recv(1024) cls.msg_sent=True print('00') len_msg=pickle.loads(plen_msg) print('{}'.format(len_msg)) pdata = connexion.recv(len_msg*2) cls.msg_sent = True data=pickle.loads(pdata) print(data) return data (i added some print to see where the program starts to bug) now when i launch this server: serveur.py import socket import select from threading import Thread from bsfc import Reseau class Find_clients(Thread): def __init__(self): Thread.__init__(self) self.connexion_serveur = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.connexion_serveur.bind(('', 12800)) self.connexion_serveur.listen(5) def run(self): print('serveur connecté') serveur = True while serveur : connexions_demandees, wlist, xlist = select.select([self.connexion_serveur], [], [], 1) for connexion in connexions_demandees : connexion_client, infos_connexion = connexion.accept() if connexion_client is not None : msg="connexion acceptee" print('msg') Reseau.snd_data(connexion_client, msg) print('msg') user=Reseau.get_data(connexion_client) print('msg') user['connexion_client']=connexion_client user['infos_connexion']=infos_connexion Clients.add_user(user) if __name__=='__main__' : serveur=Find_clients() serveur.start() serveur.join() and then i try to join i…
answer count: 0
tagged with: class-attributes
has comment: http://stackoverflow.com/comment/88275093
type: Question
has comment: http://stackoverflow.com/comment/88274934
has comment: http://stackoverflow.com/comment/88275045
has comment: http://stackoverflow.com/comment/88275074
linked to: http://stackoverflow.com/q/35990313

http://stackoverflow.com/q/50594925
has body: I am wondering how one could separate the blocks of text within the same text file. The example is below. Basically I have 2 items, one goes from "Channel 9" to the line with "Brief:..", the other one starts with "Southern ..." to again, the "Brief" line. How does one go about separating them into 2 text files with python? I reckon the common divider would be "(female 16+)". Many thanks! Channel 9 (1 item) A woman selling her caravan near Bendigo has been left $1,100 out hosted by Peter Hitchener A woman selling her caravan near Bendigo has been left $1,100 out of pocket after an elderly couple made the purchase with counterfeit money. The wildlife worker tried to use the notes to pay for a house deposit, but an agent noticed the notes were missing the Coat of Arms on one side. Brief: Radio &amp; TV Demographics: 153,000 (male 16+) • 177,000 (female 16+) Southern Cross Victoria Bendigo (1 item) Heathcote Police are warning the residents to be on the lookout a hosted by Jo Hall Heathcote Police are warning the residents to be on the lookout after a large dash of fake $50 note was discovered. Victim Marianne Thomas was given counterfeit notes from a caravan. The Heathcote resident tried to pay the house deposit and that's when the counterfeit notes were spotted. Thomas says the caravan is in town for the Spanish Festival. Brief: Radio &amp; TV Demographics: 4,000 (male 16+) • 3,000 (female 16+)
has answer: http://stackoverflow.com/a/50595116
accepted answer: http://stackoverflow.com/a/50595116
type: Question
possible better answer: http://stackoverflow.com/a/50594985
has answer: http://stackoverflow.com/a/50594986
has answer: http://stackoverflow.com/a/50594992
has comment: http://stackoverflow.com/comment/88199104
tagged with: block
score: 0
has title: Separate blocks of text python
has answer: http://stackoverflow.com/a/50594985
tagged with: python
answer count: 4
tagged with: text
type: AnsweredQuestion

http://stackoverflow.com/q/50602085
has body: When I am using the below line in my code vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length, vocabulary=bow) I get theses warnings. How do I eliminate them ? WARNING:tensorflow:From /usr/local/lib/python3.5/dist-packages/tensorflow/contrib/learn/python/learn/datasets/base.py:198: retry (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version. Instructions for updating: Use the retry module or similar alternatives. WARNING:tensorflow:From /tmp/anyReader-376H566fJpAUSEt/anyReader-376qtSRQxT2gOiq.tmp:67: VocabularyProcessor.__init__ (from tensorflow.contrib.learn.python.learn.preprocessing.text) is deprecated and will be removed in a future version. Instructions for updating: Please use tensorflow/transform or tf.data. WARNING:tensorflow:From /usr/local/lib/python3.5/dist-packages/tensorflow/contrib/learn/python/learn/preprocessing/text.py:154: CategoricalVocabulary.__init__ (from tensorflow.contrib.learn.python.learn.preprocessing.categorical_vocabulary) is deprecated and will be removed in a future version. Instructions for updating: Please use tensorflow/transform or tf.data. WARNING:tensorflow:From /usr/local/lib/python3.5/dist-packages/tensorflow/contrib/learn/python/learn/preprocessing/text.py:170: tokenizer (from tensorflow.contrib.learn.python.learn.preprocessing.text) is deprecated and will be removed in a future version. Instructions for updating: Please use tensorflow/transform or tf.data.
tagged with: machine-learning
tagged with: tensorflow
type: Question
tagged with: deprecation-warning
score: 0
answer count: 2
upvote count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/64442098
has answer: http://stackoverflow.com/a/50611284
type: UnansweredQuestion
has title: Tensorflow contrib learn deprecation warnings
tagged with: python

http://stackoverflow.com/q/50698710
has body: I have a dictionary which contains a list and the list elements are supposed to be tuple I am creating a product filter from filter.py I am sending the tuple as per the user choice in URL and in views.py qu=dict(request.GET) #qu={'price':['(300,600)']} I want to run the following query result=Product.objects.all() for key, value in qu.items(): result=result.filter(attribute__price__range=value) print (result) I am getting IndexError :tuple index out of range
type: Question
has comment: http://stackoverflow.com/comment/88406601
accepted answer: http://stackoverflow.com/a/50698930
score: 0
answer count: 1
has title: IndexError :tuple index out of range
has answer: http://stackoverflow.com/a/50698930
has comment: http://stackoverflow.com/comment/88406669
tagged with: django
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/50576681
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50577098
tagged with: python-2.7
tagged with: pandas
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/41941605
upvote count: 1
tagged with: python
type: AnsweredQuestion
has title: Pandas filling missing value from yesterday data (same DataTime) in python
has answer: http://stackoverflow.com/a/50577098
score: 1
type: Question
has body: I am trying to fill missing value by yesterday (one day back data) in python. for the same I am trying with following code but not getting expected output. Code import pandas as pd df = pd.read_csv(r'input_3.csv') saved_column = df.Value #you can also use df['column_name'] df['DateTime'] = pd.DatetimeIndex(df['DateTime']) b = df.loc[df.Value.isnull(), 'Value'] = \ df.loc[df.Value.isnull(), 'Value'].map(df.loc[df.Value.notnull()] \ .set_index('DateTime')['Value']) print b Yesterday's Data: block DateTime Value 1 09-01-2016 00:00 -0.886492 2 09-01-2016 01:00 -0.500995 3 09-01-2016 02:00 4 4 09-01-2016 03:00 5 5 09-01-2016 04:00 2.145205 6 09-01-2016 05:00 0.475309 Today's Data: 1 10-01-2016 00:00 -0.886492 2 10-01-2016 01:00 -0.500995 3 10-01-2016 02:00 NaN 4 10-01-2016 03:00 NaN 5 10-01-2016 04:00 2.145205 6 10-01-2016 05:00 0.475309 Expected to fill today's data: 1 10-01-2016 00:00 -0.886492 2 10-01-2016 01:00 -0.500995 3 10-01-2016 02:00 5 4 10-01-2016 03:00 2.145205 5 10-01-2016 04:00 2.145205 6 10-01-2016 05:00 0.475309 Please suggest me some approach for the same. Thank you in advance I have tried using this post Fill values from one dataframe to another with matching IDs but not getting expected output

http://stackoverflow.com/comment/88284714
type: QuestionComment
has text: why u need a tab action to click on that element?
score: 0
comment on: http://stackoverflow.com/q/50637373
type: Comment

http://stackoverflow.com/q/50656716
possible better answer: http://stackoverflow.com/a/50657783
answer count: 2
has body: The document about super() found on the Python website says it returns a proxy object that delegates method calls to parent or sibling class. Information found at super considered super, how does super() work with multiple inheritance and super considered harmful explains that in fact the next method in the mro is used. My question is, what happens if super(object, self).some_method() is used? Since object typically appears at the end of a mro list, I guess the search will hit the end immediately with an exception. But in fact, it seems that the methods of the proxy itself were called, as shown by super(object, self).__repr__() showing the super object itself. I wonder whether the behavior of super() with object is not to delegate method at all. If this is the case, I wonder any reliable material ever mentions it and whether it applies to other Python implementations. class X(object): def __init__(self): # This shows [X, object]. print X.mro() # This shows a bunch of attributes that a super object can have. print dir(super(object, self)) # This shows something similar to &lt;super object at xxx&gt; print(object, self) # This failed with `super() takes at least one argument` try: super(object, self).__init__() except: pass # This shows something like &lt;super &lt;class 'object'&gt;, &lt;'X' object&gt;&gt;. print(super(object, self).__repr__()) # This shows the repr() of object, like &lt;'X' object at xxx&gt; print(super(X, self).__repr__()) if __name__ == '__main__': X()
favorite count: 0
tagged with: super
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50659467
type: Question
has answer: http://stackoverflow.com/a/50657783
downvote count: 0
has comment: http://stackoverflow.com/comment/88323652
accepted answer: http://stackoverflow.com/a/50659467
linked to: http://stackoverflow.com/q/3277367
score: 4
has title: The behaviour of 'super()' when type is 'object'?
upvote count: 4

http://stackoverflow.com/q/50685538
type: Question
has comment: http://stackoverflow.com/comment/88394608
tagged with: boost-python
score: 0
has comment: http://stackoverflow.com/comment/88434346
has comment: http://stackoverflow.com/comment/88394918
tagged with: downgrade
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88465159
has comment: http://stackoverflow.com/comment/88418392
tagged with: python
tagged with: c++
linked to: http://stackoverflow.com/q/8430332
has body: I have installed boost 1.65.1 and I want to either downgrade it to 1.63.1 or uninstall it and then rebuild it. boost getting started I don't know how to do that and also from which folder to execute which command...?
has title: downgrade boost 1.65.1 python to 1.63.1 or uninstall and rebuild
tagged with: boost
has comment: http://stackoverflow.com/comment/88458492

http://stackoverflow.com/q/50553585
has body: I am trying to use the re.UNICODE flag to match a string potentially containing unicode characters, but it doesn't seem to be working. E.g.: Python 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import re &gt;&gt;&gt; r = re.compile(ur"(\w+)", re.UNICODE) &gt;&gt;&gt; r.findall(u"test test test", re.UNICODE) [] It works if I do not specify the unicode flag, but then obviously it will not work with unicode strings. What do I need to do to get this working?
has answer: http://stackoverflow.com/a/50553682
downvote count: 1
type: Question
score: 3
has comment: http://stackoverflow.com/comment/88117934
accepted answer: http://stackoverflow.com/a/50553682
has comment: http://stackoverflow.com/comment/88117989
upvote count: 4
tagged with: python-2.7
answer count: 1
tagged with: unicode
has comment: http://stackoverflow.com/comment/88117879
favorite count: 0
has title: How do I use re.UNICODE in python 2.7?
tagged with: python
has comment: http://stackoverflow.com/comment/88118047
tagged with: regex
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88118008

http://stackoverflow.com/comment/88202960
comment on: http://stackoverflow.com/q/50596608
score: 0
has text: @Ramesh Maharjan No serial number is different
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88348634
type: Comment
type: QuestionComment
has text: See also [Python Names and Values](https://nedbatchelder.com/text/names1.html) by @NedBatchelder.
comment on: http://stackoverflow.com/q/50640122
score: 1

http://stackoverflow.com/comment/88321429
has text: ok so if i understood , when i automate this by `driver.find_element_by_css_selector("._5f5mN.-fzfL.KUBKM.yZn4P").click()` it click the last one for first. But i don't know how to put this code in my python file
comment on: http://stackoverflow.com/a/50651396
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/a/50687964
answers question: http://stackoverflow.com/q/50687882
downvote count: 0
has comment: http://stackoverflow.com/comment/88386410
type: Answer
has body: You could use a little function converting the values to numbers: import pandas as pd, numpy as np df = pd.DataFrame({ 'A': [1.0, 'abc', -1.11], 'B': ['abc', 1.0, 'abc'], 'C': [1.0, 'abc', 'abc']}) def change(value): try: v = float(value) if v &lt; -1: value = np.nan except ValueError: pass return value df['A'] = df['A'].apply(change) print(df) This yields A B C 0 1 abc 1 1 abc 1 abc 2 NaN abc abc
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88394586
has comment: http://stackoverflow.com/comment/88386660
has comment: http://stackoverflow.com/comment/88397455

http://stackoverflow.com/q/50644572
has body: I have a few spatial data points (x,y,z) with errors on all coordinates and I would like to fit a straight line to them. I struggle at finding the chi^2 to minimise. I found the 2D case here (numerical recipies).see also this pic for just the formula of the chi^2 but I have troubles working it out in 3D - does anyone have experience/an idea? Are there any python libraries that can deal with problems like this?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88302454
tagged with: data-fitting
linked to: http://stackoverflow.com/q/2298390
tagged with: line
has title: Fitting a straight line in 3D with errors on x,y,z
type: Question
has comment: http://stackoverflow.com/comment/88303017
linked to: http://stackoverflow.com/q/14854339
score: 0
has comment: http://stackoverflow.com/comment/88644853
has answer: http://stackoverflow.com/a/50815105
tagged with: least-squares
answer count: 1

http://stackoverflow.com/comment/88143223
comment on: http://stackoverflow.com/a/50566577
type: Comment
score: 0
type: AnswerComment
has text: I'm going to look into it. From what you wrote, you seem to have perfectly understood the issue. I just need to understand the code now :) Thanks.

http://stackoverflow.com/q/50609974
has comment: http://stackoverflow.com/comment/88229846
has body: I am trying to access an Oracle database table using a python script. I have written following code: import cx_Oracle con = cx_Oracle.connect("system/infy123@127.0.0.1/XE") cur = con.cursor() cur.execute(" SELECT * FROM SUPPLIER") for row in cursor.fetchall(): print(row) and the output is: Traceback (most recent call last): File "C:/Users/ADMIN/AppData/Local/Programs/Python/Python36- 32/my_file.py", line 6, in &lt;module&gt; cur.execute(" SELECT * FROM SUPPLIER") cx_Oracle.DatabaseError: ORA-00942: table or view does not exist Can anyone tell me how to solve this error?
score: 4
has comment: http://stackoverflow.com/comment/88230082
answer count: 1
has answer: http://stackoverflow.com/a/50613900
favorite count: 0
type: UnansweredQuestion
tagged with: oracle-database
has comment: http://stackoverflow.com/comment/88230440
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/88250437
downvote count: 0
tagged with: oracle11g
has title: cx_Oracle.DatabaseError: ORA-00942: table or view does not exist
type: Question
has comment: http://stackoverflow.com/comment/88229685

http://stackoverflow.com/q/50697859
has body: How to access line format object for series in chart based on XL_CHART_TYPE.LINE? chart_data = ChartData() vec2 = [ float(i.value) for i in xl_sheet.col(1)] chart_data.categories = [ datetime.datetime.fromordinal(int(693594+i.value )) for i in xl_sheet.col(0)] uu=chart_data.add_series('Model1', tuple(vec2)) I didn't access to format of series line by uu.format.line.color.rgb = RGBColor((100,100,100))
accepted answer: http://stackoverflow.com/a/50705045
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
has title: python pptx How to change line format in chart based on XL_CHART_TYPE.LINE
type: Question
tagged with: python-pptx
tagged with: python
has answer: http://stackoverflow.com/a/50705045
answer count: 1
upvote count: 1

http://stackoverflow.com/q/50689367
has answer: http://stackoverflow.com/a/50705666
score: 0
has title: Tensorflow placeholder for tf.Variable
answer count: 1
type: UnansweredQuestion
tagged with: python
tagged with: tensorflow
type: Question
has body: The code below throws a "no gradients" error. self.x1 = tf.placeholder(tf.float64) self.x2 = tf.placeholder(tf.float64) self.x3 = tf.placeholder(tf.float64) self.cos1_denom = tf.norm(self.x1, axis=0) * tf.norm(self.x2, axis=0) self.cos1 = tf.matmul(self.x1, self.x2, transpose_b=True) / self.cos1_denom self.cos2_denom = tf.norm(self.x1, axis=0) * tf.norm(self.x2, axis=0) self.cos2 = tf.matmul(self.x1, self.x3, transpose_b=True) / self.cos2_denom self.loss = tf.reduce_mean(self.cos2) - tf.reduce_mean(self.cos1) self.optimizer = tf.train.AdamOptimizer(learning_rate=self.eta).minimize(self.loss) I believe it's because my loss function depends on placeholders instead of Variables, but in my training function I pass in a Variable value for the placeholder. Is there a way to create a placeholder for a Variable?

http://stackoverflow.com/comment/88279525
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50634104
type: Comment
has text: @J.Lin I've edited the answer to show how to do this with your toy example. If it's not obvious how to adapt that to your real example, edit your question to provide a slightly more complex [mcve] that shows why it's not obvious, and I can edit my answer.

http://stackoverflow.com/q/50558388
has title: While installing BeautifulSoup in Python on my Mac, I am facing this issue. I have already updated the setup tools still the issue persists
type: Question
score: 0
has answer: http://stackoverflow.com/a/50573274
answer count: 1
tagged with: python
linked to: http://stackoverflow.com/q/48884253
type: UnansweredQuestion
has body: Gaurangs-MacBook-Air:Python_Practice gaurang$ pip3 install BeautifulSoup Collecting BeautifulSoup Using cached https://files.pythonhosted.org/packages/1e/ee/295988deca1a5a7accd783d0dfe14524867e31abb05b6c0eeceee49c759d/BeautifulSoup-3.2.1.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/private/var/folders/zc/0dyk58m96f7f4h_5dycqsbw80000gn/T/pip-install-iwn33wod/BeautifulSoup/setup.py", line 22 print "Unit tests have failed!" ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Unit tests have failed!")? ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/zc/0dyk58m96f7f4h_5dycqsbw80000gn/T/pip-install-iwn33wod/BeautifulSoup/

http://stackoverflow.com/a/50655765
answers question: http://stackoverflow.com/q/50655446
has body: Looks like a perfect job for Negative Lookbehind and Negative Lookahead: re.sub(r'''(?&lt;![^\s]) [+-]?[.,;]? (\d+[.,;']?)+% (?![^\s.,;!?'"])''', '@percent@', string, flags=re.VERBOSE) (?&lt;![^\s]) means "no space immediately before the current position is allowed" (add more forbidden characters if you need). (?![^\s.,;!?'"]) means "no space, period, etc. immediately after the current position are allowed". Demo: https://regex101.com/r/khV7MZ/1.
has comment: http://stackoverflow.com/comment/88336696
accepted answer of: http://stackoverflow.com/q/50655446
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88337106
has comment: http://stackoverflow.com/comment/88346623
type: Answer
has comment: http://stackoverflow.com/comment/88369515

http://stackoverflow.com/comment/88397601
comment on: http://stackoverflow.com/q/50675943
has text: Yes I do get the key error since the dict is empty
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88354570
score: 0
type: Comment
type: QuestionComment
has text: Yes, the mask will later be multiplied with the input and more layers will follow. I am sorry I was that unclear, I'll try to improve it tomorrow. Thanks again.
comment on: http://stackoverflow.com/q/50669431

recaptcha
tag name: recaptcha
tags question: http://stackoverflow.com/q/50685323
type: Tag

axes
tag name: axes
type: Tag
tags question: http://stackoverflow.com/q/50642641

http://stackoverflow.com/a/50710316
type: Answer
has body: Try adding to Apache configuration: WSGIApplicationGroup %{GLOBAL} See: http://modwsgi.readthedocs.io/en/develop/user-guides/application-issues.html#python-simplified-gil-state-api
answers question: http://stackoverflow.com/q/50694576
has comment: http://stackoverflow.com/comment/88432480
score: 0
has comment: http://stackoverflow.com/comment/88432772

http://stackoverflow.com/comment/88251589
comment on: http://stackoverflow.com/q/50618925
has text: @miracle173, Thanks for your responses, I have made some edits to the question, Hope this time I have made it correct, I want to know why the 1st set is not running.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50687489
has answer: http://stackoverflow.com/a/50687541
has comment: http://stackoverflow.com/comment/88385435
tagged with: python
favorite count: 0
tagged with: include
has comment: http://stackoverflow.com/comment/88385918
upvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50687541
tagged with: http://stackoverflow.com/tag/c
type: Question
answer count: 1
downvote count: 0
tagged with: header
score: 1
has title: python-dev installed and Python.h in place, but error on include
has body: I work on a u 18.04 and a third party tool (pymesh) that I use needs to include Python.h I installed python-dev, python3-dev, libpython-dev and libpython3-dev. Python.h is found in the folders: /usr/include/Python/, /usr/include/Python3.6m/ and /usr/include/Python3.6/. Still when I try to compile a minimal C-program: #include&lt;Python.h&gt; int main(){} I get the error: $ gcc test.c test.c:1:9: fatal error: Python.h: No such file or directory #include&lt;Python.h&gt; ^~~~~~~~~~ compilation terminated. I can fix this by making symbolic links to every header in one of those directories in, e.g., /usr/local/include/ or by specifying the path in the #include statement, but is that the correct way of doing it?

http://stackoverflow.com/a/50600020
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50599934
has body: You can use: df[df.EntityName.str[0].str.isupper()]
downvote count: 0

http://stackoverflow.com/q/50635835
has body: I'm trying to achieve interprocess communication with socket. I have this code which acts as a socket server. When a message is received, the server broadcasts all the message to the other conntected clients. from socket import AF_INET, gethostname, socket, SOCK_STREAM import _thread as thread clients = [] HOST = gethostname() PORT = 33000 BUFFER_SIZE = 1024 ADDR = (HOST, PORT) s = socket(AF_INET, SOCK_STREAM) s.bind(ADDR) def accept_client(): while True: client, _ = s.accept() clients.append(client) print("Client accepted.") thread.start_new_thread(handle_client, (client, )) def handle_client(client): while True: message = client.recv(BUFFER_SIZE) print("Incoming message: {}".format(message.decode('utf-8'))) broadcast(message) def broadcast(message): print("Broadcasting...") for c in clients: print("Broadcasting to {}".format(c)) c.send(message) if __name__ == '__main__': s.listen() print("Listening...") thread.start_new_thread(accept_client, ()) try: while True: pass except KeyboardInterrupt: print("Exited.") exit(0) And here is a class for my client. from socket import AF_INET, gethostname, socket, SOCK_STREAM import _thread as thread class SocketClient: buffer_size = 1024 def __init__(self, host=gethostname(), port=33000): self.host = host self.port = port self.buffer_size = 1024 self.s = socket(AF_INET, SOCK_STREAM) self.s.connect((self.host, self.port)) def bind_callback(self, callback, args=()): thread.start_new_thread(self.receive, (callback, args)) def receive(self, callback, args): while True: try: msg = self.s.recv(self.buffer_size).decode('utf-8') callback(msg, *args) except OSError as err: self.close() raise err except NameError: raise err def send(self, msg): try: self.s.send(msg.encode('utf-8')) except: self.close() def close(self): self.send('{clientClose}') self.s.close() In other script which I've create the object ofSocketClient, there is an infinite amount of incoming socket after the script terminates (by Ctrl+D in Python). The server script (wh…
accepted answer: http://stackoverflow.com/a/50635991
type: Question
score: 0
answer count: 1
has title: Python socket still keeps incoming even after client terminates
tagged with: sockets
tagged with: python
has answer: http://stackoverflow.com/a/50635991
type: AnsweredQuestion

http://stackoverflow.com/comment/88307245
type: Comment
type: QuestionComment
score: 1
has text: I don't think `to_timestamp` works with microseconds like that. Take out the `.SSSSSS` and it should work or write a UDF to achieve more granularity.
comment on: http://stackoverflow.com/q/50648154

http://stackoverflow.com/comment/88347043
score: 0
has text: Section III, step 6 explains how a smaller matrix of size M x M can be used instead.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50667849

http://stackoverflow.com/q/50571153
accepted answer: http://stackoverflow.com/a/50571175
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/95749330
type: AnsweredQuestion
upvote count: 2
type: Question
score: -2
has answer: http://stackoverflow.com/a/50571175
downvote count: 4
has title: Why does re.match(...) == True print False?
answer count: 1
has comment: http://stackoverflow.com/comment/88152126
has body: import re print(re.match(r'[a-zA-Z0-9]{6,}', '4fdg5Fj3') == True) it is printing False but the string given is fullfilling all the conditions of the regular expression.
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/88348534
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50669160
type: AnswerComment
has text: @Robertas in this way do you need data?, or it need to remain the same list of lists ?

http://stackoverflow.com/a/50629566
has comment: http://stackoverflow.com/comment/88269335
type: Answer
answers question: http://stackoverflow.com/q/50629480
upvote count: 1
downvote count: 1
score: 0
has body: You can use python's regex module import re a = """ &lt;span id="publisher" itemprop="Publisher" data-source="LE MONDE"&gt;Le Monde&lt;/span&gt; | &lt;time datetime="2018-05-30T10:44:42+02:00" itemprop="datePublished"&gt;30.05.2018 &amp;agrave; 10h44&lt;/time&gt; • Mis à jour le &lt;time datetime="2018-05-31T13:54:38+02:00" itemprop="dateModified"&gt;31.05.2018 &amp;agrave; 13h54&lt;/time&gt; | &lt;span class="signature_article"&gt; Par &lt;span itemprop="author" class="auteur txt2_120"&gt; &lt;a class="auteur" target="_blank" href="/journaliste/anne-sophie-faivre-le-ca dre/"&gt;Anne-Sophie Faivre Le Cadre&lt;/a&gt; &lt;/span&gt; &lt;/span&gt; &lt;/p&gt; """ match=re.findall(r'(\d{2,2}.\d{2,2}.\d{4,4})',a) print match ['30.05.2018', '31.05.2018'] match will contains an array of all matched string
has comment: http://stackoverflow.com/comment/88269410

http://stackoverflow.com/comment/88245120
score: 0
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/172139/discussion-between-user1411837-and-huwenchao).
comment on: http://stackoverflow.com/a/50600551
type: AnswerComment

http://stackoverflow.com/a/72655561
score: 0
type: Answer
has body: I had excel with many sheets. I wanted only those sheets whose state is visible. If you do not know about that its fine. But if you want to read your sheet names from excel then you can use this code. it took me average 3 sec time to read near about 20 sheet names. It takes quite a few attempts to get this. file_name = r'C:\Users\xyz.xlsx' File_sheet_list = [] workbookObj = pd.ExcelFile(file_name) LenOfWorkBook = len(workbookObj.book.worksheets) idx = 0 for idx in range(0, LenOfWorkBook ): if workbookObj.book.worksheets[idx].sheet_state == "visible": File_sheet_list.append(workbookObj.book.worksheets[idx].title)
answers question: http://stackoverflow.com/q/50695778

http://stackoverflow.com/q/50629620
has comment: http://stackoverflow.com/comment/88269350
has answer: http://stackoverflow.com/a/50629759
accepted answer: http://stackoverflow.com/a/50629759
has body: Beginner to machine learning... I know CNN model indicates value "1" for the class to which image belongs, otherwise "0". But the output I'm getting for one of my model is little weird. Output-: 1.00000000e+00 , 1.02304026e-20 , 0.00000000e+00 I observed the value of class 1 is higher as compare to other classes because the image I'm testing actually belongs to that class. But i really cant understand what that output implies and why it is not simply in 0 or 1.
has comment: http://stackoverflow.com/comment/88269295
score: 0
answer count: 1
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/88269363
has title: What does output of Convolutional neural network implies
tagged with: python
type: AnsweredQuestion
tagged with: conv-neural-network
upvote count: 1
downvote count: 1
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/88278910
type: Comment
has text: I'm going to flag this as not an answer as it does not attempt to answer the question posed by OP.
score: 1
comment on: http://stackoverflow.com/a/50634395
type: AnswerComment

http://stackoverflow.com/comment/88276868
has text: I think I could understand your answer,I just conclude this code "import pymc as pm print(pm.Uniform("stds",0,100).value)" each time pritnted value is different. I
comment on: http://stackoverflow.com/a/50618198
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50542371
has comment: http://stackoverflow.com/comment/88095997
tagged with: python
has body: I'm trying to add 2 layers in my model with different weights. I want to update these weights as the training goes on. Example: l1 = l1*(1-a) l2 = l2*(a) l3 = keras.layers.Add()([l1, l2]) Is there a way I can update the value of 'a' linearly with each epoch?
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/88097344
has title: change addition weight of 2 layers in a model while training
tagged with: keras
score: 0
has answer: http://stackoverflow.com/a/50544184
accepted answer: http://stackoverflow.com/a/50544184
answer count: 1

http://stackoverflow.com/comment/88393792
has text: I believe Cormac is asking about maintaining game state during execution, rather that storing such state in the file system.
comment on: http://stackoverflow.com/a/50689384
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88303571
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50645807
has text: Should I use pip install Django or pip3 install Django?

http://stackoverflow.com/comment/88372875
comment on: http://stackoverflow.com/a/50674020
has text: Yup, that's basically it. I didn't need a print statement, but a comprehension inside all() works.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50546737
has answer: http://stackoverflow.com/a/50546857
downvote count: 1
accepted answer: http://stackoverflow.com/a/50546857
type: Question
has title: Condition based in strings contained in groups
has comment: http://stackoverflow.com/comment/88104322
has answer: http://stackoverflow.com/a/50546922
score: 0
possible better answer: http://stackoverflow.com/a/50546874
answer count: 3
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/50546874
favorite count: 0
upvote count: 1
tagged with: python
has body: A B C 0 2002-01-12 Sarah 39 1 2002-01-12 John 17 2 2002-01-12 Susan 30 3 2002-01-15 Danny 12 4 2002-01-15 Peter 25 5 2002-01-15 John 25 6 2002-01-20 John 16 7 2002-01-20 Hung 10 8 2002-02-20 John 20 9 2002-02-20 Susan 40 10 2002-02-24 Rebel 40 11 2002-02-24 Susan 15 12 2002-02-24 Mark 38 13 2002-02-24 Susan 30 I want to select full A groups that contain John and Susan. Output should be: A B C 0 2002-01-12 Sarah 39 1 2002-01-12 John 17 2 2002-01-12 Susan 30 6 2002-01-20 John 16 7 2002-01-20 Hung 10 8 2002-02-20 John 20 9 2002-02-20 Susan 40 I've tried: df.groupby('A').apply(lambda x: ((df.B == x.John) &amp; (df.B == x.Susan)))
type: AnsweredQuestion

http://stackoverflow.com/comment/88311882
comment on: http://stackoverflow.com/a/50650390
type: Comment
has text: I have a hunch that small integer powers are special cased at least on linux, indeed, of `a*a, a**2, math.exp(2*math.log(a))` the first two seem to be equal all the time, while the third often deviates.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88395109
type: AnswerComment
comment on: http://stackoverflow.com/a/50692578
type: Comment
has text: @coldspeed - Thanks.
score: 0

http://stackoverflow.com/comment/88253876
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50620831
has text: Looks like you have a windows file, try `encoding="utf-8-sig"` so that python knows about the BOM

http://stackoverflow.com/comment/88335397
score: 0
has text: What do you want the result to look like? Does `End_Station` have values other than `NaN`, if so how are they combined with `Start_Station` values?
type: Comment
comment on: http://stackoverflow.com/q/50662613
type: QuestionComment

http://stackoverflow.com/comment/88315792
type: Comment
type: QuestionComment
has text: And seriously guys, stackexchange didn't tell me my question was "off-topic", I was just referring to this yellow box: https://ibb.co/b6gcYJ But I believe the fear was warranted.
score: 0
comment on: http://stackoverflow.com/q/50652332

http://stackoverflow.com/q/50663243
tagged with: python
type: AnsweredQuestion
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/50692630
tagged with: data-manipulation
score: 0
answer count: 1
has title: Logical operation on the contents of a tensor
accepted answer: http://stackoverflow.com/a/50692630
tagged with: tensor
has body: I have a list named 'datastate' of shape (?,10) which is getting filled with the results of 10 batch samples in tensorflow (all tensors). In other words, with a batch size of 256, this will be populated with 10 different tensors of size 256. in pseudocode below .... datastate = {} for sample in range(num_samples): datastate[sample] = batch_results What I would like to do next is define a variable like 'datastate_change', which would determine if the i-th record of batch_results was changed versus the (i-1)th record of batch_results. This might look something like the following if Pandas style syntax worked ... but I'm not clear on how to do this inside of tf during the sess.run. for sample in range(num_samples): datastate[sample] = batch_results datastate_change[sample] = batch_results - batch_results.shift(1) To be a bit more concrete, if a single instance of batch_results are [1,1,1,0,1] I would like to have datastate[1] = [1,1,1,0,1] and datastate_change[1] = [1,0,0,-1,1]

http://stackoverflow.com/a/72281022
upvote count: 7
has comment: http://stackoverflow.com/comment/130749760
type: Answer
answers question: http://stackoverflow.com/q/50620954
downvote count: 0
has body: While developing SQLAlchemy application I run into the same issue. I've added the -X dev (https://docs.python.org/3/using/cmdline.html#miscellaneous-options) Interpreter options in PyCharm Run/Debug Configurations which resulted in new exceptions instead of crashing with -1073741819 (0xc0000005). These exceptions did not appear before.
score: 7

http://stackoverflow.com/q/50635941
has comment: http://stackoverflow.com/comment/88281833
tagged with: docker
has body: I would like to pipe a file using the cat command into a Docker container along with arguments related to running the Python file. The command to run this Python file is going to be mentioned in the Dockerfile as RUN ["python", "myfile.py"]. After building the Docker image using Docker build -t test ., I shall call the command cat file.txt | docker run -i test --param1 value. I understand how arguments are accepted in the Python file using the argparse module and here is what I have: parser = argparse.ArgumentParser() parser.add_argument("param1") args = parser.parse_args() value = args.param1 My question is: how do I configure the Dockerfile to route the parameter passed from the command line (param1) into the Python file's argument parser? My findings about doing this have just shown me how to write the cat .. | docker run ... command.
score: 0
tagged with: argparse
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88281941
answer count: 0
has comment: http://stackoverflow.com/comment/88281974
has title: Pipe to Docker stdin with arguments picked up by Python argparse
tagged with: dockerfile
type: Question
has comment: http://stackoverflow.com/comment/88281855

azure
tags question: http://stackoverflow.com/q/50672566
tags question: http://stackoverflow.com/q/50574010
type: Tag
tags question: http://stackoverflow.com/q/50607467
tags question: http://stackoverflow.com/q/50593199
tags question: http://stackoverflow.com/q/50651390
tags question: http://stackoverflow.com/q/50581452
tag name: azure

http://stackoverflow.com/comment/88324505
comment on: http://stackoverflow.com/a/50656862
type: Comment
has text: But this is a parsing task. Once compiled, nothing in the `bytes`, `str` or `unicode` object holds information about how the literal was shaped. For instance, `dis.dis(compile('"hello" " " "world"', '', 'exec'))` shows only one constant string, not three.
score: 3
type: AnswerComment

http://stackoverflow.com/comment/88143458
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50566728
has text: look at link and then use a `len()` to get the number of items
score: 0

http://stackoverflow.com/a/50598480
score: 0
has body: Make a list of 4 consecutive elements and filter those with none in it. Then party... with open("input_file","r") as in_file: lines = in_file.read().split("\n") consecutive_lines_4 = [lines[i:i+4] for i in range(0,len(lines)-3),2] result = [i for i in consecutive_lines_4 if 'none' not in i] print(result)
type: Answer
answers question: http://stackoverflow.com/q/50597860

http://stackoverflow.com/a/50626727
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50621419
has body: a good way to implement this would be to override the DUPEFILTER_CLASS to check your database before doing the actual requests. Scrapy uses a dupefilter class to avoid getting the same request twice, but it only works for running spiders.
answers question: http://stackoverflow.com/q/50621419
has comment: http://stackoverflow.com/comment/88285229

http://stackoverflow.com/comment/88194958
comment on: http://stackoverflow.com/a/50591644
score: 0
type: AnswerComment
has text: you're a master
type: Comment

http://stackoverflow.com/a/50591765
answers question: http://stackoverflow.com/q/50591699
type: Answer
has body: You could use this list comprehension which filters the elements that don't exist in B (they aren't in any one of B's elements, and all B's elements aren't in them): lista = ['abc.txt', '123.txt', 'apple.jpg'] listb = ['ab', '123'] listc = [a for a in lista if all(a not in b and b not in a for b in listb)] print(listc) # =&gt; ['apple.jpg']
score: 0

http://stackoverflow.com/comment/88205933
comment on: http://stackoverflow.com/q/50598003
has text: `margin-left`, `margin-right` are negative numbers. Could that be the reason?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88207032
comment on: http://stackoverflow.com/q/50582105
has text: @GPT14 if you'll post you comment as an answer I'll accept it..
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/74546042
score: 0
type: Answer
has body: To set the access scopes from the python client libraries with the same effect as that radio button in the GUI: instance_client = compute_v1.InstancesClient() instance.service_accounts = [ compute_v1.ServiceAccount( email="$$$$$$$-compute@developer.gserviceaccount.com", scopes=[ "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/cloud-platform", ], ) ] With a tutorial for creating instances from python here
answers question: http://stackoverflow.com/q/50646403

flask-cache
type: Tag
tags question: http://stackoverflow.com/q/50624908
tag name: flask-cache

http://stackoverflow.com/comment/88200746
comment on: http://stackoverflow.com/q/50595210
score: 0
type: Comment
has text: https://developer.microsoft.com/en-us/windows/downloads/sdk-archive
type: QuestionComment

http://stackoverflow.com/q/50592912
has comment: http://stackoverflow.com/comment/88197189
has answer: http://stackoverflow.com/a/50593228
tagged with: python
score: 8
has answer: http://stackoverflow.com/a/50593024
has comment: http://stackoverflow.com/comment/88195383
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50593016
has comment: http://stackoverflow.com/comment/88196867
has title: Python representation for a set of non-overlapping integer ranges
accepted answer: http://stackoverflow.com/a/50593016
downvote count: 0
upvote count: 8
type: Question
answer count: 3
has body: I'd like to represent a set of integer ranges using Python where the set could be modified dynamically and tested for inclusion. Specifically I want to apply this to address ranges or line numbers in a file. I could define the range of addresses I cared about to include: 200 - 400 450 - 470 700 - 900 Then I want to be able to add a potentially overlapping range to the set such that when I add 460 - 490 the set becomes: 200 - 400 450 - 490 700 - 900 But then be able to delete from the set where I could exclude the range 300 - 350 and the set becomes: 200 - 300 350 - 400 450 - 490 700 - 900 Finally, I want to be able to iterate over all integers included in the set, or test whether the set contains a particular value. I'm wondering what the best way to do this is (particularly if there's something built into Python).
possible better answer: http://stackoverflow.com/a/50593024
favorite count: 0

http://stackoverflow.com/a/50668548
score: 2
has body: You can use numpy.where and numpy.isnan to locate the indices where values are not nan, then use np.random.choice to pick one index that is not nan: array = np.array(1,np.nan,2,np.nan,3,4) not_nan_idx = np.random.choice(np.where(~np.isnan(array))[1]) not_nan_idx # 2 array[0, not_nan_idx] = np.nan array # array(1., nan, nan, nan, 3., 4.)
answers question: http://stackoverflow.com/q/50668495
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50668495
type: AcceptedAnswer
upvote count: 2
type: Answer

http://stackoverflow.com/comment/88341915
comment on: http://stackoverflow.com/a/50665603
type: AnswerComment
type: Comment
has text: @RishuA - Give me some time, do you need colspans for first row?
score: 1

http://stackoverflow.com/q/50554272
has comment: http://stackoverflow.com/comment/88119454
has answer: http://stackoverflow.com/a/50554612
tagged with: arrays
downvote count: 0
answer count: 6
has answer: http://stackoverflow.com/a/64904670
has title: Randomly shuffle items in each row of numpy array
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88119304
has answer: http://stackoverflow.com/a/50554557
has answer: http://stackoverflow.com/a/50554923
score: 13
tagged with: python
has body: I have a numpy array like the following: Xtrain = np.array([[1, 2, 3], [4, 5, 6], [1, 7, 3]]) I want to shuffle the items of each row separately, but do not want the shuffle to be the same for each row (as in several examples just shuffle column order). For example, I want an output like the following: output = np.array([[3, 2, 1], [4, 6, 5], [7, 3, 1]]) How can I randomly shuffle each of the rows randomly in an efficient way? My actual np array is over 100000 rows and 1000 columns.
linked to: http://stackoverflow.com/q/50415972
upvote count: 13
has answer: http://stackoverflow.com/a/50554614
has answer: http://stackoverflow.com/a/50554447
has comment: http://stackoverflow.com/comment/88119340
type: Question
tagged with: numpy

http://stackoverflow.com/comment/88205349
has text: @Abhinay Same result `from_file` as well
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50598003

http://stackoverflow.com/comment/88114963
type: Comment
has text: It works when I copy all my data into a new string, I think something wrong of my output, thanks.
comment on: http://stackoverflow.com/a/50551974
score: 0
type: AnswerComment

http://stackoverflow.com/a/50689831
type: Answer
has body: Try the below: from pandas.compat import StringIO df_string= pd.read_csv(StringIO(ss), sep=';') Or: df_string=pd.DataFrame(pd.Series(ss))
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50689763
upvote count: 2

http://stackoverflow.com/comment/88315755
comment on: http://stackoverflow.com/q/50652463
has text: It can not *Join on level between two MultiIndex objects is ambiguous *
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88127804
score: 0
has text: I am having the same dataset as other person and same code but I m getting error of expecting 2D array
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50558546

http://stackoverflow.com/comment/88419173
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50691641
has text: The outer loop (“for i, x in enumerate”) loops through the elements of the first column. For each element (“i, x”) you then check the entire second column if that appears. All indices where that element from col1 appears in col2 are stored in matches. k is the first of thise indices. Update the value of col1 at i, of col2 at k!
type: AnswerComment

http://stackoverflow.com/q/50615262
has answer: http://stackoverflow.com/a/50615446
type: AnsweredQuestion
score: 7
tagged with: hamming-distance
upvote count: 7
type: Question
has answer: http://stackoverflow.com/a/50615355
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/50615491
has title: What is the fastest way to XOR A LOT of binary arrays in python?
accepted answer: http://stackoverflow.com/a/50615355
answer count: 3
has body: I am tasked with calculating hamming distances between 1D binary arrays in two groups - a group of 3000 arrays and a group of 10000 arrays, and every array is 100 items(bits) long. So thats 3000x10000 HD calculations on 100 bit long objects.And all that must be done in at most a dozen minutes Here's the best of what I came up with #X - 3000 by 100 bool np.array #Y - 10000 by 100 bool np.array hd = [] i=1 for x in X: print("object nr " + str(i) + "/" + str(len(X))) arr = np.array([x] * len(Y)) C = Y^arr # just xor this array by all the arrays in the other group simultainously hd.append([sum(c) for c in C]) #add up all the bits to get the hamming distance i+=1 return np.array(hd) And it's still going to take 1-1.5 hours for it to finish. How do I go about making this faster?
favorite count: 0
has comment: http://stackoverflow.com/comment/88240466
tagged with: python
possible better answer: http://stackoverflow.com/a/50615446

http://stackoverflow.com/q/50618116
has comment: http://stackoverflow.com/comment/88246211
accepted answer: http://stackoverflow.com/a/50618228
downvote count: 0
has title: regex for finding file paths
possible better answer: http://stackoverflow.com/a/50618329
has answer: http://stackoverflow.com/a/50618417
favorite count: 0
has comment: http://stackoverflow.com/comment/88246022
score: 6
has answer: http://stackoverflow.com/a/50618228
tagged with: python
has answer: http://stackoverflow.com/a/50618329
tagged with: regex
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88246133
type: Question
upvote count: 6
has body: I used this regex(\/.*\.[\w:]+) to find all file paths and directories. But in a line like this "file path /log/file.txt some lines /log/var/file2.txt" which contains two paths in the same line , it does not select the paths individually , rather , it selects the whole line. How to solve this?
answer count: 3

http://stackoverflow.com/comment/88098369
type: Comment
comment on: http://stackoverflow.com/a/50543626
score: 0
type: AnswerComment
has text: I'm not sure this will work,but it worked for a similar case to me :)

http://stackoverflow.com/a/50600853
score: 5
type: Answer
has body: This for x in list(itertools.permutations(list_Abecedario, i)): does store all the possible permutations (and there might be many) in memory, so yes your computer is "keeping the data" somewhere. FWIW making a list of those permutations only to iterate over this list is totally defeats the whole point of itertools, which is to use lazy iteration (hence saving memory). So the solution here is simple: just iterate over itertools.permutations: for x in itertools.permutations(list_Abecedario, i): EDIT: note that given the huge number of permutations, even if you don't hit another memory limit, your program will take a very long time to finish.
has comment: http://stackoverflow.com/comment/88211491
has comment: http://stackoverflow.com/comment/88211693
upvote count: 5
has comment: http://stackoverflow.com/comment/88211363
accepted answer of: http://stackoverflow.com/q/50600651
answers question: http://stackoverflow.com/q/50600651
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88169688
type: QuestionComment
comment on: http://stackoverflow.com/q/50574339
has text: can you add the data in order to reproduce the probelm? Also, what's your sklearn version ?
score: 0
type: Comment

http://stackoverflow.com/comment/88226288
type: QuestionComment
comment on: http://stackoverflow.com/q/50607748
score: 0
type: Comment
has text: /usr/bin/python2.7: ELF 64-bit LSB shared object Thank you, I'll report this bug.

http://stackoverflow.com/comment/88136227
comment on: http://stackoverflow.com/q/50562878
type: QuestionComment
has text: When you use the `%` based string formatting, it takes a *sequence* of arguments. You passed it an empty tuple, which is being interpreted as the sequence of arguments. Since it is empty, and your format specification specifies a single argument, it throws an error. You probably shouldn't be using `%` based string formatting anyway, and instead, use `.format` or f-strings.
score: 0
type: Comment

http://stackoverflow.com/comment/88188429
type: QuestionComment
comment on: http://stackoverflow.com/q/50587297
score: 0
has text: This can't be ok, since in your question you say that the resulting shape is `(93615200,)` There is no way that this is multiplicative of 58 and or 8020. There must be some irregular shapes in you data.
type: Comment

http://stackoverflow.com/comment/88292740
has text: Share your existing code you have written
score: 0
comment on: http://stackoverflow.com/q/50641033
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88370163
score: 1
has text: yeah, it works :) thank you a lot do you want to write the solution to get a lot of good points ?
type: Comment
comment on: http://stackoverflow.com/q/50679134
type: QuestionComment

http://stackoverflow.com/comment/88390989
comment on: http://stackoverflow.com/q/50690549
score: 0
has text: @ShadowRanger I would like to use binary search, as I have little experience with it. Although thanks for the suggestion!
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50568770
answers question: http://stackoverflow.com/q/50562869
score: 0
has body: I find a useful option in the API that is seed input_queue = tf.RandomShuffleQueue(capacity=50, min_after_dequeue=2, dtypes="int32", shapes=[()], seed=1234) label_queue = tf.RandomShuffleQueue(capacity=50, min_after_dequeue=2, dtypes="int32", shapes=[()], seed=1234) [array([4, 2, 4, 2, 2, 1, 2, 3, 4, 3], dtype=int32), array([4, 2, 4, 2, 2, 1, 2, 3, 4, 3], dtype=int32)]
type: Answer

http://stackoverflow.com/comment/88405318
type: AnswerComment
has text: What is your pandas version?
comment on: http://stackoverflow.com/a/50696442
type: Comment
score: 0

http://stackoverflow.com/comment/88312190
has text: This is JSON, better to use the builtin json packages to parse, than do it yourself with regex.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50650633
score: 0

http://stackoverflow.com/comment/100068412
has text: This worked for me just two points to add: Expand tree as Packages > script > lib > grammars and after changing python to python 3 restart atom to see changes taking effect.
comment on: http://stackoverflow.com/a/53507376
type: Comment
score: 1
type: AnswerComment

loops
tags question: http://stackoverflow.com/q/50654531
tags question: http://stackoverflow.com/q/50580779
tags question: http://stackoverflow.com/q/50565663
tags question: http://stackoverflow.com/q/50591233
tags question: http://stackoverflow.com/q/50657642
tags question: http://stackoverflow.com/q/50549536
tags question: http://stackoverflow.com/q/50659212
tags question: http://stackoverflow.com/q/50598269
tags question: http://stackoverflow.com/q/50685113
tags question: http://stackoverflow.com/q/50637444
tags question: http://stackoverflow.com/q/50587046
type: Tag
tags question: http://stackoverflow.com/q/50580548
tags question: http://stackoverflow.com/q/50661606
tags question: http://stackoverflow.com/q/50614366
tags question: http://stackoverflow.com/q/50584986
tags question: http://stackoverflow.com/q/50607759
tags question: http://stackoverflow.com/q/50634086
tags question: http://stackoverflow.com/q/50647383
tags question: http://stackoverflow.com/q/50695766
tags question: http://stackoverflow.com/q/50695748
tags question: http://stackoverflow.com/q/50546488
tag name: loops
tags question: http://stackoverflow.com/q/50632294
tags question: http://stackoverflow.com/q/50658809
tags question: http://stackoverflow.com/q/50624206
tags question: http://stackoverflow.com/q/50661910
tags question: http://stackoverflow.com/q/50657770
tags question: http://stackoverflow.com/q/50585210
tags question: http://stackoverflow.com/q/50567381
tags question: http://stackoverflow.com/q/50650133
tags question: http://stackoverflow.com/q/50659474
tags question: http://stackoverflow.com/q/50636404
tags question: http://stackoverflow.com/q/50620755
tags question: http://stackoverflow.com/q/50671083
tags question: http://stackoverflow.com/q/50694694
tags question: http://stackoverflow.com/q/50574241
tags question: http://stackoverflow.com/q/50577114
tags question: http://stackoverflow.com/q/50552803
tags question: http://stackoverflow.com/q/50621608
tags question: http://stackoverflow.com/q/50695038
tags question: http://stackoverflow.com/q/50639090
tags question: http://stackoverflow.com/q/50642307

http://stackoverflow.com/q/50632785
has comment: http://stackoverflow.com/comment/88275981
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/88276238
upvote count: 0
has comment: http://stackoverflow.com/comment/88276625
has answer: http://stackoverflow.com/a/50632814
answer count: 1
has comment: http://stackoverflow.com/comment/88275928
favorite count: 0
has title: How to insert equations into python script from txt file and generate another file?
has comment: http://stackoverflow.com/comment/88275884
has comment: http://stackoverflow.com/comment/88276294
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/88276981
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/14257373
downvote count: 1
type: Question
duplicate of: http://stackoverflow.com/q/14257373
has comment: http://stackoverflow.com/comment/88277911
has body: I'm asking this question again because I have not gathered a clear answer for my question. I have a set of equations: ref_energy = (K-(C/2)comp(a)) + C/2 form_E2 = relaxed_E_per_atom - ref_energy(comp_x) I need to have a python script use these two equations using the values in the txt file to generate another x and y columns of values that will plot those values. This is the first few lines of my txt file. the config is the name of the structure associated with four values comp(a),form_E,comp_x,relaxed_E_per_atom 0,0,0,-8.15382173 1,0,0.33333333,-5.25358563 0.5,0.18614484,0.2,-6.33922213 0.5,-0.69658919,0.2,-6.69231575 0.5,-0.70549249,0.2,-6.69587707 Below is my script but I keep getting errors such as Traceback (most recent call last): File "attempt_#2.py", line 80, in &lt;module&gt; x.append(float(row[0])) ValueError: could not convert string to float: 'comp(a)' I assume the x value isn't a numerical value in the configname, but not sure. #!/bin/env/python import numpy as np import matplotlib.pyplot as plt import csv Columns = 'configname,comp(a),form_E,comp_x,relaxed_E_per_atom'.split(',') testdata ='''\ comp(a),form_E,comp_x,relaxed_E_per_atom 0,0,0,-8.15382173 1,0,0.33333333,-5.25358563 0.5,0.18614484,0.2,-6.33922213 0.5,-0.69658919,0.2,-6.69231575 0.5,-0.70549249,0.2,-6.69587707 ''' reader = csv.DictReader(StringIO(testdata)) desired_cols = (tuple(row[col] for col in columns) for row in reader) x=[] y=[] K=-2.69028905 C=-32.65176322 with open('values2.txt','r') as csvfile: points = csv.reader(csvfile,delimiter=',') for row in points: x.append(float(row[0])) y.append(float(row[1])) allpoints=np.loadtxt('hmm.csv',delimiter=',') ref_energy = (Kend-(Cend/2))*comp(a) + Cend/2 form_E = relaxed_E_per_atom-ref_energy(comp_x) plt.scatter(x,y, label='Energy') plt.xlabel('Composition KxC',fontsize=24) plt.ylabel('Formation Energy per carbon (eV)',fontsize=18) plt.title('Convex Hull Potassium Graphite') plt.xticks(fontsize=20) plt.yticks(fontsize=20) plt.tight_layout() p…

http://stackoverflow.com/comment/116602097
type: Comment
score: 0
type: AnswerComment
has text: With recent changes in I think coverage 5.4 I think the last four lines should instead read backendcov = coverage.data.CoverageData(basename='.coverage.backend') backendcov.read() cov.get_data().update(backendcov)
comment on: http://stackoverflow.com/a/50700912

http://stackoverflow.com/comment/88162815
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50576836
type: Comment
has text: This is not matching with the output provided.

http://stackoverflow.com/comment/88297579
type: QuestionComment
comment on: http://stackoverflow.com/q/50643551
has text: In cas the post is two days old, this means that you already decrease it with 0.03%. So if your `baseScore` was 10k (which is again unreachable, since you use a `log`), then only 3 remains. For three days, the percentage is below what can be represented by a float, so `0`. So you "cool down" the posts too fast I guess.
score: 0
type: Comment

http://stackoverflow.com/q/50655031
score: 0
possible better answer: http://stackoverflow.com/a/50657247
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/50657247
accepted answer: http://stackoverflow.com/a/50655070
has body: Suppose I have the following numpy array of shape (10, 5) where I want to split it into two subarrays: the first one contains the first 7 rows and the second one takes the remaining 3 rows. If I do this: x = np.arange(50).reshape(10, 5) x1, y1 = np.vsplit(x, 2) It will split exactly half. How can I make it two subarrays (7,5) and (3,5)?
answer count: 2
tagged with: python-3.x
has title: Split 2D numpy array vertically into uneven subarrays
tagged with: python
has answer: http://stackoverflow.com/a/50655070
type: AnsweredQuestion

http://stackoverflow.com/comment/88192313
type: Comment
score: 4
comment on: http://stackoverflow.com/q/50591442
type: QuestionComment
has text: Possible duplicate of [How can I convert an RGB image into grayscale in Python?](https://stackoverflow.com/questions/12201577/how-can-i-convert-an-rgb-image-into-grayscale-in-python)

http://stackoverflow.com/comment/88166579
has text: Yes, probably they would use the APIs of these sites to scrape the data via the python script, then save the data into a database and use a nodejs server to display the data into the frontend and filter it.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50577932
type: AnswerComment

http://stackoverflow.com/q/50656924
has answer: http://stackoverflow.com/a/50657167
downvote count: 0
possible better answer: http://stackoverflow.com/a/50657022
has answer: http://stackoverflow.com/a/50657470
answer count: 3
has body: TL;DR: see code at the bottom. I'm implementing a Reverse Polish Notation calculator in Python, using the collections.deque stack implementation. Since I'm handling also the case of functions with multiple arguments, I use a separator symbol that I place before the actual arguments. For example, given the following expression as input: max(2, 3, 4), the Shunting Yard algorithm produces the following iterable: ['|', '2', '3', '4', 'max']. When I iterate over it, the separator and the numbers are pushed onto a stack; if a function is encountered, all the previous elements up to the separator are "popped" out of the stack and appended into a list. Is there a more pythonic way to pop out elements from the end of a stack up to a certain condition? My code so far: args = [] while op_stack[-1] != FUNC_ARGS_SEPARATOR: args.append(op_stack.pop())
favorite count: 0
tagged with: python-3.x
upvote count: 2
tagged with: deque
tagged with: python
accepted answer: http://stackoverflow.com/a/50657470
type: AnsweredQuestion
score: 2
has title: pythonic way to pop elements out of stack (collections.deque)
type: Question
has answer: http://stackoverflow.com/a/50657022

http://stackoverflow.com/a/50624606
score: 0
has comment: http://stackoverflow.com/comment/88259153
has comment: http://stackoverflow.com/comment/88260141
has body: try this, df['ranks'].str.split(', ', expand=True).rename(columns={0:'ranks',1:'url'}) Keyword ranks search_type search_volume 0 kw1 [{'rank': 1, 'url': example.com}] 1 500 1 kw1 [{'rank': 1, 'url': example.com}] 2 500 2 kw2 [{'rank': 2, 'url': example.com}] 1 1500 3 kw2 [{'rank': 2, 'url': example.com}] 2 1500 4 kw3 [{'rank': 1, 'url': example.com}] 1 60 5 kw3 [{'rank': 1, 'url': example.com}] 2 60 ranks url 0 [{'rank': 1 'url': example.com}] 1 [{'rank': 1 'url': example.com}] 2 [{'rank': 2 'url': example.com}] 3 [{'rank': 2 'url': example.com}] 4 [{'rank': 1 'url': example.com}] 5 [{'rank': 1 'url': example.com}]
type: Answer
has comment: http://stackoverflow.com/comment/88259303
has comment: http://stackoverflow.com/comment/88260113
has comment: http://stackoverflow.com/comment/88260011
answers question: http://stackoverflow.com/q/50624412

http://stackoverflow.com/comment/88387168
has text: The input is read from the file, but I just added some example data. Thanks.
comment on: http://stackoverflow.com/q/50688595
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50614233
has comment: http://stackoverflow.com/comment/88239005
has comment: http://stackoverflow.com/comment/88239503
has comment: http://stackoverflow.com/comment/88239222
upvote count: 1
has comment: http://stackoverflow.com/comment/88239108
has comment: http://stackoverflow.com/comment/88239144
score: 1
has body: The layouts handle the geometry() of the widgets so that when wanting to change the pos property these are interfacing with their handles so it is very common that you get that type of behavior, a better option is to use a QVariantAnimation to establish a fixed height: import sys from PyQt4 import QtGui, QtCore class AnimatedWidgets(QtGui.QWidget): def __init__(self): super(AnimatedWidgets, self).__init__() layout1 = QtGui.QVBoxLayout(self) expanding_label = QtGui.QLabel("Expanding label!") expanding_label.setStyleSheet("border: 1px solid red") layout1.addWidget(expanding_label) self.file_model = QtGui.QFileSystemModel(self) self.file_model.setRootPath(QtCore.QDir.rootPath()) self.browse_tree = QtGui.QTreeView() self.browse_tree.setModel(self.file_model) layout1.addWidget(self.browse_tree) shrink_tree_btn = QtGui.QPushButton("Shrink the tree") shrink_tree_btn.clicked.connect(self.shrink_tree) layout1.addWidget(shrink_tree_btn) #-- self.tree_anim = QtCore.QVariantAnimation(self) self.tree_anim.setDuration(1000) self.tree_anim.setEasingCurve(QtCore.QEasingCurve.InOutQuart) def shrink_tree(self): self.tree_anim.setStartValue(self.browse_tree.height()) self.tree_anim.setEndValue(0) self.tree_anim.valueChanged.connect(self.on_valueChanged) self.tree_anim.start() def on_valueChanged(self, val): h, isValid = val.toInt() if isValid: self.browse_tree.setFixedHeight(h) def main(): app = QtGui.QApplication(sys.argv) ex = AnimatedWidgets() ex.show() sys.exit(app.exec_()) if __name__ == "__main__": main()
has comment: http://stackoverflow.com/comment/88238845
has comment: http://stackoverflow.com/comment/88239571
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50611712
downvote count: 0
has comment: http://stackoverflow.com/comment/88239361
answers question: http://stackoverflow.com/q/50611712
has comment: http://stackoverflow.com/comment/88239184
type: Answer
has comment: http://stackoverflow.com/comment/88239098
has comment: http://stackoverflow.com/comment/88239131

http://stackoverflow.com/q/50586501
tagged with: pandas
has answer: http://stackoverflow.com/a/50586549
accepted answer: http://stackoverflow.com/a/50587033
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50586549
score: 0
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50587033
answer count: 2
has title: Pandas - Create a column based on values from 2 other columns
favorite count: 0
has body: I am trying to tackle something on Pandas but I am not sure where to start. I have a dataframe with multiple columns, but the ones of interest for this question look like this: df = pd.DataFrame(data = {'subject': [1, 1, 1, 2, 2, 2, 3, 3, 3], 'val': [np.nan, 2, np.nan, np.nan, np.nan, 7, np.nan, np.nan, 10]}) subject val 0 1 NaN 1 1 2.0 2 1 NaN 3 2 NaN 4 2 NaN 5 2 7.0 6 3 NaN 7 3 NaN 8 3 10.0 I want to create a third column which, for each subject, has the value on column val for the corresponding subject: subject val total 0 1 NaN 2 1 1 2.0 2 2 1 NaN 2 3 2 NaN 7 4 2 NaN 7 5 2 7.0 7 6 3 NaN 10 7 3 NaN 10 8 3 10.0 10 I know I can do df'subject', 'val'.dropna() to get the values for the third column, but that would lose all the other columns in the dataframe (which has different values in each row). Thanks

http://stackoverflow.com/comment/88245603
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50617334
has text: Correct, it just prints out only the last entry.. how can i make it to give me the list with all the values sorted?.. Have edited the question..sorry
score: 0

http://stackoverflow.com/comment/88337844
has text: @MateenUlhaq ok, you did not use count method. but your answer is defaultdict(<class 'int'>, {'Mary': 1, 'David': 1, 'Grace': 2, 'Curtis': 1, 'Alice': 1, 'Joe': 1}). return so many unneccessary words.
type: QuestionComment
comment on: http://stackoverflow.com/q/50663198
score: 0
type: Comment

http://stackoverflow.com/a/50581170
score: 1
upvote count: 1
has body: You should use copy to actually create a copy of the variable. from copy import copy temp = copy(landmarks_per_tooth[index])
downvote count: 0
answers question: http://stackoverflow.com/q/50581063
type: Answer

http://stackoverflow.com/a/50596199
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88201634
upvote count: 7
answers question: http://stackoverflow.com/q/50596062
score: 7
has body: With a plain old cursor you can just do cursor.fetchall(), like follows: with connection.cursor() as cursor: cursor.execute("select a, b, c from bar") print(cursor.fetchall()) Which outputs [(1,2,3), (4,5,6), ...] However, if you want to have the results in dictionary format, make sure to connect with: connection = pymysql.connect(db='foo', cursorclass=pymysql.cursors.DictCursor) In this case the results will be usable in your lambda, ie: [{'a':1, 'b':2, 'c': 3}, ...]
has comment: http://stackoverflow.com/comment/88201532
accepted answer of: http://stackoverflow.com/q/50596062
type: AcceptedAnswer

series
tag name: series
tags question: http://stackoverflow.com/q/50582305
type: Tag
tags question: http://stackoverflow.com/q/50583868
tags question: http://stackoverflow.com/q/50680355
tags question: http://stackoverflow.com/q/50683344
tags question: http://stackoverflow.com/q/50611165
tags question: http://stackoverflow.com/q/50695748
tags question: http://stackoverflow.com/q/50662091
tags question: http://stackoverflow.com/q/50589063
tags question: http://stackoverflow.com/q/50663334
tags question: http://stackoverflow.com/q/50570813
tags question: http://stackoverflow.com/q/50623430
tags question: http://stackoverflow.com/q/50658515
tags question: http://stackoverflow.com/q/50588059
tags question: http://stackoverflow.com/q/50667036
tags question: http://stackoverflow.com/q/50662176
tags question: http://stackoverflow.com/q/50592013
tags question: http://stackoverflow.com/q/50603794
tags question: http://stackoverflow.com/q/50667928
tags question: http://stackoverflow.com/q/50647587

http://stackoverflow.com/q/50606466
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50607344
has title: List last charges in Stripe
downvote count: 0
answer count: 1
has body: I'm trying to get a list of our latest Stripe charges received in order to match it with our invoices and customers. Is there any way of obtain the last charges since a given date (i.e the last week)? I have looked in the documentation but I haven't seen anything that could achieve that with the Python API. Thanks in advance.
tagged with: stripe-payments
favorite count: 0
accepted answer: http://stackoverflow.com/a/50607344
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/88403455
score: 2
type: Comment
has text: `[]` is a list in python. Its printing `['t', 'a', 't', 'a', 't']` because you take each letter and put it in a list - `rev.insert(i,word[l-1])`
type: QuestionComment
comment on: http://stackoverflow.com/q/50697054

http://stackoverflow.com/a/50669187
has body: This should cut you some lines: @app.route('/employee') def employee(): cur = connection.cursor() emp_num == request.form.emp_num(emp_num) emp_nums = {'1010': 'dev', '1122': 'analyst'} if emp_num in emp_nums: cur.execute('''SELECT * FROM emp_data WHERE team = "{}"'''.format(emp_nums[emp_num])) else: return 'Data not found'
score: 0
has comment: http://stackoverflow.com/comment/88348439
has comment: http://stackoverflow.com/comment/88741875
answers question: http://stackoverflow.com/q/50667582
type: Answer
has comment: http://stackoverflow.com/comment/88348586
has comment: http://stackoverflow.com/comment/88372755

http://stackoverflow.com/comment/134760283
has text: As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/76423020
type: Comment

http://stackoverflow.com/a/50649804
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50649701
has comment: http://stackoverflow.com/comment/88310859
has comment: http://stackoverflow.com/comment/88311165
type: Answer
score: 8
has comment: http://stackoverflow.com/comment/88310925
has body: Don't cleanup these with shutil. The tempfile.TemporaryDirectory class provides a cleanup() method, just call that if you want to opt-in to an explicit cleanup. The reason you get the crash with your code is that the TemporaryDirectory class is designed to clean up after itself once it goes out of scope (ref count to zero). However, since you've already removed the directory from your filesystem manually, the tear down fails when the instance subsequently tries to delete itself. The "No such file or directory" error is from TemporaryDirectory's own tear down, it's not from your shutil.rmtree line!
has comment: http://stackoverflow.com/comment/88311290
has comment: http://stackoverflow.com/comment/88310984
upvote count: 8
accepted answer of: http://stackoverflow.com/q/50649701

http://stackoverflow.com/comment/88168296
has text: I only have one Input here, the `image` variable used above is one single image. So the output should be only 10 sigmoid values, but it simply isn't. This is sadly not the explanation.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50567959
score: 0

http://stackoverflow.com/a/50632029
has comment: http://stackoverflow.com/comment/88274601
has comment: http://stackoverflow.com/comment/88275306
type: Answer
has comment: http://stackoverflow.com/comment/88274581
answers question: http://stackoverflow.com/q/50631957
has comment: http://stackoverflow.com/comment/88274657
downvote count: 1
score: 3
has body: Split the string at the dots and treat the numbers as integers: &gt;&gt;&gt; version_string = "2.06" &gt;&gt;&gt; version_as_integers = tuple(int(segment) for segment in version_string.split('.')) &gt;&gt;&gt; version_as_integers (2, 6) Then, just compare the versions: if version_1_as_integers &lt; version_2_as_integers: return -1 elif version_1_as_integers == version_2_as_integers: return 0 else: return 1 Complete solution: def version_to_integers(version_string): return tuple(int(segment) for segment in version_string.split('.')) def compare_versions(version_string_1, version_string_2): v1 = version_to_integers(version_string_1) v2 = version_to_integers(version_string_2) return ((v1 &gt; v2) - (v1 &lt; v2)) The last line is a trick from a codegolf.stackexchange.com question
upvote count: 4
has comment: http://stackoverflow.com/comment/88274404
has comment: http://stackoverflow.com/comment/88274345
has comment: http://stackoverflow.com/comment/88274360

http://stackoverflow.com/comment/88136222
has text: I can very clearly see the progress though, given what I assume is the GUI needing some extra time to draw the updated value.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50562433

http://stackoverflow.com/a/50544467
accepted answer of: http://stackoverflow.com/q/50544441
type: Answer
has body: The loop condition is checked at the beginning of each loop. If it passes, everything in the body is executed (and the condition is checked again). If you want to exit the middle of the loop body, use the 'break' statement.
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/50544441
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50597805
tagged with: post
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/50609700
has answer: http://stackoverflow.com/a/50609700
tagged with: get
tagged with: google-cloud-platform
accepted answer: http://stackoverflow.com/a/50597900
downvote count: 0
has body: I don't know how to pass authentication/credentials to the google cloud api post that I'm running from my python program import requests api_endpoint = "https://dataflow.googleapis.com/v1b3/projects/projectid/templates" data = { "jobName": "scriptjob2", "parameters": { "inputFilePattern": "gs://bucket/files/*.json", "outputTopic": "projects/project6/topics/data" }, "environment": { "tempLocation": "gs://bucket/tmp", "zone": "us-central1-f" }, "gcsPath": "gs://dataflow-templates/latest/GCS_Text_to_Cloud_PubSub", "location": "us-central1" } r = requests.post(url = api_endpoint, data = data) result = r.text print("Result:%s"%result) I know that I'm supposed to pass a google service account authentication but I just can't figure out how to do this. This is the error message that I'm getting. "error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other v alid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "status": "UNAUTHENTICATED" } }
favorite count: 0
upvote count: 1
tagged with: python
has title: how to pass authentication/credentials to the google cloud api post that I'm running from python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50597900

http://stackoverflow.com/comment/88145708
comment on: http://stackoverflow.com/q/50566896
has text: @ImportanceOfBeingErnest do you mean adding `def animate(i): for i in uniqueYears: if (data[data['Ano'] == uniqueYears[i]]): ax.scatter(...)` to the function?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50547061
score: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50546946
upvote count: 1
has body: The first line is returning an array with all tr tags with class attribute "even". The [1] array index selector says to select the second tr tag in the array (remember arrays start at 0). At this point the tr object is not an array or any kind of collection you would use brackets on, it is a beautiful soup tag object. The error is saying that [2] is not a valid operation to perform on the tr object.

http://stackoverflow.com/a/50591160
score: -1
answers question: http://stackoverflow.com/q/50591047
type: Answer
downvote count: 1
upvote count: 0
has body: df.replace({'-': None}) is what you are looking for. Found in another post on stack overflow.

http://stackoverflow.com/comment/88198254
comment on: http://stackoverflow.com/a/50594293
score: 0
type: Comment
has text: `for i in range(len(some_list)): ... some_list[i]` is a code smell. Prefer `for i, el in enumerate(some_list): ... el`
type: AnswerComment

gspread
tags question: http://stackoverflow.com/q/50648249
tags question: http://stackoverflow.com/q/50595915
type: Tag
tag name: gspread

http://stackoverflow.com/a/50549044
downvote count: 0
answers question: http://stackoverflow.com/q/50545343
has body: You can try something like this: import cv2 import numpy as np img = cv2.imread('input.jpg') myRect = img[280:340, 330:390] 280:340, 330:390 means: get a rectangle that begins at 280th row and 330th column and ends at 340th row and 390 column. So coordinates of the rectangle would be: (280,330), (280,390), (340,330), (340,390)
score: 4
type: Answer
upvote count: 4

http://stackoverflow.com/q/50571592
has title: Matplotlib FormatStrFormatter returns wrong values
tagged with: python
has answer: http://stackoverflow.com/a/52038175
downvote count: 1
type: Question
tagged with: matplotlib
has answer: http://stackoverflow.com/a/50573539
has comment: http://stackoverflow.com/comment/88153108
upvote count: 4
answer count: 2
score: 3
has comment: http://stackoverflow.com/comment/88153354
favorite count: 0
has body: When trying to plot a heatmap using Seaborns sns.heatmapfunction, I get wrong ticks when formatting the x-axis with FormatStrFormatter. After building the required pivot data frame, the relevant code is: ax = sns.heatmap(oi_pivot_df, cmap=plt.cm.Spectral, cbar=True) ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%.2f')) ax.invert_yaxis() ax.set_xlabel('moneyness') ax.set_ylabel('time to maturity (years)') fig = plt.gcf() plt.tight_layout() Here, x varies between .5 and 96.5. Without the formatter, the x-ticks are the real range: How do I have to change the formatter such that it returns x ticks formatted such that I only see up to the first 2 decimals, e.g. in my example below, the x axis should go from 0.92 to 1.29.
type: UnansweredQuestion

http://stackoverflow.com/q/50695288
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: sockets
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88404124
tagged with: server
type: Question
has title: Keep on listen to udp port server python with recvfrom(), when processing data
has comment: http://stackoverflow.com/comment/88402515
score: 0
tagged with: udp
tagged with: python
has body: I have a simple server while True: d = s.recvfrom(UDP_BUFFER_SIZE) process(d) and a simple client: while True: sock.sendto(data, addr): But I found out that during processing the server is not listening any more, and I loose data that do received. I know UDP can loose data, but here the UDP implementation and the processing that might take too long, preventing me from collecting data. How is it possible to process the received data and still listen to the port ? Even exporting the recvfrom() to a thread, will likely have some time between listening: while True: d = s.recvfrom(UDP_BUFFER_SIZE) export_data(d) # make it faster, but export time can still miss packets.

http://stackoverflow.com/comment/88121789
type: Comment
type: QuestionComment
has text: @PratikKumar Sorry, that should've been ent
comment on: http://stackoverflow.com/q/50555395
score: 0

http://stackoverflow.com/comment/88527024
type: QuestionComment
comment on: http://stackoverflow.com/q/50646120
has text: Thanks for this - I had a slight index issue previously in the code which is why I didn't upvote it earlier. Works well!
score: 0
type: Comment

http://stackoverflow.com/q/50683523
type: Question
has body: I'm trying to build a decorator-based dispatcher, such as you find used by Flask or Pyramid. I got something that works, but ran into a bit of a catch-22. The following code works, but only because foo() gets executed and sets the .mq_path-attribute. When starting the application and building a list of the dispatchable functions no attributes are thus set yet. I want to execute foo() driven by events. I could "manually" prepare a list of functions ahead and updated as I add functions, but I enjoy the way Flask works, by just adding a decorator to a function that handles an URL (or in this case a MQ path). list_of_paths = [] path_dispatcher = {} def handle_mq(path): def decorator(fn): def decorated(*args,**kwargs): decorated.mq_path = path print "Hello from the handle_mq() decorator, your path is: {0}".format(path) return fn(*args,**kwargs) return decorated return decorator @handle_mq('/some/path') def foo(): print "foo!" foo() # &lt;- this code only works if I first call the decorated function for k, v in globals().items(): if hasattr(v, 'mq_path'): list_of_paths.append(v.mq_path) path_dispatcher[v.mq_path] = v print list_of_paths print path_dispatcher path_dispatcher['/some/path']() So basically the question is, how to gather a list of the decorated functions before they are first executed? I'm on Python 2.7.
answer count: 1
tagged with: dispatch
has comment: http://stackoverflow.com/comment/88376854
score: 0
accepted answer: http://stackoverflow.com/a/50683736
has title: Python: Decorator Dispatcher: Catch-22
tagged with: python
tagged with: python-decorators
has answer: http://stackoverflow.com/a/50683736
type: AnsweredQuestion

http://stackoverflow.com/q/50559654
has body: Error: Traceback (most recent call last): File "C:/Users/xx/abc/Final.py", line 167, in &lt;module&gt; tf.app.run() File "C:\Users\xx\tensorflow\python\platform\app.py", line 126, in run _sys.exit(main(argv)) File "C:/Users/xx/abc/Final.py", line 148, in main hooks=[logging_hook]) File "C:\Users\xx\tensorflow\python\estimator\estimator.py", line 363, in train loss = self._train_model(input_fn, hooks, saving_listeners) File "C:\Users\xx\tensorflow\python\estimator\estimator.py", line 843, in _train_model return self._train_model_default(input_fn, hooks, saving_listeners) File "C:\Users\xx\tensorflow\python\estimator\estimator.py", line 856, in _train_model_default features, labels, model_fn_lib.ModeKeys.TRAIN, self.config) File "C:\Users\xx\tensorflow\python\estimator\estimator.py", line 831, in _call_model_fn model_fn_results = self._model_fn(features=features, **kwargs) File "C:/Users/xx/abc/Final.py", line 61, in cnn_model_fn loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits) File "C:\Users\xx\tensorflow\python\ops\losses\losses_impl.py", line 853, in sparse_softmax_cross_entropy name="xentropy") File "C:\Users\xx\tensorflow\python\ops\nn_ops.py", line 2046, in sparse_softmax_cross_entropy_with_logits logits.get_shape())) ValueError: Shape mismatch: The shape of labels (received (100,)) should equal the shape of logits except for the last dimension (received (300, 10)). Train input function: train_input_fn = tf.estimator.inputs.numpy_input_fn( x={"x": train_data}, y=train_labels, batch_size=100, num_epochs=None, shuffle=True) ALL DATASET SHAPES print(train_data.shape) //Output: (9490, 2352) train_labels = np.asarray(label_MAX[0], dtype=np.int32) print(train_labels.shape) //Output: (9490,) eval_data = datasets[1] # Returns np.array print(eval_data.shape) //Output: (3175, 2352) eval_labels = np.asarray(label_MAX[1], dtype=np.int32) print(eval_labels.shape) //Output: (3175,) I read other StackOverflow questions and most of them pointed to the…
answer count: 2
has answer: http://stackoverflow.com/a/50560776
tagged with: deep-learning
downvote count: 0
has comment: http://stackoverflow.com/comment/88131148
has title: Shape of logits and labels mismatch
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89713216
accepted answer: http://stackoverflow.com/a/50560776
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88130772
score: 3
tagged with: conv-neural-network
upvote count: 3
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/88130686
possible better answer: http://stackoverflow.com/a/58216066
has answer: http://stackoverflow.com/a/58216066
has comment: http://stackoverflow.com/comment/88130986
has comment: http://stackoverflow.com/comment/88130335

http://stackoverflow.com/q/50548685
tagged with: django-allauth
answer count: 5
has body: I'm using Django allauth as my user account framework for my django site. The docs show there is an ACCOUNT_USERNAME_MIN_LENGTH however there is no ACCOUNT_USERNAME_MAX_LENGTH for some reason. Is there any way to create a max length for username? Here's my custom allauth signup form - maybe I can do something here?: class AllauthSignupForm(forms.Form): captcha = ReCaptchaField( public_key=config("RECAPTCHA_PUBLIC_KEY"), private_key=config("RECAPTCHA_PRIVATE_KEY"), ) class Meta: model = User def signup(self, request, user): """ Required, or else it throws deprecation warnings """ pass Edit: Trying to subclass SignupView draft1/forms.py class AllauthSignupForm(SignupForm): def __init__(self, *args, **kwargs): super(AllauthSignupForm, self).__init__(*args, **kwargs) self.fields['username']['validators'] += MaxLengthValidator(150, "Username should be less than 150 character long") captcha = ReCaptchaField( public_key=config("RECAPTCHA_PUBLIC_KEY"), private_key=config("RECAPTCHA_PRIVATE_KEY"), ) class Meta: model = User def signup(self, request, user): """ Required, or else it throws deprecation warnings """ pass draft1/views.py from allauth.account.views import SignupView class MySignupView(SignupView): form_class = AllauthSignupForm allauth/account/urls.py url(r"^signup/$", MySignupView.as_view(), name="account_signup"), draft1/settings.py ACCOUNT_SIGNUP_FORM_CLASS = 'draft1.forms.AllauthSignupForm' The above code returns this error: Traceback (most recent call last): File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/Users/zorgan/Desktop/postr1/lib/p…
linked to: http://stackoverflow.com/q/12303478
has title: How to add max_length to allauth username
linked to: http://stackoverflow.com/q/20923776
tagged with: python
possible better answer: http://stackoverflow.com/a/50549813
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50629332
tagged with: django
type: Question
score: 1
has answer: http://stackoverflow.com/a/50940406
has answer: http://stackoverflow.com/a/50549813
has answer: http://stackoverflow.com/a/50941366
accepted answer: http://stackoverflow.com/a/50941366
upvote count: 1
has comment: http://stackoverflow.com/comment/88322849
has answer: http://stackoverflow.com/a/50648437
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/88167391
has text: Yes, what @Sraw said is what I mean by empty.
comment on: http://stackoverflow.com/q/50579027
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88250149
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50619722
score: 0
has text: @soolo What is special about the notebook? What if the user runs the same code without the notebook? What if they save data to a file and then open it with another program? Do you need to log that too?

http://stackoverflow.com/q/50596832
tagged with: python
has body: lets say I have one file in CSV, which has two columns, first column contains the image values in integer i.e., 28 x 28, and second column has label. How an I read this file. numpy.load and numpy.loadtxt both fails. I have to read column 1 and then convert into array of 784.
has comment: http://stackoverflow.com/comment/88202826
type: Question
has comment: http://stackoverflow.com/comment/88204570
has title: Python reading file and then converting into Matrix
score: 0
has comment: http://stackoverflow.com/comment/88202828
has answer: http://stackoverflow.com/a/50617859
answer count: 1
has comment: http://stackoverflow.com/comment/88202937
has comment: http://stackoverflow.com/comment/88202763
type: UnansweredQuestion

http://stackoverflow.com/comment/88325609
has text: sorry i fix it ... wait the solution
comment on: http://stackoverflow.com/q/50657770
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/97041907
type: Comment
comment on: http://stackoverflow.com/a/50608122
type: AnswerComment
has text: I'm struggling with getting started too... would you care to explain which missing packages you also installed?
score: 0

http://stackoverflow.com/q/50558108
tagged with: dataframe
score: 0
tagged with: pandas
has body: I am trying to iterate through a DataFrame group by group, would the group by function do something like that? In the first group, the return is calculated from the profit from group 0, the return from the second group is from the profit at the end of group 1. The Actual return is positive if Win_Lose is 1, 0 otherwise Group Cost Win_Lose Return Profit 0 0 0.00 0 0 $10000 1 1 0.29 1 $2900 $12900 2 1 0.35 0 $3500 $9400 3 1 0.07 1 $700 $11000 4 2 0.16 0 $1760 $9240 5 2 0.19 1 $2090 $11330 6 2 0.27 0 $2970 $8360
has title: Iterate through DataFrame Incrementally
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88127722
tagged with: python
has comment: http://stackoverflow.com/comment/88127126
has comment: http://stackoverflow.com/comment/88127116
has comment: http://stackoverflow.com/comment/88127104
type: Question

http://stackoverflow.com/q/50616958
has comment: http://stackoverflow.com/comment/88243773
has title: Saving results second by second in Python
type: Question
has comment: http://stackoverflow.com/comment/88244194
tagged with: saving-data
has answer: http://stackoverflow.com/a/50617706
answer count: 1
has body: I am measuring a parameter which is a distance between two objects in a live video. I want to save my results (distance) in a text file "second by second" along with the time. To be more specific I want a text file including two columns: 1- Time = [1,2,3,4,5,6,...] 2- Distance = [7,4,8,2,3,1,...] and I need this text file to be updated second by second. I was wondering if someone could help me with that. Thanks!
tagged with: timer
type: UnansweredQuestion
score: 0
tagged with: python

http://stackoverflow.com/comment/88447910
type: AnswerComment
has text: Ohh ok, you're using Celery. I've never used that but I can try to help. Can you post the html?
score: 0
comment on: http://stackoverflow.com/a/50686031
type: Comment

http://stackoverflow.com/comment/88120721
score: 0
type: Comment
has text: Issue with this: flag_parser("--test --test2") returns {'test': None} and not {'test': None, 'test2':None}
comment on: http://stackoverflow.com/a/50554810
type: AnswerComment

http://stackoverflow.com/q/50638524
upvote count: 9
possible better answer: http://stackoverflow.com/a/50679091
has comment: http://stackoverflow.com/comment/88287623
has answer: http://stackoverflow.com/a/50679091
accepted answer: http://stackoverflow.com/a/50788162
score: 9
tagged with: numpy
answer count: 2
tagged with: array-broadcasting
has body: Assuming I want have a numpy array of size (n,m) where n is very large, but with a lot of duplication, ie. 0:n1 are identical, n1:n2 are identical etc. (with n2%n1!=0, ie not regular intervals). Is there a way to store only one set of values for each of the duplicates while having a view of the entire array? example: unique_values = np.array([[1,1,1], [2,2,2] ,[3,3,3]]) #these are the values i want to store in memory index_mapping = np.array([0,0,1,1,1,2,2]) # a mapping between index of array above, with array below unique_values_view = np.array([[1,1,1],[1,1,1],[2,2,2],[2,2,2],[2,2,2], [3,3,3],[3,3,3]]) #this is how I want the view to look like for broadcasting reasons I plan to multiply array(view) by some other array of size (1,m), and take the dot product of this product: other_array1 = np.arange(unique_values.shape[1]).reshape(1,-1) # (1,m) other_array2 = 2*np.ones((unique_values.shape[1],1)) # (m,1) output = np.dot(unique_values_view * other_array1, other_array2).squeeze() Output is a 1D array of length n.
has comment: http://stackoverflow.com/comment/88287791
downvote count: 0
has comment: http://stackoverflow.com/comment/88406186
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88366303
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50788162
has comment: http://stackoverflow.com/comment/88366738
has comment: http://stackoverflow.com/comment/88287273
has title: broadcast views irregularly numpy
type: Question
has comment: http://stackoverflow.com/comment/88421093
has comment: http://stackoverflow.com/comment/88418492
has comment: http://stackoverflow.com/comment/88418722

http://stackoverflow.com/q/50548820
tagged with: python
tagged with: qtcharts
type: AnsweredQuestion
has title: plot candlestick and 5-days average line on a same qtchart but give two x axis plot
accepted answer: http://stackoverflow.com/a/50548931
upvote count: 3
tagged with: pyqt5
has body: I want to plot candlestick and 5-days average line on the same qchart, it should show one x axis, but gives two x axis. here is the code and the plot. import sys from PyQt5.QtChart import (QCandlestickSeries, QChart, QChartView) from PyQt5.QtWidgets import QApplication, QMainWindow from PyQt5.QtCore import Qt from PyQt5 import QtChart as qc """ data to be load just like the following: num, open, high, low, close, ma5 1 7380 7520 7380 7510 7324 2 7520 7580 7410 7440 7372 3 7440 7650 7310 7520 7434 4 7450 7640 7450 7550 7480 5 7510 7590 7460 7490 7502 6 7500 7590 7480 7560 7512 7 7560 7830 7540 7800 7584 ... ... """ app = QApplication(sys.argv) # series = QCandlestickSeries() series.setDncreasingColor(Qt.red) series.setIecreasingColor(Qt.green) ma5 = qc.QLineSeries() # 5-days average data line candle_x_axis_label = [] # stores str type data # in a loop, series and ma5 append corresponding data for num, o, h, l, c, m in data: series.append(QCandlestickSet(o, h, l, c)) ma5.append(m) candle_x_axis_label.append(str(num)) chart = QChart() chart.addSeries(series) # candle chart.addSeries(ma5) # ma5 line chart.setAnimationOptions(QChart.SeriesAnimations) chart.createDefaultAxes() chart.legend().hide() # here is the point # tm is str list, just like '1, 2, 3, ..., n' chart.axes(Qt.Horizontal)[0].setCategories(candle_x_axis_label) # chartview = QChartView(chart) ui = QMainWindow() ui.setGeometry(50, 50, 500, 300) ui.setCentralWidget(chartview) ui.show() sys.exit(app.exec_()) and the plot i check qtchart code, and find out the class type of candlestick x axis is QBarCategoryAxis but the class type of ma5 x axis is QValueAxis. so how to remove of the two x axis?
type: Question
tagged with: pyqt
answer count: 1
downvote count: 0
favorite count: 0
score: 3
has answer: http://stackoverflow.com/a/50548931
tagged with: candlestick-chart

http://stackoverflow.com/a/60272646
type: Answer
answers question: http://stackoverflow.com/q/50634329
score: 0
has body: It's generally easier to download install a binary. If you do build from source: Download the WinPcap Developer's Pack. Use pip's --global-option. setup.py is different, but I think pip is preferred over setup.py anyway. Here's an example line (substitute in the correct paths for your system; I just referenced them right in the Downloads folder): pip install ./pcapy-src-dir --global-option=build_ext --global-option="-LC:\path\to\WpdPack_4_1_2\WpdPack\Lib" --global-option="-IC:\path\to\WpdPack_4_1_2\WpdPack\Include See also this answer

http://stackoverflow.com/q/50544503
score: -1
has comment: http://stackoverflow.com/comment/88100430
downvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88100604
has comment: http://stackoverflow.com/comment/88100287
has comment: http://stackoverflow.com/comment/88100310
tagged with: python
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/50544922
accepted answer: http://stackoverflow.com/a/50544922
has title: Generate files with passing arguments using python
type: Question
has body: I would like to generate files using python is such way. For example, I have script_1.aas file. Inside it, there are 2 parameters which are actually a different path of a network, in the example below, there are 2 folders script_1 in different path : ...; char const * const outputDir = "output\\script_1"; ... success = readNetworkWithLogLevel( net, "network\\script_1", LOGLEVEL_WARNING); I would like to generate or create files using python with the same content and changing only these two parameters with the corresponding number (from 1 to 20), for example, 20 of script_1 with incrementing the number one by one. script_1, script_2, ... script_20.

http://stackoverflow.com/a/50664185
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50664048
downvote count: 0
has body: You can query files by fileId using below API - GET https://www.googleapis.com/drive/v3/files/fileId https://developers.google.com/drive/api/v3/reference/files/get

http://stackoverflow.com/comment/88333402
type: AnswerComment
has text: Thanks Carlos. So can you tell me how to develop and test my app in browser using Spyder IDE? Actually how to run my Flask app in browser? I can do that using my Git Bash terminal but it would be much easier to run directly from Spyder.
comment on: http://stackoverflow.com/a/50661060
type: Comment
score: 1

bokeh
tags question: http://stackoverflow.com/q/50694793
tags question: http://stackoverflow.com/q/50689985
type: Tag
tags question: http://stackoverflow.com/q/50566838
tags question: http://stackoverflow.com/q/50593326
tags question: http://stackoverflow.com/q/50697847
tags question: http://stackoverflow.com/q/50638909
tags question: http://stackoverflow.com/q/50604214
tags question: http://stackoverflow.com/q/50601505
tags question: http://stackoverflow.com/q/50588257
tags question: http://stackoverflow.com/q/50576975
tags question: http://stackoverflow.com/q/50689700
tags question: http://stackoverflow.com/q/50557255
tags question: http://stackoverflow.com/q/50633040
tags question: http://stackoverflow.com/q/50648727
tags question: http://stackoverflow.com/q/50680753
tags question: http://stackoverflow.com/q/50603077
tag name: bokeh
tags question: http://stackoverflow.com/q/50641157

airflow
tags question: http://stackoverflow.com/q/50603012
tag name: airflow
tags question: http://stackoverflow.com/q/50589754
tags question: http://stackoverflow.com/q/50671008
tags question: http://stackoverflow.com/q/50661276
tags question: http://stackoverflow.com/q/50671270
tags question: http://stackoverflow.com/q/50671671
tags question: http://stackoverflow.com/q/50603904
tags question: http://stackoverflow.com/q/50686063
type: Tag
tags question: http://stackoverflow.com/q/50567100

http://stackoverflow.com/comment/88361081
comment on: http://stackoverflow.com/a/50675749
score: 0
type: AnswerComment
type: Comment
has text: Thanks, it works quite well :-)

http://stackoverflow.com/q/50689760
tagged with: data-analysis
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/88389806
has body: How do I fix the output from pandas.describe() method? I'm doing some analytics on a excel file with 16084 records. When I run pd.descibe() it loses 11 records and shows a count of 14921. A count of 14921 for account_with_no_state, which should be 14932. A count of 1152 for accounts_with_state, and the two should total 16084. When I use the built in len() function on the column it returns the correct number of 16084 records. Here's the code: import pandas as pd import numpy as np address_with_accounts = pd.read_excel('private document.xlsx', sheet_name = 'Sheet1') accounts = address_with_accounts'Account Name', 'Sold To Street', 'Sold To City', 'Sold To State/Province' accounts_with_no_state = accounts[accounts['Sold To State/Province'].isnull()] accounts_with_state = accounts[accounts['Sold To State/Province'].notnull()] #print(accounts_with_no_state.head()) print('\n-------------------------------------------------------------------\n') print("number of accounts: ", len(accounts_with_no_state['Account Name'])) print(accounts_with_no_state.describe()) print('\n-------------------------------------------------------------------\n') #print(accounts_with_state.head()) print('\n-------------------------------------------------------------------\n') print("number of accounts: ", len(accounts_with_state['Account Name'])) print(accounts_with_state.describe()) print('\n-------------------------------------------------------------------\n') The output with the top addresses crossed out for privacy: EDIT: The records are there, and show up as the correct number under different columns, just not the Account Name column, which is the important one I need information from.
has comment: http://stackoverflow.com/comment/88389670
type: Question
has comment: http://stackoverflow.com/comment/88389921
score: 0
has comment: http://stackoverflow.com/comment/88389549
tagged with: pandas
has title: Why is pandas not showing 11 rows in the Describe method, How do I fix the output?
has comment: http://stackoverflow.com/comment/88389911
has comment: http://stackoverflow.com/comment/88389853

http://stackoverflow.com/comment/88338237
type: QuestionComment
comment on: http://stackoverflow.com/q/50664026
type: Comment
has text: Your code never splits the string, so of course it doesn't work.
score: 0

http://stackoverflow.com/q/50589906
type: AnsweredQuestion
has title: Why am I getting "No module named 'flask.ext'" with Flask-Autodoc?
linked to: http://stackoverflow.com/q/50261135
favorite count: 0
has body: In setup.py I require both Flask and Flask-Autodoc. I run setup.py install and confirm that both distributions are installed. Following the directions, I imported Flask-Autodoc: from flask.ext.autodoc import Autodoc But I get ModuleNotFoundError: No module named 'flask.ext'. I'm in a Conda Python 3.6 environment, and the same thing happens when I created a new virtual environment and re-install the package with dependencies. I thought that Flask extensions are supposed to be imported from the flask.ext module, but that doesn't seem to be working. I've also tried the following: from flask.autodoc import Autodoc, from autodoc import Autodoc, from FlaskAutodoc import Autodoc.
type: Question
duplicate of: http://stackoverflow.com/q/50261135
has answer: http://stackoverflow.com/a/50589932
tagged with: python
answer count: 1
score: 4
duplicate of: http://stackoverflow.com/q/31837364
upvote count: 4
tagged with: python-import
accepted answer: http://stackoverflow.com/a/50589932
downvote count: 0
tagged with: flask

http://stackoverflow.com/q/50693865
has comment: http://stackoverflow.com/comment/88410983
type: UnansweredQuestion
has title: Redirecting Batch Script Output to Shared Folder in Network
has answer: http://stackoverflow.com/a/50712662
tagged with: anaconda
type: Question
score: 0
tagged with: batch-file
tagged with: batch-processing
answer count: 1
has body: I am using Anaconda Environment for running Python 3.6 (Windows 7) . I have a Windows Batch Script (.bat) for running scripts which I have written in python . The output of the batch script is 3 CSV files which are currently stored in the same directory as the python script. I want to store the CSV files in a shared network location ; but I don't know how . Can we do that ? conda activate env_name python script.py This is what I am using currently to run the batch script. Also I want to schedule this Batch script in Windows machine to run everyday at 12:00 am JST. Any help in that direction is appreciated . Thanks in Advance.
tagged with: python

http://stackoverflow.com/a/50547893
has comment: http://stackoverflow.com/comment/88117170
has comment: http://stackoverflow.com/comment/88106994
answers question: http://stackoverflow.com/q/50547610
has comment: http://stackoverflow.com/comment/88108873
has comment: http://stackoverflow.com/comment/88108763
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88117010
has comment: http://stackoverflow.com/comment/88117172
score: 0
has comment: http://stackoverflow.com/comment/88108760
type: Answer
has comment: http://stackoverflow.com/comment/88106776
has body: so to answer the first part, you can create two timestamp min and max for the interval you want: time_min = pd.Timestamp('2018-05-26 15:00') time_max = pd.Timestamp('2018-05-26 15:30') and then create a mask to select only the rows of your df between this two times: mask = (df.timestamp &gt;= time_min) &amp; (df.timestamp &lt;= time_max) Now if you do df[mask] you will get only the rows where the timestamp is within this 30 min window. For the second question: # you can first create the column for the token do: df['token'] = 'BTC' # should fill all the rows of your df with this word # rename the column close to price df = df.rename(columns={'close':'price'}) # finally save as csv only the columns you want: df'token','timestamp','price'.to_csv('here_the_path_to_your/file.csv') and if you want to add the mask, then do df'token','timestamp','price'[mask].to_csv('here_the_path_to_your/file.csv') EDIT for the json, it depends how you want it, so I would suggest to read the documentation about to_json to find what is possible
has comment: http://stackoverflow.com/comment/88107026
has comment: http://stackoverflow.com/comment/88106804
accepted answer of: http://stackoverflow.com/q/50547610

http://stackoverflow.com/comment/88280486
type: QuestionComment
has text: @StephenRauch. I was hoping you would know of a better dupe.
comment on: http://stackoverflow.com/q/50635116
score: 0
type: Comment

http://stackoverflow.com/comment/88139943
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50564837
type: Comment
has text: `ExtremLevel 43344 43102` these values look like a date. You probably shifted some columns or rows.

http://stackoverflow.com/q/50621829
type: Question
accepted answer: http://stackoverflow.com/a/50622336
tagged with: django-views
has comment: http://stackoverflow.com/comment/88253394
has answer: http://stackoverflow.com/a/50622336
answer count: 1
downvote count: 0
has body: I need to add a specific date format to the DATE_INPUT_FORMATS setting. Now, there is already a default value (a list of formats) for DATE_INPUT_FORMATS - and I want to append my format to that list. What is the best way to go about this? Of course, I'm trying to avoid overriding the default definition.
tagged with: django-rest-framework
score: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/88254121
tagged with: python
upvote count: 4
has title: Add a value to Django's date input settings
type: AnsweredQuestion
tagged with: python-3.x
tagged with: django

http://stackoverflow.com/comment/88103851
has text: hopefully the example i gave helps!
type: QuestionComment
comment on: http://stackoverflow.com/q/50546540
score: 0
type: Comment

http://stackoverflow.com/q/50582560
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/88230569
has comment: http://stackoverflow.com/comment/88174770
tagged with: pyqt
answer count: 1
has comment: http://stackoverflow.com/comment/88230120
has comment: http://stackoverflow.com/comment/88174226
favorite count: 0
linked to: http://stackoverflow.com/q/57750322
has comment: http://stackoverflow.com/comment/88174398
linked to: http://stackoverflow.com/q/23499909
downvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/88174584
type: UnansweredQuestion
tagged with: pyside2
has body: edit: Tried the equivalent code with pyqt5 compiled with cython. It works swimmingly so this seems to be a pyside2 bug. Latest version of cython. My app works fine when i run it with python but when i make it into a module and import the module from a simple launcher script suddenly it doesn't seem to see any data from the internet and it also gives me these: RecursionError: maximum recursion depth exceeded while calling a Python object. Nuitka has the same problem but doesn't give me these recursionerrors. I have no idea if it's relevant but when compiling the program(making object code) with gcc i also get this error/warning/note(the only one): $ python setup.py build_ext --inplace Compiling prog.py because it changed. [1/1] Cythonizing prog.py running build_ext building 'prog' extension gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -march=x86-64 -mtune=generic -O2 -pipe - fstack-protector-strong -fno-plt -march=x86-64 -mtune=generic -O2 - pipe -fstack-protector-strong -fno-plt -march=x86-64 -mtune=generic - O2 -pipe -fstack-protector-strong -fno-plt -fPIC - I/usr/include/python3.6m -c prog.c -o build/temp.linux-x86_64- 3.6/prog.o prog.c: In function ‘__pyx_pf_4prog_13Ui_MainWindow_setupUi.isra.76’: prog.c:41235:18: note: variable tracking size limit exceeded with - fvar-tracking-assignments, retrying without static PyObject *__pyx_pf_4prog_13Ui_MainWindow_setupUi(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self, PyObject *__pyx_v_MainWindow) { ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Also not sure if relevant but i have a bunch of classes(threads) that calls the next class when one is finished making a loop. Maybe this is a nono even if it works fine in python? I'm using pyside2, requests, delorean and humanize. Im not even sure how to start debugging this, it's a 4000 line program. edit: Ok so i managed to reproduce the exact problem in a minimal example. This code will work perfectly before you compile …
has comment: http://stackoverflow.com/comment/88189902
tagged with: cython
has title: When i compile my python code i get: RecursionError: maximum recursion depth exceeded while calling a Python object
linked to: http://stackoverflow.com/q/5061582
has answer: http://stackoverflow.com/a/50582822
has comment: http://stackoverflow.com/comment/88191556
duplicate of: http://stackoverflow.com/q/57750322
score: -1
has comment: http://stackoverflow.com/comment/88230702
has comment: http://stackoverflow.com/comment/88175047

http://stackoverflow.com/q/50631470
answer count: 1
has body: I have a toy python project containing the following files: requirements.txt: numpy==1.14.3 xgboost==0.71 print_numpy_version.py: from __future__ import print_function import numpy print('numpy version: %s' % numpy.version.version) print_xgboost_version.py: from __future__ import print_function import xgboost print('xgboost version: %s' % xgboost.__version__) When I create a virtualenv, install the packages, and run the two programs, everything works exactly as you would expect it to: $ mkvirtualenv toyvirtualenv New python executable in /home/username/.virtualenvs/toyvirtualenv/bin/python2.7 Also creating executable in /home/username/.virtualenvs/toyvirtualenv/bin/python Installing setuptools, pip, wheel...done. virtualenvwrapper.user_scripts creating /home/username/.virtualenvs/toyvirtualenv/bin/predeactivate virtualenvwrapper.user_scripts creating /home/username/.virtualenvs/toyvirtualenv/bin/postdeactivate virtualenvwrapper.user_scripts creating /home/username/.virtualenvs/toyvirtualenv/bin/preactivate virtualenvwrapper.user_scripts creating /home/username/.virtualenvs/toyvirtualenv/bin/postactivate virtualenvwrapper.user_scripts creating /home/username/.virtualenvs/toyvirtualenv/bin/get_env_details (toyvirtualenv) $ pip install -r requirements.txt Collecting numpy==1.14.3 (from -r requirements.txt (line 1)) Using cached https://files.pythonhosted.org/packages/b8/97/ecff917542e3a8a33bc8e88c031ed50c90577fd205eab362b29f3e57c09e/numpy-1.14.3-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl Collecting xgboost==0.71 (from -r requirements.txt (line 2)) Collecting scipy (from xgboost==0.71-&gt;-r requirements.txt (line 2)) Using cached https://files.pythonhosted.org/packages/d1/d6/3eac96ffcf7cbeb37ed72982cf3fdd3138472cb04ab32cdce1f444d765f2/scipy-1.1.0-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl Installing collected packages: numpy, scipy, xgboos…
tagged with: xgboost
tagged with: bazel
has title: Bazel rules_python fails to copy xgboost into runfiles directory
tagged with: python
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/50688713
downvote count: 1
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/50688713
type: Question

http://stackoverflow.com/comment/88102929
has text: @MiniMiloe sure, `colors.cnames` is a dictionary. You can make a copy and delete all the colors you don't want. --- Re the error could you please copy&paste the exact two lines you are using right now? (Starting with `named_colors =` and ending just before `ncol =`)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50545735
type: AnswerComment

http://stackoverflow.com/comment/88226342
type: Comment
comment on: http://stackoverflow.com/a/50608125
has text: I want the turtle to go to (900, -900) and then start drawing. But it just disappears.
type: AnswerComment
score: 0

http://stackoverflow.com/q/50571641
favorite count: 0
type: Question
score: 3
tagged with: python
upvote count: 3
answer count: 1
has body: As described in the Keras handbook -Deep Learning with Pyhton-, for a multi-output model we need to specify different loss functions for different heads of the network. But because gradient descent requires you to minimize a scalar, you must combine these losses into a single value in order to train the model. Very imbalanced loss contributions will cause the model representations to be optimized preferentially for the task with the largest individual loss, at the expense of the other tasks. To remedy this, you can assign different levels of importance to the loss values in their contribution to the final loss. This is useful in particular if the losses’ values use different scales. Can anyone help with the following: I've got a five-output model with the following outputs: emotion (multiclass, multilabel classification) valence (regression) arousal (regression) dominance (regression) age (multiclass classification) I am using the following : losses_list = {'EMOTIONS': 'binary_crossentropy', 'VALENCE': 'mse', 'AROUSAL': 'mse', 'DOMINANCE': 'mse', 'AGE': 'categorical_crossentropy'} losses_weights = {'EMOTIONS': 1.0, 'VALENCE': 0.025, 'AROUSAL': 0.025, 'DOMINANCE': 0.025, 'AGE': 0.45} metrics ={'EMOTIONS': 'crossentropy', 'VALENCE': 'mse', 'AROUSAL': 'mse', 'DOMINANCE': 'mse', 'AGE': 'categorical_accuracy'} Are those the right loss functions? Are those the right weights and are those metrics properly set?
type: UnansweredQuestion
tagged with: deep-learning
has title: Compilation options of a multi-output model: multiple losses & loss weighting
downvote count: 0
has answer: http://stackoverflow.com/a/50571803
tagged with: keras

http://stackoverflow.com/a/50554426
accepted answer of: http://stackoverflow.com/q/50554374
type: Answer
has comment: http://stackoverflow.com/comment/88119972
score: 2
upvote count: 2
has body: No. You are conflating cumulative time with time spent in the top-level code of the __init__.py file itself. The top-level code calls other methods, and those together take a lot of time. Look at the self column instead to find where all that time is being spent. Also see What is the difference between tottime and cumtime in a python script profiled with cProfile?, the incl. column is the cumulative time, self is the total time. I'd just filter out all the &lt;frozen importlib.*&gt; entries; the Python project has already made sure those paths are optimised. However, your second screenshot does show that in your profiling run, all that your Python code busied itself with was loading bytecode for modules to import (the marshal module provides the Python bytecode serialisation implementation). Either the Python program did nothing but import modules and no other work was done, or it is using some form of dynamic import that is loading a large number of modules or is otherwise ignoring the normal module caches and reloading the same module(s) repeatedly. You can profile import times using Python 3.7's new -X importtime command-line switch, or you could use a dedicated import-profiler to find out why imports take such a long time.
has comment: http://stackoverflow.com/comment/88119969
answers question: http://stackoverflow.com/q/50554374
has comment: http://stackoverflow.com/comment/88119813
has comment: http://stackoverflow.com/comment/88119652
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88120026
downvote count: 0
has comment: http://stackoverflow.com/comment/88119914
has comment: http://stackoverflow.com/comment/88120212

http://stackoverflow.com/comment/88260247
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50612003
has text: It would be good if you could [edit] the question and explain the full requirements.

http://stackoverflow.com/comment/88415838
has text: No no, rect.move_ip made it turn false only.
comment on: http://stackoverflow.com/a/50667910
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50573742
has body: I'm using apache and python to run my web pages. But when I try to save even a txt file generated on the fly, the file is not saved. def save(req): try: fe1=req.form['fe1'] fe2=req.form['fe2'] file=open("file.txt",'w') file.write("%s %s" %(fe1,fe2)) file.close() except KeyError: fe1='' fe2='' view=""" """.format(**locals()) return (view) After I submi the form I get this: Mod_python error: "PythonHandler mod_python.publisher" Traceback (most recent call last): File "/usr/lib64/python2.7/site-packages/mod_python/apache.py", line 399, in HandlerDispatch result = obj(req) File "/usr/lib64/python2.7/site-packages/mod_python/publisher.py", line 222, in handler published = publish_object(req, object) File "/usr/lib64/python2.7/site-packages/mod_python/publisher.py", line 446, in publish_object return publish_object(req, util.apply_fs_data(obj, req.form, req=req)) File "/usr/lib64/python2.7/site-packages/mod_python/util.py", line 642, in apply_fs_data return object(**args) File "<string>", line 5, in save IOError: [Errno 13] Permission denied: 'file.txt'
has comment: http://stackoverflow.com/comment/88157033
score: 0
has title: How can I save a document from web page on server side?
type: UnansweredQuestion
tagged with: python
answer count: 0
type: Question
tagged with: server
has comment: http://stackoverflow.com/comment/88188043
tagged with: apache

http://stackoverflow.com/a/50576994
has body: import sys sys.exit() This will end the runtime, freeing up the GPU. EDIT: Apparently my last answer doesn't work any more. The thing to do now is !kill -9 -1.
has comment: http://stackoverflow.com/comment/88260156
has comment: http://stackoverflow.com/comment/88279045
downvote count: 2
upvote count: 6
score: 4
accepted answer of: http://stackoverflow.com/q/50541851
has comment: http://stackoverflow.com/comment/119888135
answers question: http://stackoverflow.com/q/50541851
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/88163379
type: Comment
has text: Can you add (or may I add) the various commands we used to investigate the question?
comment on: http://stackoverflow.com/a/50574746
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88215069
has text: Why are you incrementing i and j inside your for loops? The for loop will increment them for you. If you wish i or j to increment by more than 1 each time, you tell `range` to do that for you.
comment on: http://stackoverflow.com/q/50602212
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50627516
has comment: http://stackoverflow.com/comment/88265852
score: 1
has comment: http://stackoverflow.com/comment/88265452
tagged with: authentication
upvote count: 1
tagged with: django
linked to: http://stackoverflow.com/q/49165201
tagged with: django-forms
has comment: http://stackoverflow.com/comment/88265808
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50628945
tagged with: cloud9
has title: DJANGO Login // INPUT FIELDS not working // Error messages not showing
answer count: 2
possible better answer: http://stackoverflow.com/a/50627689
accepted answer: http://stackoverflow.com/a/50628945
has body: ****** Hear me out, I know this is kinda long and I hate to sound like this, but I haven't slept in 4 days and this is part of my project due for school so I would really appreciate literally any input on this ****** Hello, I'm relatively new to Django but nonetheless, I've been bouncing from tutorial to tutorial on youtube and Django documentation try to make up for that. I've created the polls application, and was also creating several other applications but both times when I was almost complete, they went COMPLETELY blank white and I had to START ALL OVER. At this point, I'm just about tired of Django, but I'm willing to continue because I really hate quitting. Anyways that's not what this question is about (although if you could help get my apps up and running again that would be great! I'll put a link down below). After my most recent app crash after trying to learn how to do a login page. I started yet another app called accounts which would be SOLELY dedicated to login/logout/register. However, so far things haven't been working out great. I started out following one tutorial on youtube, but then there was a whole bunch of errors that I couldn't get out of that had to deal with indentations and stuff. So I started my app over with another tutorial, which is this one right here: https://www.youtube.com/watch?v=BIgVhBBm6zI I tried looking past my errors (which was the fact that my input fields weren't showing up) for this video and tried to move on to the next one which was the logic behind the login page. However I know had ANOTHER ERROR. Now the error messages weren't working and whenever I click submit, nothing happens. The page just BASICALLY refreshes. And I know that I haven't got deep enough to the registration part, which would allow me to actually log in, but I'm expecting some sort of error message to tell me that I don't have an account or something. For my input fields, I've tried several things (including this post) and nothing works. The only thin…
downvote count: 0
has answer: http://stackoverflow.com/a/50627689
has comment: http://stackoverflow.com/comment/88265247
favorite count: 0
tagged with: python

http://stackoverflow.com/q/50685333
has body: I have installed multiple versions of Python. Currently when I do which Python - I believe it still points to the default version of the Python and not to the one that's installed by python2.7. When I try python2.7 it shows a different location of python2.7 PMs-MBP:~ prem$ which python /usr/local/bin/python PMs-MBP:~ prem$ which python python2.7 /usr/local/bin/python /Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 What should I change to point the default version (Python) to homebrew version? I tried to link using the below command but get the below error: PMs-MBP:~ prem$ brew link python2.7 Error: No such keg: /usr/local/Cellar/python2.7
score: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50685461
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50685704
tagged with: python
has title: Multiple versions of Python on a Mac
type: UnansweredQuestion
tagged with: homebrew
upvote count: 1

http://stackoverflow.com/q/50625320
favorite count: 0
upvote count: 3
linked to: http://stackoverflow.com/q/47744131
answer count: 1
tagged with: google-drive-api
linked to: http://stackoverflow.com/q/48376580
has title: How to access files on Google Drive via Google Colab notebook (.ipynb)?
type: UnansweredQuestion
tagged with: python
score: 3
downvote count: 0
has answer: http://stackoverflow.com/a/50759287
linked to: http://stackoverflow.com/q/15057907
has body: I have uploaded all the files I need to train (fine-tune) an object detection model on my Google Drive account. There, I have opened an ipynb file via google colab and I need to run some scripts to initialize things and run training. But I ran into a problem of not knowing how to access the files that I uploaded from the notebook. The notebook is created in the same directory of the scripts that I need to run. When I execute !ls I get only one datalab folder in return, and !pwd returns /content. I want to know if there's a way to access all the files I have uploaded to my google drive account. I may be doing the wrong thing trying to train a model this way, but I don't know any other. So, please help :). Thank you in advance.
has comment: http://stackoverflow.com/comment/88260587
type: Question
has comment: http://stackoverflow.com/comment/94933083
tagged with: google-colaboratory

http://stackoverflow.com/comment/88110389
comment on: http://stackoverflow.com/a/50549713
type: AnswerComment
has text: So is your problem fixed now?
score: 0
type: Comment

http://stackoverflow.com/comment/88333791
type: Comment
type: QuestionComment
has text: @UriGoren I ran this code, but I am getting the rows which are not there in CSV1, I want specifically the rows from CSV1 which are not there in CSV2. CSV1 file has 405 entries and CSV2 has around 16k, but it is missing entries that are in CSV1 and I need those to write to a file.
score: 0
comment on: http://stackoverflow.com/q/50651406

http://stackoverflow.com/q/50628407
accepted answer: http://stackoverflow.com/a/50628485
type: Question
has body: I have a list of dicts from which I need to extract, into a new list, some elements. It works fine for one element: d = [ { "a": 1, "b": { "x": 3 }, "blah": 4 }, { "a": 10, "b": { "x": 30 }, "blah": 40 }, ] z = [k["b"] for k in d] print(z) This outputs [{'x': 3}, {'x': 30}] which is the extracted data. I now realize that I also need to include in the extracted dict another element from the original one: a (and its value). I thought I would just take the value if b and update() it with a pair: y = [k["b"].update({"a": k["a"]}) for k in d] print(y) This will not work (returns [None, None]) as update() does not return the resulting dict. A previous question led me to build a dict() from the components: x = [dict(a=k["a"], **k["b"]) for k in d] print(x) This crashes with Traceback (most recent call last): File "C:/dev/config/scratches/scratch_21.py", line 24, in &lt;module&gt; x = [dict(a=k["a"], **k["b"]) for k in d] File "C:/dev/config/scratches/scratch_21.py", line 24, in &lt;listcomp&gt; x = [dict(a=k["a"], **k["b"]) for k in d] TypeError: type object got multiple values for keyword argument 'a' What does that mean? Specifically: what are the "multiple values" when there is only one for that key (an integer) ?
has title: Why do I get a TypeError when building a dict()?
tagged with: list-comprehension
upvote count: 4
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/88267266
linked to: http://stackoverflow.com/q/1452995
has answer: http://stackoverflow.com/a/50628485
type: AnsweredQuestion
score: 1
downvote count: 3

http://stackoverflow.com/comment/88373667
type: QuestionComment
comment on: http://stackoverflow.com/q/50679343
has text: Again, I'd be really surprised if the upgrade from Django 1.11.1 to 1.11.4 caused a problem with `forms.ValidationError`. There's too much code and the explanation isn't clear on that question, so I didn't answer it. O don't know what you mean by "does not work", but the comments on this question aren't the best place to discuss that.
score: 0
type: Comment

http://stackoverflow.com/comment/90479277
has text: this question completed. problem is my django application returned 5xx error. thanks for answers and comments!
comment on: http://stackoverflow.com/q/50575729
score: 0
type: Comment
type: QuestionComment

passlib
tag name: passlib
tags question: http://stackoverflow.com/q/50636805
type: Tag

http://stackoverflow.com/comment/88316312
score: 0
has text: @PaulCornelius Thank you for the info that was something I did not know. However I am still unable to correct the error I am having and I do not see what is the cause. I have been looking all over for half the day and just don't see this problem somewhere else and not sure what the solution would be. I am sure once I figure it out it will be one of those things that seams obvious.
type: QuestionComment
comment on: http://stackoverflow.com/q/50652766
type: Comment

http://stackoverflow.com/q/50656560
has title: Automated download without the download bar
has comment: http://stackoverflow.com/comment/88350273
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88326022
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88477862
answer count: 0
tagged with: selenium
type: Question
has body: I'm trying to download a file from a website using selenium in Python. I'm using a chrome webdriver to do the following I click on the button to download the dataset and add an implicit wait time.sleep(4) to wait for the download to begin Then I select a drop-down for the next data-set. The problem is that when the file download begins the download bar pops up and the window gets resized. This triggers a javascript code that refreshes the page to fix the UI. Due to this the dropdown selection sometimes occurs before the page is refreshed which causes the code to stop post the refresh. These are the possible workarounds that I can think of Increase the implicit wait time (Inefficient and have to use implicit wait. Cannot wait for an element to be visible because the same page is reloaded with the same elements) Disable javascript in the entire webdriver profile (I need it for other elements to load, plus I'm unable to pass arguments to the webdriver due to IT restrictions) Download the file in a separate window similar to this answer (Again, inefficient) Press Ctrl + J immediately to skip the browser download bar from popping up (Browser shortcuts are not working with the chrome webrowser) I'm a bit new to automated testing, so any other ideas that you may have would be helpful.
has comment: http://stackoverflow.com/comment/88341363
linked to: http://stackoverflow.com/q/26566799
linked to: http://stackoverflow.com/q/41598169
score: 0
tagged with: automated-tests
has comment: http://stackoverflow.com/comment/88337493
linked to: http://stackoverflow.com/q/21905946

http://stackoverflow.com/comment/88160534
has text: Because, `range(2, 2)` is an empty range so it'll be skipped.
score: 3
comment on: http://stackoverflow.com/q/50575700
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50579860
accepted answer of: http://stackoverflow.com/q/50579691
has body: Since you're using numpy, use np.repeat + np.reshape: &gt;&gt;&gt; np.repeat(arr, 3).reshape(-1, 3) array([[9.975, 9.975, 9.975], [9.976, 9.976, 9.976], [9.977, 9.977, 9.977], [9.978, 9.978, 9.978], [9.979, 9.979, 9.979], [9.98 , 9.98 , 9.98 ], [9.981, 9.981, 9.981], [9.982, 9.982, 9.982], [9.983, 9.983, 9.983], [9.984, 9.984, 9.984], [9.985, 9.985, 9.985], [9.986, 9.986, 9.986], [9.987, 9.987, 9.987], [9.988, 9.988, 9.988], [9.989, 9.989, 9.989], [9.99 , 9.99 , 9.99 ], [9.991, 9.991, 9.991], [9.992, 9.992, 9.992], [9.993, 9.993, 9.993], [9.994, 9.994, 9.994]])
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50579691
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88331701
comment on: http://stackoverflow.com/q/50660786
score: 0
has text: It's Instagram website. Here is the link: https://www.instagram.com/ . It's the form to create a new account
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88378247
has text: but actually you need to care with the whitespace in the beginning of lines. EDIT: or use `RegexOptions.IgnorePatternWhitespace` as Thomas Ayoub mentionned in his answer.
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50684032

http://stackoverflow.com/q/50574244
answer count: 2
has comment: http://stackoverflow.com/comment/88157962
tagged with: counting
has answer: http://stackoverflow.com/a/50574341
has body: I'm just learning Python, and have been having a little bit of trouble with the list functionality of the language. I have a .csv file named purchases.csv and I need to do four things with it: output the total number of "purchase orders" aka count the total number of entries in the csv output the average amount of the purchases, showing three decimals. output the total number of purchases made over 1,800 output the average amount of purchases made that are over 1,800 showing three decimals. The output needs to look something like: Total Number of Purchases: xxxx Amount of Average Purchase: xxxx Number of Purchase Orders over $1,800: xxxx Amount of Average Purchases over $1,800: xxxx So far I've written import csv with open('purchases.csv') as csvfile: readCSV = csv.reader(csvfile,delimiter=',') total_purchases=[] for row in readCSV: total=row[0] total_purchases.append(total) print(total_purchases) my_sum=0 for x in home_runs: my_sum=my_sum+int(x) print("The total number of purchases was: ", my_sum) To find the total number of purchases, but I've hit a wall and can't seem to figure out the rest! I'd love any help and guidance with this...I just can't figure it out!
upvote count: 1
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
possible better answer: http://stackoverflow.com/a/50574341
accepted answer: http://stackoverflow.com/a/50574326
has comment: http://stackoverflow.com/comment/88157971
favorite count: 0
has title: Counting entries in a CSV?
downvote count: 0
has answer: http://stackoverflow.com/a/50574326
type: AnsweredQuestion
tagged with: list
score: 1
type: Question

http://stackoverflow.com/comment/88202932
score: 3
comment on: http://stackoverflow.com/q/50596895
type: QuestionComment
type: Comment
has text: You have your indices backwards. It should be `items[j][i]`. Also, I don't get the question. You're appending values to that list; why would you expect it to be empty?

http://stackoverflow.com/q/50692972
downvote count: 0
possible better answer: http://stackoverflow.com/a/50693737
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/50693910
has body: I have a error when I implement the XOR with tensorflow. The error message indicates that the shape of input data does not match the shape of the placeholder. The code is following: #!/usr/bin/python import tensorflow as tf import numpy as np x = tf.placeholder(tf.float32,shape=[None,2]) data = np.random.rand(2,2) print data.shape print data y = tf.add(x,x) sess = tf.Session() sess.run(tf.global_variables_initializer()) sess.run(y,{x:data}) print sess.run(y) The error message: InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape [?,2] [[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[?,2], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
has answer: http://stackoverflow.com/a/50693737
upvote count: 1
tagged with: tensorflow
has answer: http://stackoverflow.com/a/50693910
type: Question
type: AnsweredQuestion
has title: the shape of feed data does not match the shape of the placeholder in tensorflow
score: 1
answer count: 2

http://stackoverflow.com/q/50672040
has comment: http://stackoverflow.com/comment/88355101
has comment: http://stackoverflow.com/comment/88355209
has title: How to monitor changes to a large file?
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/88354041
score: 0
has body: I'm using python to build a big tree in a server, and I need read a file to get data. When the file changes, I want to update my tree. Since the file is too big ,say 1G, then the cost time of reading and building the tree is too long, say 2 minutes. Python does not support "real multithreading". (I tried and made the server blocked), so I tried multiprocessing, but it takes up too many resources, and data shared between processes is bit hard. So is there a proper way to monitor the file and build a new tree to replace the old one in the server?
has comment: http://stackoverflow.com/comment/88355559
has comment: http://stackoverflow.com/comment/88355251
answer count: 0
type: UnansweredQuestion
tagged with: multithreading
tagged with: python

http://stackoverflow.com/comment/88316344
has text: Legend @jezrael
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50638247

http://stackoverflow.com/comment/88412885
has text: Thank you so much. Can all the functions from matlab be imported to Pyhthon?
comment on: http://stackoverflow.com/a/50698464
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88334798
has text: Please post the error with traceback in the question, not as a comment.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50661733
score: 0

http://stackoverflow.com/a/50587273
type: Answer
answers question: http://stackoverflow.com/q/50586807
score: 0
has comment: http://stackoverflow.com/comment/88184120
has body: I like the glob module. You can match against a pattern for a given folder. Here is your code with some edits to show how it might work. import glob pdfs = glob.glob("./*.pdf") for pdf in pdfs: image_pdf = Image(pdf, resolution=300) image_jpeg = image_pdf.convert('jpeg') txt = tool.image_to_string( PI.open(io.BytesIO(image_jpeg)), lang=lang, builder=pyocr.builders.TextBuilder() ) final_text.append(txt)

http://stackoverflow.com/comment/116855179
score: 3
has text: @hadi It can open up security vulnerabilities very easily. For example, if you use this code: `import subprocess;name = input("Name? ");subprocess.run(f"echo Hi, {name}", shell=True)` then someone can tell the user to type `person;sudo rm -Rf /*` as their name which will be a valid command since the entire string put together is `echo person;sudo rm -Rf /*` (sudo rm -Rf /* in UNIX will delete every file possible on the computer, recursively). They can't do that with `shell=False` since it's not actually run in a shell, so that can't happen.
comment on: http://stackoverflow.com/a/50631835
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50645297
answer count: 2
accepted answer: http://stackoverflow.com/a/50645672
downvote count: 0
has title: How to use isin while ignoring index
has body: I'm trying to check if rows exist in another dataframe. I'm not joining/merging because of issues with it creating duplication, and then needing to filter out that duplication might also filter out actual duplication that I want to keep. example: table1 = pd.DataFrame({'a':[1, 2, 5, 3, 4], 'b':['a', 'b', 'e', 'c', 'd']}) table2 = pd.DataFrame({'a':[1, 4, 3, 6, 2], 'b':['a', 'd', 'c', 'f', 'b']}) table1.isin(table2) a b 0 True True 1 False False 2 False False 3 False False 4 False False I would like all of these to be True except at index 2 where row 5 e doesn't exist in table2.
favorite count: 0
tagged with: pandas
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50645338
has answer: http://stackoverflow.com/a/50645338
type: Question
score: 5
upvote count: 5
has answer: http://stackoverflow.com/a/50645672

http://stackoverflow.com/q/50683810
upvote count: 3
answer count: 2
has answer: http://stackoverflow.com/a/58565853
accepted answer: http://stackoverflow.com/a/50684010
has body: I am trying to execute a stored Procedure with 20 different table outputs. These outputs range from 3-6 columns and 10-100 rows. If not pyodbc, how else would I be able to iterate through all these tables without the same structure? connection = pyodbc.connect(r'DRIVER={SQL Server Native Client 11.0};SERVER=dsdrsossql2;DATABASE=TableauDev;Trusted_Connection=yes;') sql = "{call dbo.DGGrading}" cur = connection.cursor() rows = cur.execute(sql,).fetchall() columns = [column[0] for column in cur.description] df = pd.DataFrame.from_records(rows,columns=columns) print(df)
type: AnsweredQuestion
score: 3
downvote count: 0
favorite count: 0
has title: Stored Procedure Multiple Tables - PYODBC - Python
has answer: http://stackoverflow.com/a/50684010
type: Question
tagged with: python
tagged with: pyodbc
possible better answer: http://stackoverflow.com/a/58565853

http://stackoverflow.com/a/50568344
downvote count: 0
answers question: http://stackoverflow.com/q/50560189
score: 1
has body: While working with Python and unittest you need to take care of the following: def setUp(self): The setUp() is the part of initialization and this method will get called before every test function which you are going to write in this testcase class. maximize_window(): Instead of using maximize_window() use chrome.options class to maximize the browser window. implicitly_wait(): Implicit Wait once set, the implicit wait is set for the life of the WebDriver object instance. Always invoke driver.quit() within tearDown(){} method to close &amp; destroy the WebDriver and Web Client instances gracefully. Here is your own code block with the minor tweaks mentioned above: import unittest from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.desired_capabilities import DesiredCapabilities class KenLogin(unittest.TestCase): def setUp(self): global driver options = Options() options.add_argument("start-maximized") options.add_argument("disable-infobars") options.add_argument("--disable-extensions") cap = DesiredCapabilities().CHROME cap = options.to_capabilities() self.driver = webdriver.Chrome(desired_capabilities=cap, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe') def test_login(self): self.driver.implicitly_wait(2000) self.driver.get("http://qa.kenzen.com") username = self.driver.find_element_by_xpath("/html/body/div[1]/div/div[2]/div/div[2]/form/div[1]/input") password = self.driver.find_element_by_xpath("/html/body/div[1]/div/div[2]/div/div[2]/form/div[2]/input") username.send_keys("pardeepk@clovity.com") password.send_keys("Kenzen@123") button = self.driver.find_element_by_xpath("/html/body/div[1]/div/div[2]/div/div[2]/form/button") button.send_keys(Keys.ENTER) print("Login Pass") def tearDown(self): self.driver.quit() if __name__ == "__main__": unittest.main() Console Output: Login Pass . -----------------------------------------------------------…
upvote count: 1
has comment: http://stackoverflow.com/comment/88172380
has comment: http://stackoverflow.com/comment/88450157
type: Answer

http://stackoverflow.com/comment/88241181
type: Comment
score: 0
has text: Logging should be there as a separate utility. So that, you can simply initiate the logging from any other files/functions and maintain the log file.
type: QuestionComment
comment on: http://stackoverflow.com/q/50615566

http://stackoverflow.com/comment/88349304
type: QuestionComment
comment on: http://stackoverflow.com/q/50669706
score: 1
has text: What do you expect `y = time.sleep(x)` to do? You also never decremented `y`.
type: Comment

http://stackoverflow.com/a/72035181
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/50563745
score: 2
downvote count: 0
has body: Maybe late to answer, but just to supplement the great answer above: In Sympy 1.8, a Poly object x has the attribute .args, i.e.: import sympy as sp x = sp.Poly(x**3 + 2*x**2 + 3*x*y + 4*y**2 + 5*y**3) x.args[1:] #returns (x,y) and x.args[1:] will be sorted based on how you defined your symbols. For instance, if your polynomial has n variables in terms of the symbols: a = sp.symbols('a:n') then x.args[1:] would be in the order (a0, ..., an). Knowing this and x.monoms(), I'm sure it could be put in the format that you wanted.

http://stackoverflow.com/a/50573684
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50573650
type: Answer
has comment: http://stackoverflow.com/comment/88288353
upvote count: 2
has body: Get the max of each max's, and min of each min's max(max(v.index) for k,v in df_dict.items()) min(min(v.index) for k,v in df_dict.items()) 2016-11-02 00:00:00 2015-07-02 00:00:00 Adding @Wen suggestion, if you won't use both k and v, you can do max(max(v.index) for _,v in df_dict.items()) or even max(max(df_dict[k].index) for k in df_dict.keys())
has comment: http://stackoverflow.com/comment/88157089
answers question: http://stackoverflow.com/q/50573650
score: 2
type: AcceptedAnswer

http://stackoverflow.com/q/50665213
has answer: http://stackoverflow.com/a/50665242
answer count: 2
score: 0
has answer: http://stackoverflow.com/a/50665449
has comment: http://stackoverflow.com/comment/88340708
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88342331
tagged with: wikipedia
has title: How to delete a line with starts with function by python3
has comment: http://stackoverflow.com/comment/88340796
type: Question
has body: I want to delete a line in 50,000 wikipages. Because that line is a dead external web page link. For example, have a look at this wiki page. The line consists of two parts. one is starting text another is the URL. THe URL varies for each and every word but the text always starts with '*தமிழ் இணையப் பல்கலைக்கழக அகரமுதலியில் '. How can i delete the line which starts with fuction? Sample code : #!/usr/bin/env python #-*- coding: utf-8 -*- wikiPage = '''==உசாத்துணை== * தமிழ் இணையப் பல்கலைக்கழக அகரமுதலியில் [http://www.tamilvu.org/slet/servlet/o33.o33searh?CboSelect=1&amp;TxtSearch=abdominal+muscle&amp;OptSearch=&amp;id=All abdominal muscle]''' # part1 is a line of 'starts with' part1 = '* தமிழ் இணையப் பல்கலைக்கழக அகரமுதலியில் ' part2 = '[http://www.tamilvu.org/slet/servlet/o33.o33searh?CboSelect=1&amp;TxtSearch=abdominal+muscle&amp;OptSearch=&amp;id=All abdominal muscle]' print(wikiPage.replace('part1','')) How to delete part2 too? Please note that part2 is a url which differs fro every wiki page.

http://stackoverflow.com/comment/88350730
comment on: http://stackoverflow.com/a/50669493
score: 0
has text: @The42ndTurtle: I think so. But let me double check tomorrow, when I again have access to a R-Pi and a scope.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/88389247
type: QuestionComment
has text: @FranciscoCouzo It says in the docs that it has to be csrf_exempt here: http://www.django-rest-framework.org/tutorial/1-serialization/ also do you think this would be better than just doing a query and adding a row?
comment on: http://stackoverflow.com/q/50689328
score: 0
type: Comment

http://stackoverflow.com/a/50586549
has body: try this, df['total'] =df.groupby('subject')['val'].transform('sum') or df['total2'] =df.groupby('subject')['val'].transform(lambda x:x[x.notnull()].unique()) #this will remove NaN records and give you unique element in each group Output: subject val total total2 0 1 NaN 2.0 2.0 1 1 2.0 2.0 2.0 2 1 NaN 2.0 2.0 3 2 NaN 7.0 7.0 4 2 NaN 7.0 7.0 5 2 7.0 7.0 7.0 6 3 NaN 10.0 10.0 7 3 NaN 10.0 10.0 8 3 10.0 10.0 10.0
has comment: http://stackoverflow.com/comment/88182666
downvote count: 0
has comment: http://stackoverflow.com/comment/88183421
answers question: http://stackoverflow.com/q/50586501
type: Answer
score: 1
upvote count: 1

google-places-api
tags question: http://stackoverflow.com/q/50573658
tags question: http://stackoverflow.com/q/50616048
type: Tag
tags question: http://stackoverflow.com/q/50644983
tag name: google-places-api

http://stackoverflow.com/comment/88188449
score: 1
comment on: http://stackoverflow.com/q/50589400
has text: Can you post the trace for the error? I can't reproduce it from the model snippet, LeakyReLU works properly.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88230544
comment on: http://stackoverflow.com/q/50610066
has text: can you show your code
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50607037
linked to: http://stackoverflow.com/q/30379488
has body: I have a file object file that I opened with: with open("text.txt","rb") as file: # read some line file.write("texte") # I know that doesn't work I just want to know if I can open this file again, because Python has all the information about it, but it says that this file is closed. I am trying to read some lines in the file and at the end, I will write a new line at the end of file, so I want to reopen this file in append mode. >>> with open("test.txt","wb") as fich: ... fich.write("test In ") ... >>> fich <closed file 'test.txt', mode ‘wb' at 0x7f3f49a3a4b0> >>> fich.open Traceback (most recent call last): File “<stdin>", line 1, in <module> I am calling a function that takes the file handle as parameter, so I can't reuse the open as the first time, because the name of the file is unkown inside the function. Can I reopen the handle itself? Because I can use the same method and reopen it with: with open("filename") as anotherfile:
answer count: 1
has comment: http://stackoverflow.com/comment/88224562
has comment: http://stackoverflow.com/comment/88223825
has comment: http://stackoverflow.com/comment/111374975
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88224285
has comment: http://stackoverflow.com/comment/88223863
has comment: http://stackoverflow.com/comment/88223860
has title: How to reopen a closed file?
type: AnsweredQuestion
score: 7
tagged with: file
has comment: http://stackoverflow.com/comment/88223815
downvote count: 1
upvote count: 8
type: Question
has comment: http://stackoverflow.com/comment/88224159
has answer: http://stackoverflow.com/a/50607154
accepted answer: http://stackoverflow.com/a/50607154
has comment: http://stackoverflow.com/comment/88224015

http://stackoverflow.com/comment/88122054
type: Comment
has text: is `name` an attribute ?
comment on: http://stackoverflow.com/q/50555630
score: 0
type: QuestionComment

http://stackoverflow.com/q/50694890
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50695606
type: Question
tagged with: raspberry-pi
has body: My question regards SSH on Raspberry Pi. I am able to successfully ssh on to the Pi using the command: sudo ssh pi@&lt;ipaddress&gt; and then entering the password. Let's say I have a Python script file on the Pi that I execute over SSH. Let's say the script reads: import time while True: print('Hello') time.sleep(1) This will print 'Hello' every second whilst the terminal/command prompt window is still open (that is, the computer I am using to access the Pi is running and the SSH session remains open). If I close the connection, then the code will stop being executed on the Pi. Is there a way I can use SSH to keep the code running on the Pi even when I close the window running SSH on the computer I am using to access the Pi? As in the Pi will keep printing 'Hello' even after I shut down my computer. Maybe by entering a command to open a terminal window on the Pi itself and running the script in that terminal window? Is there a way this can be done? Thanks
has comment: http://stackoverflow.com/comment/88399153
accepted answer: http://stackoverflow.com/a/50695606
score: 0
answer count: 1
tagged with: ssh
has title: Start terminal on Raspberry Pi using SSH
has comment: http://stackoverflow.com/comment/88399537
has comment: http://stackoverflow.com/comment/88399195
tagged with: terminal
tagged with: python

http://stackoverflow.com/q/50552059
type: Question
has answer: http://stackoverflow.com/a/74723229
tagged with: anaconda
has comment: http://stackoverflow.com/comment/88115112
has answer: http://stackoverflow.com/a/53685910
upvote count: 11
tagged with: batch-file
has answer: http://stackoverflow.com/a/51766068
has comment: http://stackoverflow.com/comment/90490275
possible better answer: http://stackoverflow.com/a/51736838
answer count: 7
has comment: http://stackoverflow.com/comment/88114995
has title: How to create a conda environment shortcut on Windows
favorite count: 0
has comment: http://stackoverflow.com/comment/88116741
has body: With Anaconda installed I got a anaconda base shortcut on Windows startmanu. To open the virtualenv I created (e.g., myenv), I have to click the anaconda base and type in activate myenv in the opened cmd window. How can I create a shortcut to get to myenv with one-click, without open-and-typing like the above? I've tried to create a copy of the base shortcut and change its command property i.e., %windir%\System32\cmd.exe "/K" C:\Programs\anaconda3\Scripts\activate.bat C:\Programs\anaconda3\envs\myenv. It does open the myenv cmdline, but seemed lost some buildin command,like conda. I guess I need a little bit help on Windows bat skills.
has answer: http://stackoverflow.com/a/76545804
tagged with: windows
accepted answer: http://stackoverflow.com/a/53365090
has comment: http://stackoverflow.com/comment/88117762
tagged with: python
score: 11
has comment: http://stackoverflow.com/comment/88115184
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/59619692
downvote count: 0
has answer: http://stackoverflow.com/a/51736838
has answer: http://stackoverflow.com/a/53365090

http://stackoverflow.com/a/50559306
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50559252
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88129136
downvote count: 0
answers question: http://stackoverflow.com/q/50559252
score: 1
type: Answer
has body: Right, one amendment is needed to achieve your stated aim: replace: start_time() with starting = start_time() when a function is called that returns a value without an explicit place for that value to be put python in effect throws away the value.

http://stackoverflow.com/q/50670553
type: AnsweredQuestion
tagged with: c#
score: 3
accepted answer: http://stackoverflow.com/a/50671198
tagged with: http-post
tagged with: encoding
answer count: 1
downvote count: 0
has title: Posting base64 converted image data
favorite count: 0
has body: What will be equilent of this python code in C#. This opens image from file and converts into base64 encoded string and sends the POST request. Please help. #!/usr/bin/python import requests import base64 import json # Sample image file is available at http://plates.openalpr.com/ea7the.jpg IMAGE_PATH = '/tmp/sample.jpg' SECRET_KEY = 'sk_DEMODEMODEMODEMODEMODEMO' with open(IMAGE_PATH, 'rb') as image_file: img_base64 = base64.b64encode(image_file.read()) url = 'https://api.openalpr.com/v2/recognize_bytes?recognize_vehicle=1&amp;country=us&amp;secret_key=%s' % (SECRET_KEY) r = requests.post(url, data = img_base64) print(json.dumps(r.json(), indent=2))
tagged with: python
has answer: http://stackoverflow.com/a/50671198
upvote count: 3
type: Question

http://stackoverflow.com/comment/88307042
type: Comment
type: QuestionComment
has text: Use [How to debug small programs (#3)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) to check if you got data to create the boxes in the first place.
score: 0
comment on: http://stackoverflow.com/q/50647855

http://stackoverflow.com/comment/88144961
type: AnswerComment
comment on: http://stackoverflow.com/a/50566890
score: 0
type: Comment
has text: It didn't work for me. I removed the type of arguments passwed to the function, but then I got a message that melt() was expecting 5 arguments and that I passed only 3 from my call.

http://stackoverflow.com/comment/88281443
has text: You've got someone else's code and a task to do with it, and now you're struggling to figure out how it works. To get an answer here you need to simplify your question and provide all the info needed to answer. Here are the guidelines on how to create a minimal, complete and verifiable example: https://stackoverflow.com/help/mcve
comment on: http://stackoverflow.com/q/50635554
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50564085
tagged with: python-3.4
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88138478
tagged with: python
has answer: http://stackoverflow.com/a/50565709
has body: this should take a line and display it in a txt box, this should work but there must be a mistake that i can't see. def show_indiv(): with open("data/tournamentdatae1.txt",'r') as f: event = combo_event.get() indivcombo = combo_individual.get() if event == 'Event 1' and indivcombo == 'Individual 1': with open('data/tournamentdatae1.txt', 'r') as f: for i,line in enumerate(f,1): if i == 21: indiv_txt.insert(0.0, line)
has comment: http://stackoverflow.com/comment/88138526
type: AnsweredQuestion
tagged with: tk-toolkit
type: Question
has title: Display data in a Tk text box without the ['\n']
accepted answer: http://stackoverflow.com/a/50565709
has comment: http://stackoverflow.com/comment/88141406

http://stackoverflow.com/comment/89106686
comment on: http://stackoverflow.com/a/50567308
type: AnswerComment
has text: It is using `X_min` and `X_max` from the training set (the one that was used to fit `min_max_scaler`)
type: Comment
score: 1

http://stackoverflow.com/q/50656519
favorite count: 0
has body: I am attending the 'Intro to Computer Science' at Udacity. I am at the final project of the course. I have been trying to solve the problem with following codes in Python - # --------------------------- # # Intro to CS Final Project # # Gaming Social Network # # --------------------------- # # # Background # ========== # You and your friend have decided to start a company that hosts a gaming # social network site. Your friend will handle the website creation (they know # what they are doing, having taken our web development class). However, it is # up to you to create a data structure that manages the game-network information # and to define several procedures that operate on the network. # # In a website, the data is stored in a database. In our case, however, all the # information comes in a big string of text. Each pair of sentences in the text # is formatted as follows: # # &lt;user&gt; is connected to &lt;user1&gt;, ..., &lt;userM&gt;.&lt;user&gt; likes to play &lt;game1&gt;, ..., &lt;gameN&gt;. # # For example: # # John is connected to Bryant, Debra, Walter.John likes to play The Movie: The Game, The Legend of Corgi, Dinosaur Diner. # # Note that each sentence will be separated from the next by only a period. There will # not be whitespace or new lines between sentences. # # Your friend records the information in that string based on user activity on # the website and gives it to you to manage. You can think of every pair of # sentences as defining a user's profile. # # Consider the data structures that we have used in class - lists, dictionaries, # and combinations of the two (e.g. lists of dictionaries). Pick one that # will allow you to manage the data above and implement the procedures below. # # You may assume that &lt;user&gt; is a unique identifier for a user. For example, there # can be at most one 'John' in the network. Furthermore, connections are not # symmetric - if 'Bob' is connected to 'Alice', it does not mean that 'Alice' is # connected to 'Bob…
has title: How to finish the code using recursion?
tagged with: python
has comment: http://stackoverflow.com/comment/88358474
type: AnsweredQuestion
tagged with: recursion
upvote count: 0
possible better answer: http://stackoverflow.com/a/50676097
accepted answer: http://stackoverflow.com/a/50656638
has answer: http://stackoverflow.com/a/50676097
has comment: http://stackoverflow.com/comment/88323372
has comment: http://stackoverflow.com/comment/88323406
type: Question
has comment: http://stackoverflow.com/comment/88323173
has answer: http://stackoverflow.com/a/50656638
score: -1
answer count: 2
downvote count: 1
has comment: http://stackoverflow.com/comment/88323098

http://stackoverflow.com/comment/88387074
type: QuestionComment
has text: Thank you @PatrickArtner ! I managed to sort the data, but I cannot find examples on how to average data for each cluster
comment on: http://stackoverflow.com/q/50684104
score: 0
type: Comment

http://stackoverflow.com/a/50686033
has body: ✓ @anvd, as I understood from your problem, you want to search the presence of values of dictionary d inside the lists rating1 &amp; rating2. Please comment, if I'm wrong or the solution that I provided below doesn't satisfy your need. I will suggest you to create 1 more dictionary d_lists that maps the name of lists to the original list objects. Steps: ✓ Take each key(list name) from d. ✓ Find the existence of this key in the d_lists. ✓ Take the corresponding list object from d_lists. ✓ Find the existence of value pointed by key in d inside picked list object. ✓ If element found then stop iteration and search the presence of next value in d. ✓ Print relevant messages. Here is your modified code (with little modification) I have shown another good example later after the below code example. rating_1 = ['nlo', 'yes'] rating_2 = ['no', 'yes'] # Creating a dictionary that maps list names to themselves (original list object) d_lists = { "rating_1": rating_1, "rating_2": rating_2, } # Creating a dictionary that maps list to the item to be searched # We just want to check whether 'rating_1' &amp; 'rating_2' contains 'no' or not d = {'rating_2': u'no', 'rating_1': u'no'} # Search operation using loop for list_name in d: if list_name in d_lists: found = False for item in d_lists[list_name]: if item == d[list_name]: found = True break if found: print "'" + d[list_name] + "' exists in", d_lists[list_name]; else: print "'" + d[list_name] + "' doesn't exist in", d_lists[list_name] else: print "Couldn't find", list_name Output: 'no' exists in ['no', 'yes'] 'no' doesn't exist in ['nlo', 'yes'] Now, have a look at another example. Another big example: rating_1 = ['no', 'yes', 'good', 'best'] rating_2 = ['no', 'yes', 'better', 'worst', 'bad'] fruits = ["apple", "mango", "pineapple"] # Creating a dictionary that maps list names to themselves (original list object) d_lists = { "rating_1": rating_1, "rating_2": rating_2, "fruits": fruits, } # Creating a dictionary that maps list to th…
downvote count: 1
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/50684708
type: Answer

http://stackoverflow.com/a/50601486
has comment: http://stackoverflow.com/comment/88212242
score: 0
has comment: http://stackoverflow.com/comment/88212381
has body: Try this: def round(number, nearest): if ((number % nearest) / nearest) &lt; 0.5: return (number - (number % nearest)) else: return ((number - (number % nearest)) + nearest) Explanation: The if checks if the the difference between the number and the most previous multiple of nearest is less than half of nearest. If it is, it means that the number needs to be rounded down, which is why, if it's True, it returns the most previous multiple of nearest. If it's False, it returns (the most previous multiple of nearest) + nearest.
type: Answer
answers question: http://stackoverflow.com/q/50601394

function
tags question: http://stackoverflow.com/q/50654215
tags question: http://stackoverflow.com/q/50581063
tags question: http://stackoverflow.com/q/50615723
tags question: http://stackoverflow.com/q/50696080
tags question: http://stackoverflow.com/q/50604799
tag name: function
tags question: http://stackoverflow.com/q/50566527
tags question: http://stackoverflow.com/q/50672238
tags question: http://stackoverflow.com/q/50543696
tags question: http://stackoverflow.com/q/50659747
tags question: http://stackoverflow.com/q/50620029
tags question: http://stackoverflow.com/q/50593476
tags question: http://stackoverflow.com/q/50615071
tags question: http://stackoverflow.com/q/50599045
tags question: http://stackoverflow.com/q/50591822
tags question: http://stackoverflow.com/q/50642566
tags question: http://stackoverflow.com/q/50686608
tags question: http://stackoverflow.com/q/50646663
tags question: http://stackoverflow.com/q/50592678
tags question: http://stackoverflow.com/q/50549536
tags question: http://stackoverflow.com/q/50542514
tags question: http://stackoverflow.com/q/50691805
tags question: http://stackoverflow.com/q/50573813
tags question: http://stackoverflow.com/q/50668894
tags question: http://stackoverflow.com/q/50588820
tags question: http://stackoverflow.com/q/50652561
type: Tag
tags question: http://stackoverflow.com/q/50671868
tags question: http://stackoverflow.com/q/50659519
tags question: http://stackoverflow.com/q/50553579
tags question: http://stackoverflow.com/q/50624105
tags question: http://stackoverflow.com/q/50662998
tags question: http://stackoverflow.com/q/50626625
tags question: http://stackoverflow.com/q/50664769
tags question: http://stackoverflow.com/q/50563064
tags question: http://stackoverflow.com/q/50622857
tags question: http://stackoverflow.com/q/50653351
tags question: http://stackoverflow.com/q/50541979
tags question: http://stackoverflow.com/q/50543300
tags question: http://stackoverflow.com/q/50565080
tags question: http://stackoverflow.com/q/50657770

http://stackoverflow.com/q/50668453
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/50668565
type: AnsweredQuestion
score: 1
upvote count: 1
has body: I need to draw a curve passing through the points (0,0) , (20,10) , (0,50). As there two points with the same x coordinate, I decided to parametrize x and y with a parameter t and since I need the equation of this polynomial (of the curve) I decided tot use Lagrange. Well, the plot is really weird, it prints the points, but there is no curve: x_parabola = np.array([0, 20, 0]) # array for x y_parabola = np.array([0, 10, 50]) # array for y plt.figure() u = plt.plot(x_parabola,y_parabola,'ro') # plot the points t = np.linspace(0, 1, len(x_parabola)) # parameter t to parametrize x and y pxLagrange = scipy.interpolate.lagrange(t, x) # X(T) pyLagrange = scipy.interpolate.lagrange(t, y) # Y(T) n = 100 ts = np.linspace(t[0],t[-1],n) xLagrange = pxLagrange(ts) # lagrange x coordinates yLagrange = pyLagrange(ts) # lagrange y coordinates plt.plot(xLagrange, yLagrange,'b-',label = "Polynomial") Please, could you show me what is wrong with the code? Thanks in advance!
tagged with: scipy
tagged with: plot
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/50668565
downvote count: 0
answer count: 1
has title: Plot a lagrange polynomial from a set of points PYTHON

http://stackoverflow.com/comment/88131028
has text: @BlackyuSylvean don't use `matrix`, use `array`.
score: 0
comment on: http://stackoverflow.com/a/50550177
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50619867
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88249517
has body: Pandas solution Try using the pandas groupby function then use the pandas apply then write lambda x: in it then, join the new list comprehension with '-': import pandas as pd df = pd.DataFrame({'A':[1,1,1,2,2,3,3], 'B': [124,456,465,46,35,53,33]}) print(df.groupby('A')['B'].apply(lambda x: '-'.join([str(i) for i in x.values])).tolist()) Output: ['124-456-465', '46-35', '53-33']
downvote count: 0
answers question: http://stackoverflow.com/q/50619573

http://stackoverflow.com/comment/88285567
type: Comment
comment on: http://stackoverflow.com/q/50636901
score: 0
type: QuestionComment
has text: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ]

http://stackoverflow.com/comment/88291732
type: Comment
type: QuestionComment
has text: @Rory Daulton The end-of-line character sequence should be '\n'. I want to ignore all occurrences of '^M' anywhere in the text file.
comment on: http://stackoverflow.com/q/50640627
score: 0

http://stackoverflow.com/q/50652473
answer count: 1
accepted answer: http://stackoverflow.com/a/50652619
tagged with: string
has comment: http://stackoverflow.com/comment/88315682
has comment: http://stackoverflow.com/comment/88315756
has comment: http://stackoverflow.com/comment/88318330
has comment: http://stackoverflow.com/comment/88315735
tagged with: python
tagged with: regex
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88315689
has answer: http://stackoverflow.com/a/50652619
has body: I have extracted the text from a Credit Card Statement, sliced for only the transactions within the entire month, and saved that within a list. The list is 404 strings long, and an excerpt of that list is shown below: ['Apr', '27', 'UBER', 'TECHNOLOGIES', 'INC866-576-1039CA', '$10.93', 'Apr', '27', 'UBER', 'TECHNOLOGIES', 'INC866-576-1039CA', '$11.38', 'Apr', '28', 'COSTCO', 'WHSE', '#1018HOUSTONTX', '$105.02'] As you can see, the list follows a standard format where one transaction is comprised of 3 pieces: the Date (2 separate strings), the Description (2-5 strings), and the Amount (1 string). My goal is to create a Pandas Dataframe based upon this information, but I am having trouble figuring out a way to manipulate the strings to properly segment each category (Date, Description, Amount). I believe I need to use some combination of a Regex and a loop to accomplish this. Per comments, The raw data that is extracted from the credit card statement (PDF) is also show below: " \nApr 27\nUBER TECHNOLOGIES\nINC866-576-1039CA\n$10.93\nApr 27\nUBER TECHNOLOGIES\nINC866-576-1039CA\n$11.38\nApr 28\nCOSTCO WHSE #1018HOUSTONTX\n$105.02\n"
type: Question
tagged with: dataframe
has title: String Manipulation to Dataframe
has comment: http://stackoverflow.com/comment/88315731
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/88315781

http://stackoverflow.com/comment/88400800
type: Comment
comment on: http://stackoverflow.com/q/50695812
has text: Welcome to stackoverflow.com. Please take some time to read the [help pages](https://stackoverflow.com/help), especially the sections named ["What topics can I ask about here?"](https://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](https://stackoverflow.com/help/dont-ask). Also please [take the tour](https://stackoverflow.com/tour) and read about [how to ask](https://stackoverflow.com/help/how-to-ask) good questions. Lastly please learn how to create a [Minimal, Complete, and Verifiable Example](https://stackoverflow.com/help/mcve).
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88234295
has text: @glibdud The only code that has an issue is in the bcs() function. The rest of the code works properly, and I included it so that anyone else could try running the same program that I am running.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50607425

http://stackoverflow.com/a/54994258
downvote count: 0
answers question: http://stackoverflow.com/q/50657368
type: Answer
has body: The problem is in your Dockerfile the python:3.6-alpine is a reduced version of Python and the mysqlclient is looking for a development headers and libraries. It is the official page Pypi: mysqlclient Prerequisites: You may need to install the Python and MySQL development headers and libraries... My solution: In my case I had the slim version and I changed to a Python 3 (3.7) and it works. #FROM python:3-slim FROM python:3
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/114912513

http://stackoverflow.com/comment/88141141
has text: Seek to specific line, and add your content while the file is opened in append mode
comment on: http://stackoverflow.com/q/50565297
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88407826
has text: Side point: `.ix` access is now depreciated. Use `.loc` or `.iloc` instead.
score: 0
comment on: http://stackoverflow.com/q/50691590
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50608021
upvote count: 2
possible better answer: http://stackoverflow.com/a/50608188
has answer: http://stackoverflow.com/a/50608188
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50608563
type: Question
tagged with: numpy
tagged with: numpy-ndarray
answer count: 2
tagged with: arrays
downvote count: 0
has body: Given an n-dimensional numpy array. Now an axis and corresponding index is given. All elements in that particular axis-index should be replaced by given value. Example of an three-dimensional array: &gt;&gt;a = np.ones((2,2,2)) array([[[ 1., 1.], [ 1., 1.]], [[ 1., 1.], [ 1., 1.]]]) Given axis=1, index=0. All elements in this axis-index needs to be zero. &gt;&gt;a array([[[ 0., 0.], [ 1., 1.]], [[ 0., 0.], [ 1., 1.]]])
favorite count: 0
has answer: http://stackoverflow.com/a/50608563
has title: Replace elements of particular axis index in n-dimensional numpy array

visual-studio
tags question: http://stackoverflow.com/q/50584900
type: Tag
tag name: visual-studio

http://stackoverflow.com/comment/88323590
type: Comment
comment on: http://stackoverflow.com/q/50656813
type: QuestionComment
has text: Please don't post to off-site pictures of information relevant to your question.
score: 0

http://stackoverflow.com/q/50626539
tagged with: python
downvote count: 0
has body: I'm following a course on EdX on Programming with Python in Data Science. When using a given function to plot the results of my linear regression model, the graph seems very off with all the scatter points clustered at the bottom and the regression line way up top. I'm not sure if it is the defined function drawLine to be incorrect or sth else is wrong with my modeling process. here is the defined function def drawLine(model, X_test, y_test, title, R2): fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(X_test, y_test, c='g', marker='o') ax.plot(X_test, model.predict(X_test), color='orange', linewidth=1, alpha=0.7) title += " R2: " + str(R2) ax.set_title(title) print(title) print("Intercept(s): ", model.intercept_) plt.show() here is the code I wrote import pandas as pd import numpy as np import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn import linear_model from sklearn.model_selection import train_test_split matplotlib.style.use('ggplot') # Look Pretty # Reading in data X = pd.read_csv('Datasets/College.csv', index_col=0) # Wrangling data X.Private = X.Private.map({'Yes':1, 'No':0}) # Splitting data roomBoard = X'Room.Board' accStudent = X'Accept' X_train, X_test, y_train, y_test = train_test_split(roomBoard, accStudent, test_size=0.3, random_state=7) # Training model model = linear_model.LinearRegression() model.fit(X_train, y_train) score = model.score(X_test, y_test) # Visualise results drawLine(model, X_test, y_test, "Accept(Room&amp;Board)", score) the data I used can be found here Thank you for your time. Any help or advice is appreciated.
tagged with: machine-learning
type: AnsweredQuestion
tagged with: linear-regression
score: 1
tagged with: matplotlib
has title: Unable to plot regression line correctly with scatter plot in Python
type: Question
upvote count: 1
answer count: 1
tagged with: scikit-learn
favorite count: 0
has answer: http://stackoverflow.com/a/50627177
accepted answer: http://stackoverflow.com/a/50627177

http://stackoverflow.com/q/50617254
has comment: http://stackoverflow.com/comment/88257140
tagged with: python
answer count: 0
has title: Can't import PunktSentenceTokenizer from nltk.corpus
type: Question
tagged with: nltk
has body: I tried to import as: from nltk.corpus import PunktSentenceTokenizer This gave me the below error: ImportError: cannot import name 'PunktSentenceTokenizer' Now I tried to import it as: tokenizer = nltk.tokenize.punkt.PunktSentenceTokenizer() but the below code gives error again: tagged_sentences = nltk.corpus.treebank.tagged_sents() cutoff = int(.75 * len(tagged_sentences)) training_sentences = DataPrep.train_news['Statement'] print(training_sentences) custom_sent_tokenizer =tokenizer.tokenize(training_sentences) tokenized=custom_sent_tokenizer error is: #TypeError: expected string or bytes-like object
tagged with: pos-tagger
score: 0
upvote count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88260741
type: UnansweredQuestion

http://stackoverflow.com/comment/88302764
comment on: http://stackoverflow.com/q/50645240
type: Comment
score: 0
has text: @SCoder after looking at the documentation, it appears to be a bug in pandas 0.23.0
type: QuestionComment

http://stackoverflow.com/q/50657545
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50657612
tagged with: python-3.x
has body: I have a dataframe like below. The 'LATENCY' column has both numerical and 'NA' characters, that makes groupby() complex. DEVICE START_PRICE LATENCY 0 ab.fxx.in 500 NA 1 ab.fxx.in 500 1 2 ab.fxx.in 500 5 3 kddo.fxx.in 500 NA 4 kddo.fxx.in 500 5 5 kddo.fxx.in 533 3 6 kddo.fxx.in 533 NA I wanted to group the dataframe by 'DEVICE' value to the sum of 'LATENCY' - by bypassing 'NA' values. I should get the output as below. DEVICE ab.fxx.in 6 kddo.fxx.in 8
tagged with: python
type: AnsweredQuestion
upvote count: 2
accepted answer: http://stackoverflow.com/a/50657612
type: Question
has title: Pandas dataframe groupby sum while ignoring non-numerical values
tagged with: dataframe
tagged with: pandas-groupby
tagged with: pandas
score: 2

http://stackoverflow.com/q/50587332
tagged with: command-line
has body: C:\Windows\system32&gt;c:\mongodb\bin\mongo.exe --port=14014 MongoDB shell version v3.4.7 connecting to: mongodb://127.0.0.1:14014/ 2018-05-29T20:10:06.939+0530 W NETWORK [thread1] Failed to connect to 127.0.0.1:14014 after 5000ms milliseconds, giving up. 2018-05-29T20:10:06.939+0530 E QUERY [thread1] Error: couldn't connect to server 127.0.0.1:14014, connection attempt failed : connect@src/mongo/shell/mongo.js:237:13 @(connect):1:6 exception: connect failed I am having an issue connecting to a database that I am running as windows service locally at port number 14014. I am able to see that the service is running successfully using the Windows Task Manager and I am also able to access it using Python. But I am not able to connect it using the command line by typing the following command: C:> C:\mongodb\bin\mongo.exe --port=14014 However, i am able to connect to another database at port 27017 that I am running using mongod.exe. This is very baffling! I hope someone can help me out here! I am also attaching below the log from database service being run at port 14014. 2018-05-29T20:06:00.169+0530 I CONTROL [main] Trying to start Windows service 'MongoDB' 2018-05-29T20:06:00.170+0530 I CONTROL [initandlisten] MongoDB starting : pid=6964 port=14041 dbpath=C:\Users\Lubna\Desktop\My Naseef\My Freelancing\mongodatabase\db 64-bit host=Lubna-PC 2018-05-29T20:06:00.170+0530 I CONTROL [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2 2018-05-29T20:06:00.171+0530 I CONTROL [initandlisten] db version v3.4.7 2018-05-29T20:06:00.171+0530 I CONTROL [initandlisten] git version: cf38c1b8a0a8dca4a11737581beafef4fe120bcd 2018-05-29T20:06:00.171+0530 I CONTROL [initandlisten] OpenSSL version: OpenSSL 1.0.1u-fips 22 Sep 2016 2018-05-29T20:06:00.171+0530 I CONTROL [initandlisten] allocator: tcmalloc 2018-05-29T20:06:00.171+0530 I CONTROL [initandlisten] modules: none 2018-05-29T20:06:00.171+0530 I CONTROL [initandlisten] build environment: 2018-05-29T20:06:00.171+0530 I CONTROL…
has comment: http://stackoverflow.com/comment/88184031
type: AnsweredQuestion
has title: Cannot connect to a service using mongo shell
type: Question
tagged with: mongodb
has answer: http://stackoverflow.com/a/50587439
answer count: 1
accepted answer: http://stackoverflow.com/a/50587439
score: 0
tagged with: windows
tagged with: python

http://stackoverflow.com/q/50673212
has answer: http://stackoverflow.com/a/50673273
has comment: http://stackoverflow.com/comment/88356210
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50673298
has comment: http://stackoverflow.com/comment/88356126
has title: How to get the data from function inside one file to another file
has answer: http://stackoverflow.com/a/50673577
tagged with: import
type: Question
tagged with: python-import
has comment: http://stackoverflow.com/comment/88356196
has body: I have to import some value from one file to another file. I have a function name myFunc in second.py where i have a variable name 'a'. Now I want to display this value in first.py file inside main function. first.py ------- import os import second.py import * def main(): //here i need to print from another file if __name__ == '__main__': main() second.py --------- import os def myFunc(var1, var2): a = 'test user'
tagged with: python-2.7
score: 0
answer count: 3
tagged with: python-module

http://stackoverflow.com/a/50678179
has comment: http://stackoverflow.com/comment/88367040
type: Answer
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/88366414
accepted answer of: http://stackoverflow.com/q/50677892
has comment: http://stackoverflow.com/comment/88367002
answers question: http://stackoverflow.com/q/50677892
type: AcceptedAnswer
downvote count: 0
has body: my_tuple = tuple(my_list) creates an instance of the class tuple from my_list object. It's not quite what a type casting like (tuple)my_list does in C since a new object is created. my_tuple = tuple(my_list) is closer to the C++ my_tuple = new Tuple(my_list).

http://stackoverflow.com/q/50645444
upvote count: 0
has answer: http://stackoverflow.com/a/50645568
duplicate of: http://stackoverflow.com/q/2612802
type: Question
has comment: http://stackoverflow.com/comment/88301418
has comment: http://stackoverflow.com/comment/88301582
linked to: http://stackoverflow.com/q/2612802
has title: Why value of input list is getting changed?
duplicate of: http://stackoverflow.com/q/19951816
downvote count: 3
answer count: 1
linked to: http://stackoverflow.com/q/19951816
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88301485
score: -3
tagged with: python
has body: As I don't know what title should be given to my this confusion so I'm putting it just a doubt a = [1,2,3,4,5] b = a for i in range(len(a)): c = (i - 4) print(a) print(b) b[c] = a[i] print(a) print(b) output [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] [1, 1, 3, 4, 5] [1, 1, 3, 4, 5] [1, 1, 3, 4, 5] [1, 1, 3, 4, 5] [1, 1, 1, 4, 5] [1, 1, 1, 4, 5] ... why values of list a is getting in each step of loop?

http://stackoverflow.com/comment/88131526
comment on: http://stackoverflow.com/q/50560399
score: 0
has text: Is output correct?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50651310
upvote count: 1
score: 1
has body: I'm assuming that each of these is a string, you can do the following using no libraries in both python 2 and 3 def mean(numbers): return float(sum(numbers)) / max(len(numbers), 1) def timestamp_to_millis(timestamp): hour, min, sec = map(float, timestamp.split(':')) mills = (((hour * 60 + min) * 60) + sec) * 1000 return millis my_data = # [ timestamps ... ] my_mean = mean(map(timestamp_to_millis, my_data))
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50651216

http://stackoverflow.com/comment/88310355
score: 1
comment on: http://stackoverflow.com/q/50649595
type: Comment
type: QuestionComment
has text: The underlying API allows for requesting a single deal by its ID; you might want to try using something like `requests` to use it directly, or another module (for example, python-pipedrive) which supports such calls.

http://stackoverflow.com/q/50691903
has comment: http://stackoverflow.com/comment/88393583
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/88393350
has comment: http://stackoverflow.com/comment/88393352
accepted answer: http://stackoverflow.com/a/50692344
score: 0
has title: I can't load polls/detail.html
answer count: 1
has body: hi guys I can't load polls/detail.html I am currently studying Django tutorials part3 If I enter http: // localhost: 8000 / polls / index.html in the browser address bar, I get a page not found response and The browser shows me the following text Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: polls/ [name='index'] polls/ <int:question_id>/ [name='detail'] polls/ <int:question_id>/results/ [name='results'] polls/ <int:question_id>/vote/ [name='vote'] admin/ The current path, polls/index.html, didn't match any of these I think there's a problem with the route this is my view.py code from django.shortcuts import get_object_or_404, render from .models import Question #... def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = { 'latest_question_list': latest_question_list } return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) polls/tamplates/polls/detail.html {{ question.question_text }} {% for choice in question.choice_set.all %} {{ choice.choice_text }} {% endfor %} polls/templates/polls/index.html {% if latest_question_list %} {% for question in latest_question_list %} {{ question.question_text }} {% endfor %} {% else %} No polls are available. {% endif %}
has answer: http://stackoverflow.com/a/50692344
tagged with: django
tagged with: python

http://stackoverflow.com/q/50649827
has answer: http://stackoverflow.com/a/50769555
has comment: http://stackoverflow.com/comment/88982881
score: 5
has answer: http://stackoverflow.com/a/52777490
downvote count: 0
has comment: http://stackoverflow.com/comment/88311243
possible better answer: http://stackoverflow.com/a/77423443
favorite count: 0
has answer: http://stackoverflow.com/a/77423443
answer count: 5
accepted answer: http://stackoverflow.com/a/50769555
has body: After reinstalling anaconda, I set up a new Pycharm project. When I debug one of my python scripts it get this error: pydev debugger: process 12636 is connecting Process finished with exit code -1073741819 (0xC0000005) This only happens when I debug. Any advice? For reference, these are the software versions I am currently using: Python version: 3.5 Pycharm version: 2017.3 Anaconda Navigator version:1.8.7
has answer: http://stackoverflow.com/a/59328700
tagged with: python
has title: Pycharm debugger can't start: finished with exit code -1073741819 (0xC0000005)
type: AnsweredQuestion
tagged with: pycharm
linked to: http://stackoverflow.com/q/29326171
has answer: http://stackoverflow.com/a/56296925
type: Question
tagged with: debugging
tagged with: anaconda
upvote count: 5

http://stackoverflow.com/q/50662457
has comment: http://stackoverflow.com/comment/88346686
answer count: 1
downvote count: 1
has title: Poloniex API using requests, returnBalances works, but returnTradeHistory does not
tagged with: poloniex
favorite count: 0
has body: I'm trying to access the Poloniex API using requests. The returnBalances code works, but the returnTradeHistory code does not. The returnTradeHistory is commented out in the example. Data is returned for returnBalances but not for returnTradeHistory. I know the whole APIKey and secret code is working because I am getting accurate returnBalances data. So why is returnTradeHistory not working? from time import time import urllib.parse import hashlib import hmac import requests import json APIKey=b"stuff goes in here" secret=b"stuff goes in here" url = "https://poloniex.com/tradingApi" # this works and returns data payload = { 'command': 'returnBalances', 'nonce': int(time() * 1000), } # this does not work and does not return data #payload = { # 'command': 'returnTradeHistory', # 'currencyPair': 'BTC_MAID', # 'nonce': int(time() * 1000), #} paybytes = urllib.parse.urlencode(payload).encode('utf8') sign = hmac.new(secret, paybytes, hashlib.sha512).hexdigest() headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Key': APIKey, 'Sign': sign, } r = requests.post(url, data=paybytes, headers=headers) fulldata=r.content data = json.loads(fulldata) print(data)
has comment: http://stackoverflow.com/comment/88344938
has comment: http://stackoverflow.com/comment/88348069
upvote count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51023030
score: -1
type: Question

http://stackoverflow.com/comment/88303664
comment on: http://stackoverflow.com/a/50645879
has text: @Chris_Rands yes, this is a very poorly written question. However it's clear that OP is looking for a short form of switch. I don't see any reason for a switch command generally, `if ... elif` does the same job.
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/comment/88191866
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50585915
type: Comment
has text: Hey thank you for the answer. What should I do if I want both 'AA' and 'AE' to be contained in each position? Meaning, Boolean check whether row 0 and column 0 contains both 'AA' and 'AE' substr. Boolean check whether row 0 and column 1 contains both 'AA' and 'AE' and so on..

http://stackoverflow.com/comment/108562477
score: 1
comment on: http://stackoverflow.com/a/57609029
type: AnswerComment
has text: Worked for me. Good idea to reflect tables from the database because schema definitions might not exist in the code any more when migration is old.
type: Comment

http://stackoverflow.com/q/50644315
favorite count: 0
upvote count: 1
has body: In a dictionary with information about a string in a text file, where keys are the strings and values are the names of the files. Dict1 = {'str1A':'file1', 'str1B':'file1', 'str1C':'file1', 'str1D':'file1', 'str2A':'file2', 'str2B':'file2', 'str2C':'file2', 'str2D':'file2', 'str2D':'file2', 'str3A':'file3', 'str3B':'file3','str3C':'file3', 'str3D':'file3', 'str3D':'file3' , 'str4A':'file4', 'str4B':'file4', 'str4C':'file4', 'str4D':'file4', 'str4E':'file4'} Another dictionary contains information about the best match for the strings from the text. Dict2 = {'str1A':'jump', 'str1B':'fly', 'str1C':'swim', 'str2A':'jump', 'str2B':'fly', 'str2C':'swim', 'str2D':'run', 'str3A':'jump', 'str3B':'fly', 'str3C':'swim', 'str3D':'run'} The third dictionary contains information about the percentage of occurrence of the string in the text. Dict3 = {'str1A':'90', 'str1B':'60', 'str1C':'30', 'str2A':'70', 'str2B':'30', 'str2C':'60', 'str2D':'40', 'str3A':'10', 'str3B':'90', 'str3C':'70', 'str3D':'90'} Now my aims are to use the information of these different dictionaries to generate a dataframe like this: jump fly swim run file1 90 60 30 NA file2 70 30 60 40 file3 10 90 70 90 To this, I started the script but I am stuck: col_file = ['str', 'file'] df_origin = pd.DataFrame(Dict1.items(), columns=col_file) #print df_origin col_bmatch = ['str', 'text'] df_bmatch = pd.DataFrame(Dict2.items(), columns=col_bmatch) #print df_bmatch col_percent = ['str', 'percent'] df_percent = pd.DataFrame(Dict3.items(), columns=col_percent) #print df_percent This block was removed from script: df_origin['text'] = df_origin['str'].map(df_bmatch.set_index('str')['text']) df_origin['percent'] = df_origin['str'].map(df_percent.set_index('str')['percent']) And substituted to: data = {} for k, col in Dict1.items(): if k in Dict1 and k not in Dict3: data.setdefault(k, {})[col] = "NA" elif k in Dict1 and k in Dict3: data.setdefault(k, {})[col] = Dict3[k] df = pd.DataFrame(data) print(df) But the final result was…
has answer: http://stackoverflow.com/a/50644457
has title: Merge dictionaries to dataframe get_dummies
type: AnsweredQuestion
score: 1
tagged with: dataframe
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50645005
downvote count: 0
accepted answer: http://stackoverflow.com/a/50644457
possible better answer: http://stackoverflow.com/a/50645005
tagged with: pandas
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/88270903
score: 0
type: AnswerComment
has text: Calculating distance will not yield the correct solution based on my updated understanding of your problem. Find the insertion index using binary search, similar to [this problem](https://leetcode.com/problems/search-in-rotated-sorted-array/description/).
comment on: http://stackoverflow.com/a/50619329
type: Comment

http://stackoverflow.com/comment/88111235
type: QuestionComment
has text: As for the `None`, that's because your `get_rate` method doesn't return anything. See [How is returning the output of a function different from printing it?](//stackoverflow.com/q/750136). As for the `**kwargs`: You put them in the wrong place. They should be used in the `Hourly.__init__` method. And `Employee` shouldn't be calling `super().__init__(**kwargs)` or `super().__init__()` or anything of the sort.
comment on: http://stackoverflow.com/q/50550153
score: 5
type: Comment

http://stackoverflow.com/comment/88225396
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50607507
has text: networkx and pygraphviz

http://stackoverflow.com/a/50575756
has comment: http://stackoverflow.com/comment/88161581
has body: try-except is for catching exceptions. In this scenario, you only account for one exception, ValueError but not TypeError. In order to catch type error, just put one more except block below try. In your case, it would be like this: L = ["29.3", "tea", "1", None, 3.14] D = [] for item in L: try: float(item) D.append(float(item)) except TypeError: # do something with None here except ValueError: D.append(item) print(D) Given that you want to catch multiple exceptions in a single except block, use a tuple of exceptions: L = ["29.3", "tea", "1", None, 3.14] D = [] for item in L: try: float(item) D.append(float(item)) except (ValueError, TypeError): D.append(item) print(D)
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50575665
downvote count: 1
answers question: http://stackoverflow.com/q/50575665
type: AcceptedAnswer
score: 1
type: Answer

http://stackoverflow.com/a/66987170
type: Answer
has comment: http://stackoverflow.com/comment/118409084
upvote count: 1
score: -1
answers question: http://stackoverflow.com/q/50686388
has body: İt is very easy actually. Open command prompt and write: pip install discord.py After that if you want voice: pip install discord.py[voice]
downvote count: 2

http://stackoverflow.com/q/50632708
has answer: http://stackoverflow.com/a/67913251
possible better answer: http://stackoverflow.com/a/55517916
has answer: http://stackoverflow.com/a/64794379
downvote count: 0
tagged with: pyspark
has answer: http://stackoverflow.com/a/55517916
favorite count: 0
tagged with: apache-spark
tagged with: python
answer count: 4
accepted answer: http://stackoverflow.com/a/64794379
upvote count: 2
has answer: http://stackoverflow.com/a/50632892
score: 2
type: AnsweredQuestion
has title: Read SAS file to get meta information
has body: Very new to data science technologies. Currently working on reading a SAS File (.sas7dbat). Able to read the file using : SAS7BDAT('/dbfs/mnt/myMntScrum1/sasFile.sas7bdat') as f: for row in f: print(row) Row prints all the data. When we view SAS files in SAS viewer we can see metadata E.g. Label Information &amp; variable (column names) used on actual data How can I read this metadata in Spark (Databricks) using Python ?
tagged with: databricks
type: Question
tagged with: sas

http://stackoverflow.com/q/50672970
answer count: 1
has title: Pandas functions too slow - optimise with dict/numpy?
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/50673281
tagged with: python
type: AnsweredQuestion
upvote count: 2
type: Question
tagged with: numpy
has body: I have ~10 large df's (5mil+ rows each and growing) that I want to perform calculations on. Doing so with raw pandas even on a super fast AWS machine is unbearably slow. Most functions I need are basic so I'm thinking it would be possible to export from pandas to a dict(?), run my calculations then send it back to a df? The original df is simply a price and size capture of trades as per below (millions of lines as mentioned). size price time 2018-05-18 12:05:11.521 -0.026600 8100.000000 2018-05-18 12:05:11.674 -0.115616 8100.000000 2018-05-18 12:05:11.677 -0.026611 8100.000000 2018-05-18 12:05:11.678 -0.074000 8098.400000 2018-05-18 12:05:11.680 -0.783772 8096.600000 2018-05-18 12:05:11.807 -1.000000 8096.600000 2018-05-18 12:05:12.024 -0.100600 8096.600000 2018-05-18 12:05:12.198 -0.899400 8096.600000 2018-05-18 12:05:12.199 -1.600600 8095.100000 2018-05-18 12:05:14.949 1.000000 8092.600000 2018-05-18 12:05:14.951 0.258350 8092.600000 2018-05-18 12:05:30.191 -0.017330 8092.500000 2018-05-18 12:05:30.192 -0.161670 8088.300000 2018-05-18 12:05:30.712 -0.002000 8088.300000 2018-05-18 12:05:30.773 -0.002000 8088.300000 2018-05-18 12:05:34.688 0.003328 8088.400000 Now I want to apply the following (which acts as an aggregation of the millions of rows to 5 second windows) : df = df.groupby(pd.Grouper(freq='5S')).apply(tick_features).shift()[1:] where tick_features() is: def tick_features(x): if not x.empty: open = x['price'].iloc[0] close = x['price'].iloc[-1] else: open = np.nan close = np.nan high = x['price'].max() low = x['price'].min() volume = np.abs(x['size']).sum() buy_volume = x['size'][x['size'] &gt; 0].sum() sell_volume = np.abs(x['size'][x['size'] &lt; 0].sum()) pct_buy_volume = (buy_volume) / ((buy_volume) + (sell_volume)) pct_sell_volume = (sell_volume) / ((buy_volume) + (sell_volume)) num_trades = x['size'].count() num_buy_trades = (x['size'] &gt; 0).sum() num_sell_trades = (x['size'] &lt; 0).sum() pct_buy_trades = (x['size'] &gt; 0).mean() * 100 pct_sell_…
tagged with: optimization
tagged with: pandas
score: 2
has answer: http://stackoverflow.com/a/50673281

arima
tag name: arima
tags question: http://stackoverflow.com/q/50605037
tags question: http://stackoverflow.com/q/50603091
type: Tag
tags question: http://stackoverflow.com/q/50647248

http://stackoverflow.com/comment/88378046
type: Comment
type: QuestionComment
has text: Do a check that the key you are looking for (e.g., `lines` or `bbox`) is in the dictionary (e.g., a block) before accessing that key.
comment on: http://stackoverflow.com/q/50682486
score: 0

http://stackoverflow.com/a/50594596
has body: There's a built-in that does this for you! It's called str.join, and you call it on the list to be joined. &gt;&gt;&gt; some_list = ["foo", "bar", "spam", "eggs"] &gt;&gt;&gt; ", ".join(some_list) foo, bar, spam, eggs However this doesn't take into account the "and" requirement. That should be fairly simple to handle just by re-writing the last item of the list. &gt;&gt;&gt; some_list = ["foo", "bar", "spam", "eggs"] &gt;&gt;&gt; some_list[-1] = "and " + some_list[-1] &gt;&gt;&gt; ", ".join(some_list) foo, bar, spam, and eggs Write it as a function with: def line_them_up(lst): new_lst = lst[:] # copy the list so we don't change the original new_lst[-1] = "and " + new_list[-1] return ", ".join(new_lst) and get input with input and split. You can even map strip over the resulting list if you like, though it shouldn't be necessary. user_list = map(str.strip, input("Enter a space-separated list: ").split())
type: Answer
answers question: http://stackoverflow.com/q/50594093
score: 0

http://stackoverflow.com/comment/88149680
has text: as I see, that can't give me the mean results by id. The axis 0 or 1 make the mean for [columns or rows](https://stackoverflow.com/questions/22149584/what-does-axis-in-pandas-mean) and somethin `like df.groupby(['id'])[value].mean()` wasn't work too
comment on: http://stackoverflow.com/a/50566967
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88188983
score: 0
type: Comment
type: QuestionComment
has text: Is there anything else that would uniquely identify the table? (i.e. something in the cells?)
comment on: http://stackoverflow.com/q/50589771

http://stackoverflow.com/q/50614701
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has title: python for loop finish
has answer: http://stackoverflow.com/a/50614719
type: Question
has comment: http://stackoverflow.com/comment/88240140
has body: i'm self learning python through out online courses but i ran into a problem . for loop how do i tell python to do something after the for loops is finished ? for example : def mixer(g): print(g) def printer(h): print("end") X = input ("words : ") var2 = "" var1 = X.split() for y in var1: if len(y) &gt; 5: y.upper() var2 += y.upper() + " " mixer(var2) elif len(y) &lt;= 5: y.lower() var2 += y.lower() + " " mixer(var2) that's what i'm trying to do after for loop is done , i want to call a function after the loop , how can u do this ? ## >>> this method didn't work elif y == False: print("false") printer(var2)
answer count: 1
has comment: http://stackoverflow.com/comment/88239290
has comment: http://stackoverflow.com/comment/88239260
score: 0
accepted answer: http://stackoverflow.com/a/50614719

http://stackoverflow.com/comment/88285653
type: QuestionComment
comment on: http://stackoverflow.com/q/50636901
score: 0
has text: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse('This is the index page of the polls application') def detail(request, question_id): return HttpResponse("This is the detail view of the question %s" % question_id) def results(request, question_id): response = "These are the results of the question %s" return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("Vote on question %s" % question_id)
type: Comment

http://stackoverflow.com/comment/88168010
type: Comment
score: 1
has text: In a language with meaningful whitespace it does. The spaces indicate if the return function is inside the for loop or outside it.
type: AnswerComment
comment on: http://stackoverflow.com/a/50579157

http://stackoverflow.com/comment/88351918
score: 0
comment on: http://stackoverflow.com/a/50670936
type: Comment
type: AnswerComment
has text: You can pickle the dictionary and write it to a file, then retrieve it from file on each program run: https://stackoverflow.com/questions/19201290/how-to-save-a-dictionary-to-a-file

http://stackoverflow.com/comment/88193631
score: 1
has text: I added a couple of ways in which they can vary in lines 6/7
comment on: http://stackoverflow.com/q/50592013
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88356473
type: Comment
type: QuestionComment
score: 1
has text: Also why 2018-10-06 is 4 rather than 2
comment on: http://stackoverflow.com/q/50673346

http://stackoverflow.com/q/50546488
tagged with: loops
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/50546644
has body: Ideally, I'd like there to be a step in the "Add Movie" process that confirms that it's an integer for the year, and once it's accepted, to continue back to the main menu once the movie has been added successfully... (I'm not going to ask or into how I'd love for it to save user input data to a file to be pulled from so it's not like I'm making a new entry every time, haha) Here's what I've got... and again, this is my effort after maybe 4 hours of a 27 hour course. I'm hoping you guys can understand what I'm trying to accomplish... but it's just not "finishing" correctly after the "add movie" function... you should see what I'm talking about. import sys import random import os movies = [] def menu(): print("Welcome to 'The Movie Program!!'") print("(A)dd movie to your list") print("(L)ist movies you've added") print("(S)earch for movies in your list") user_input = str(input("Which function would you like to do?:\n\n""Selection: ").capitalize()) while user_input != 'Q': if user_input == 'A': add_movies() elif user_input == 'L': show_movies() elif user_input == 'A': search_movies() else: print("\n\n--Unknown command--Please try again.\n") menu() #user_input = str(input("\nWhich function would you like to do?:\n" # "(A)dd movie to your list\n" # "(L)ist movies you've added\n" # "(S)earch for movies in your list\n\n""Selection: ").capitalize()) def add_movies(): name = (input('What is the title of the movie?: ').title()) director = str(input("Who was the director of this movie?: ").title()) while True: try: year = int(input("What was the release year?: ")) return year break except ValueError: print("Only numbers, please.") year = False #return year #if year &lt; 0: # print("Sorry,your response must not be negative.") # continue #else: # return year movies.append({ "name": name, "director": director, "year": year }) def show_movies(): movies[::3] for c, value in enumerate(movies, 1): print(c, value) for movie in movies: print(f"Name: {movie['name']}") print(f"Director: …
tagged with: while-loop
tagged with: python
has title: How do I go to, and finish one sub function, and then revert back to the "menu function" that I came from? (python)
tagged with: menu
score: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/88138565
type: QuestionComment
comment on: http://stackoverflow.com/q/50562254
has text: Still can't reproduce your issue. Consider posting a subset of `data`, maybe something like `data[::data.shape[0]//25]`.
score: 0
type: Comment

http://stackoverflow.com/comment/88228965
comment on: http://stackoverflow.com/a/50609438
has text: As I said, the `/v2/logout` is meant to be requested from the browser. This is so that the browser sends the session cookie, and Auth0 can identify who is requesting the logout and clear the session. The way to do this is returning a redirect response from the server, which instructs the browser to do a new request to the new location (i.e. the `/v2/logout` endpoint). Since you don't want the user to just endup in a blank "OK" page, you use the `returnTo` parameter to redirect the user back to a different place (like the home page of your app).
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50560993
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88133302
has title: Avoid auto filling of missing values in pd.MltiIndex
score: 1
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/50561477
has body: I try to read an Excel file with those data. The first 2 columns are index columns. In the third line, the second index is missing. 2017 2018 Airbus 10 8 Airbus A320 2 7 Airbus 4 10 Airbus A320 5 1 I read the Excel file like this : df = pd.read_excel( "C:\\Users\\Desktop\\test.xlsx", sheet_name = 'Feuil1', index_col = [0,1], header = [0] ) But the second index of my third line became A320 : 2017 2018 Airbus 10 8 Airbus A320 2 7 Airbus A320 4 10 Airbus A320 5 1 I whould like the empty indexes to stay empty or at least to fill empty indexes with the value of my choice. How can I do that ?
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/50561477
favorite count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88132964

http://stackoverflow.com/comment/88143869
score: 0
comment on: http://stackoverflow.com/q/50566855
type: Comment
type: QuestionComment
has text: "hello", something, "World" without any "hello" between them. You should post it as answer @WiktorStribiżew

http://stackoverflow.com/comment/88365223
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50677554
has text: @TarunKhaneja A dupe is a common word used for a question that is a duplicate of something. I identified this question as already answered and made a search.

http://stackoverflow.com/a/50634330
answers question: http://stackoverflow.com/q/50634303
has comment: http://stackoverflow.com/comment/88279063
type: Answer
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/50634303
has body: You can use a staticmethod to wrap decorator. The inner func_wrap function of decorator contains an additional parameter in its signature: cls. cls can be used to access the ser attribute of the instance of App, and then the desired methods write and read can be called from cls.ser. Also, note that in your declarations, MySerial.write takes no paramters, but is passed the result of the wrapped function. The code below uses *args to prevent the TypeError which would otherwise be raised: class MySerial(): def __init__(self): pass # I have to have an __init__ def write(self, *args): pass # write to buffer def read(self): pass # read to buffer @staticmethod def decorator(func): def func_wrap(cls, *args, **kwargs): cls.ser.write(func(cls, *args, **kwargs)) return cls.ser.read() return func_wrap class App(): def __init__(self): self.ser = MySerial() @MySerial.decorator def myfunc(self): # 'yummy_bytes' is written to the serial buffer via # MySerial's decorator method return 'yummy_bytes' App().myfunc()
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/50870781
accepted answer of: http://stackoverflow.com/q/50650500
answers question: http://stackoverflow.com/q/50650500
upvote count: 3
has comment: http://stackoverflow.com/comment/88768443
score: 3
has comment: http://stackoverflow.com/comment/88757928
type: AcceptedAnswer
downvote count: 0
has body: It's a bit sneaky, but I believe the problem is that the line if self.daily_rula_average_ranges.length &gt; 0: is causing an AttributeError to be raised, because length is not usually an attribute of lists. You probably meant if len(self.daily_rula_average_ranges) &gt; 0: . Here's an ORM-agnostic example - the serializer returns no field if an attribute error is raised, but returns data fine if appropriate data is returned by the property: from marshmallow import fields, Schema from marshmallow.fields import Nested class DailyRulaAverageRangeSchema(Schema): id=fields.UUID() date=fields.Date() risk=fields.Integer() class PersonSchema(Schema): last_assessment = Nested(DailyRulaAverageRangeSchema, only=['id', 'date', 'risk']) class Meta: fields = ('last_assessment',) class Person(object): @property def last_assessment(self): raise AttributeError('oops') PersonSchema().dump(Person()) # Out[73]: {} class Person(object): @property def last_assessment(self): return {"id": None, "date":None, 'risk': 100} PersonSchema().dump(Person()) # Out[83]: {u'last_assessment': {u'date': None, u'id': None, u'risk': 100}} It is not too surprising that marshmallow behaves this way because an attribute that raises an AttributeError will appear as though the attribute does not exist, e.g.: class Person(object): @property def last_assessment(self): raise AttributeError('oops') hasattr(Person(), 'last_assessment') # Out: False
type: Answer

http://stackoverflow.com/comment/88351913
score: 0
has text: Not only when you post on `show_recommendation(request):` you got error, but when access the view with GET method, there's no Http Response. think when the `request.method != 'POST'`, what's the response
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50671066

http://stackoverflow.com/comment/88335790
type: AnswerComment
type: Comment
has text: I tried this initially but I moved to try/excepts because occasional errors broke the if/else strategy.
score: 1
comment on: http://stackoverflow.com/a/50662039

http://stackoverflow.com/a/50605935
score: 4
has body: The underlying WINAPIs for this task are part of [MS.Docs]: WNetAddConnection2W function family. The [GitHub]: mhammond/pywin32 - Python for Windows (pywin32) Extensions wrapper is [ActiveState]: Module win32wnet (it's not the official doc (I couldn't find any at this point) - I don't know for how long the URL will be valid, but it's the best I could find). I've prepared a trivial example. code00.py: #!/usr/bin/env python3 import sys import os import pywintypes import win32wnet CONNECT_INTERACTIVE = 0x00000008 HOST_NAME = "192.168.1.3" SHARE_NAME = "Work" SHARE_FULL_NAME = os.path.sep * 2 + os.path.sep.join((HOST_NAME, SHARE_NAME)) SHARE_USER = "cfati" SHARE_PWD = "********" def main(): net_resource = win32wnet.NETRESOURCE() net_resource.lpRemoteName = SHARE_FULL_NAME flags = 0 #flags |= CONNECT_INTERACTIVE print("Trying to create connection to: {:s}".format(SHARE_FULL_NAME)) try: win32wnet.WNetAddConnection2(net_resource, SHARE_PWD, SHARE_USER, flags) except pywintypes.error as e: print(e) else: print("Success!") if __name__ == "__main__": print("Python {:s} on {:s}\n".format(sys.version, sys.platform)) main() Notes: The password is obfuscated (obviously) This is the simplest functionality (the equivalent of your command), however the function can do much more: One thing that I want to point out. If you: Input some invalid credentials, and Decomment the flags |= CONNECT_INTERACTIVE line A credentials dialog box will then pop up Output: (py35x64_test) e:\Work\Dev\StackOverflow\q050602112&gt;net use New connections will be remembered. There are no entries in the list. (py35x64_test) e:\Work\Dev\StackOverflow\q050602112&gt;"e:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" code00.py Python 3.5.4 (v3.5.4:3f56838, Aug 8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32 Trying to create connection to: \\192.168.1.3\Work Success! (py35x64_test) e:\Work\Dev\StackOverflow\q050602112&gt;net use New connections will be remembered. Status Local Remote Network -------------…
has comment: http://stackoverflow.com/comment/88221668
type: Answer
accepted answer of: http://stackoverflow.com/q/50602112
has comment: http://stackoverflow.com/comment/88221864
answers question: http://stackoverflow.com/q/50602112
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88221621

http://stackoverflow.com/q/50603171
has comment: http://stackoverflow.com/comment/139641444
type: Question
linked to: http://stackoverflow.com/q/58610333
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88215714
has title: python user32.GetMessage never exits
has answer: http://stackoverflow.com/a/50604668
has body: for some of my python applications i'm installing system hooks using ctypes and the windows API, in order for these to work a message loop must be running. because I have other things happening in the foreground this message loop is set to run as a background thread. this part works fine, however when i want to stop this background thread I can't get it to exit, the GetMessage function should return 0 when the WM_QUIT message is received and the body of my message loop should but for some reason it never does. I've tried various combinations of SendMessage, PostMessage, PostThreadMessage and PostQuitMessage with no success. #!python3 import tkinter as tk import ctypes import ctypes.wintypes from threading import Thread user32 = ctypes.windll.user32 def loop(): msg = ctypes.wintypes.MSG() while user32.GetMessageW(ctypes.byref(msg), 0, 0, 0) != 0: print('msg') user32.TranslateMessageW(msg) user32.DispatchMessageW(msg) print('end of loop') def SendMessage1(): user32.SendMessageA(0xFFFF, 0x001C, 0, 0) # broadcast handle, app_activate message def SendMessage2(): user32.SendMessageA(0, 0x001C, 0, 0) # null handle def PostMessage1(): user32.PostMessageA(0xFFFF, 0x001C, 0, 0) def PostMessage2(): user32.PostMessageA(0, 0x001C, 0, 0) def PostThreadMessage1(): user32.PostThreadMessageA(0xFFFF, 0x001C, 0, 0) def PostThreadMessage2(): user32.PostThreadMessageA(0, 0x001C, 0, 0) def PostQuitMessage1(): user32.PostQuitMessage(0) def PostQuitMessage2(): user32.PostQuitMessage(0) root = tk.Tk() t = Thread(target=loop) t.daemon=True t.start() tk.Button(root, text='SendMessage 1', command=SendMessage1).pack() tk.Button(root, text='SendMessage 2', command=SendMessage2).pack() tk.Button(root, text='PostMessage 1', command=PostMessage1).pack() tk.Button(root, text='PostMessage 2', command=PostMessage2).pack() tk.Button(root, text='PostThreadMessage 1', command=PostThreadMessage1).pack() tk.Button(root, text='PostThreadMessage 2', command=PostThreadMessage2).pack() tk.Button(root, text='Po…
favorite count: 0
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/88218633
accepted answer: http://stackoverflow.com/a/50604668
score: 2
type: AnsweredQuestion

http://stackoverflow.com/a/50594185
answers question: http://stackoverflow.com/q/50594178
has body: from pprint import pprint d = { 'e': [{'y': 'y'}, {'x': [{'2': 2, '1': 1}]}], 'x': ['c', 'b', 'a'], 'z': { 'a': [3, 1, 2], 'd': [{'y': [6,5,1]}, {'w': 1}], 'c': {'2': 2, '3': 3, '4': 4} }, 'w': {1:1, 2:2, 3:3} } def rec_sort(iterable): """Recursively sort """ def sort_dict_key(x): if isinstance(x, dict): return sorted(x.keys(), key=sort_dict_key) return x if isinstance(iterable, dict): d = {} for k, v in iterable.items(): d[k] = rec_sort(v) elif isinstance(iterable, list): iterable.sort(key=sort_dict_key) for pos,item in enumerate(iterable): iterable[pos] = rec_sort(item) return iterable pprint(rec_sort(d))
type: Answer
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/88247572
has text: can you be more specific about ：X_scaler = StandardScaler() X_train = X_scaler.fit_transform(X_train) X_test = X_scaler.transform(X_test),Thanks.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50616591

http://stackoverflow.com/comment/104795608
type: Comment
type: QuestionComment
has text: I'm wondering why this question has been voted down. I'm planning on removing the question, since it seems like it's not a good question. However, I'd like to know why it got the negative responses.
score: 0
comment on: http://stackoverflow.com/q/50613848

http://stackoverflow.com/a/50562874
has body: Try removing view-source: from your url_src, in essence: url_src = 'https://wallstreetcn.com/live/global?from=navbar' I think view-source: is Chrome specific (so Chrome knows to show you source rather than the webpage).
answers question: http://stackoverflow.com/q/50562793
type: Answer
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50562793

http://stackoverflow.com/comment/88189669
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50586672
type: Comment
has text: Try the original AI. It isn't that hard (If you have a way to check where walls are relative to the ghost). If you have problems with implementing that AI, just ask here. This question is too broad.

http://stackoverflow.com/a/50582559
type: Answer
score: 2
upvote count: 2
has body: use drop_duplicates to get rid of duplicate tags per post, and then you can use value_counts df.Posts.str.extractall( r'(\#\w+)' ).reset_index().drop_duplicates(['level_0', 0])[0].value_counts() shorter alternative where level=0 is passed to reset_index df.Posts.str.extractall( r'(\#\w+)' ).reset_index(level=0).drop_duplicates()[0].value_counts() both will output: #tag1 3 #tag3 1 #tag2 1 Name: 0, dtype: int64
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50582305
answers question: http://stackoverflow.com/q/50582305

http://stackoverflow.com/comment/88145362
type: AnswerComment
type: Comment
has text: This will give the expected result, but will not contribute to understanding the concept of programming. Also, as a teacher, I would doubt the student came up with this on his/her own. So it will raise more questions than it answers.
comment on: http://stackoverflow.com/a/50567594
score: 0

http://stackoverflow.com/comment/88375587
comment on: http://stackoverflow.com/q/50682466
has text: @ResetACK Oh right! You hit the point! So the problem get solved. Do you mind to edit your answer again and I accept it there?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50581138
tagged with: python-3.x
type: UnansweredQuestion
score: 6
tagged with: python
downvote count: 0
has comment: http://stackoverflow.com/comment/88172999
has body: I got the following error: from azure.storage.blob import BlockBlobService ImportError: cannot import name 'BlockBlobService' when trying to run my python project using command prompt. (The code seems to work when i execute it directly from anaconda navigator.) I am using Python 3.6.4 for Anaconda. Running pip freeze gives me the following: azure-nspkg==2.0.0 azure-storage-blob==1.1.0 azure-storage-common==1.1.0 azure-storage-nspkg==3.0.0 azurepython3==1.7.7
type: Question
linked to: http://stackoverflow.com/q/58900507
upvote count: 6
linked to: http://stackoverflow.com/q/35558463
has comment: http://stackoverflow.com/comment/88175416
answer count: 1
has title: Cannot import name 'BlockBlobService'
has answer: http://stackoverflow.com/a/58900584
favorite count: 0

http://stackoverflow.com/comment/88148637
comment on: http://stackoverflow.com/q/50569345
type: QuestionComment
has text: what is the function `f` doing? Could you please provide a [Minimal, Complete, and Verifiable Example (MCVE)](https://stackoverflow.com/help/mcve)?
score: 0
type: Comment

http://stackoverflow.com/comment/117840581
type: Comment
comment on: http://stackoverflow.com/a/50640931
type: AnswerComment
has text: use `tf.nn.top_k` instead of `tf.math.top_k`.
score: 0

data-cleaning
tags question: http://stackoverflow.com/q/50645206
type: Tag
tags question: http://stackoverflow.com/q/50645280
tags question: http://stackoverflow.com/q/50577893
tag name: data-cleaning

http://stackoverflow.com/comment/88095194
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50541979
has text: that's a subjective question. but python has the built-in [`property`](https://docs.python.org/3/library/functions.html#property), so it's clearly made for using
score: 0

http://stackoverflow.com/comment/88290439
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50640023
score: 0
has text: Maybe this can help ==> https://stackoverflow.com/questions/29630217/multiprocessing-in-ipython-console-on-windows-machine-if-name-requirement

http://stackoverflow.com/q/50587297
has comment: http://stackoverflow.com/comment/88187746
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/88184693
has answer: http://stackoverflow.com/a/50589785
favorite count: 0
has comment: http://stackoverflow.com/comment/88188429
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88185757
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88186667
accepted answer: http://stackoverflow.com/a/50589785
has body: I have a pandas dataframe that holds the image id, image class and image data: img_train.head(5) ID index class data 0 10472 10472 0 [[[255, 255, 255, 0], [255, 255, 255, 0], [255... 1 7655 7655 0 [[[255, 255, 255, 0], [255, 255, 255, 0], [255... 2 6197 6197 0 [[[255, 255, 255, 0], [255, 255, 255, 0], [255... 3 9741 9741 0 [[[255, 255, 255, 0], [255, 255, 255, 0], [255... 4 9169 9169 0 [[[255, 255, 255, 0], [255, 255, 255, 0], [255... I am trying to convert each of these columns to a numpy array: train_img_array = np.array([]) train_id_array = np.array([]) train_lab_array = np.array([]) count = 0 for index, row in img_train.iterrows(): imgid = row['ID'] imgclass = row['class'] imgdata = row['data'] #print(imgdata) train_img_array = np.append(train_img_array, imgdata ) train_lab_array = np.append(train_lab_array, imgclass ) train_id_array = np.append(train_id_array, imgid ) However, the the column that holds the image data and is of the type 'object' is not getting translated into corresponding row in the numpy array. For instance, this is the shape of each numpy array after processing 58 rows from the original dataframe: train_img_array.shape train_lab_array.shape train_id_array.shape (93615200,) (58,) (58,) How do i fix this?
downvote count: 1
type: Question
tagged with: numpy
has title: Convert a pandas dataframe column of type object to a numpy array
has comment: http://stackoverflow.com/comment/88188491
tagged with: arrays
has comment: http://stackoverflow.com/comment/88184594
has comment: http://stackoverflow.com/comment/88184203
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88188007
has comment: http://stackoverflow.com/comment/88187899
has comment: http://stackoverflow.com/comment/88187762

http://stackoverflow.com/q/50698063
tagged with: array-broadcasting
has answer: http://stackoverflow.com/a/50698496
favorite count: 0
tagged with: python-3.x
has title: cosine similarity between a vector and pandas column(a linear vector)
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50719439
score: 3
upvote count: 3
type: Question
tagged with: numpy
answer count: 2
downvote count: 0
tagged with: scikit-learn
has body: I have a pandas data frame containing list of wines with their respective wine attributes. Then I made a new column vector that contains numpy vectors from these attributes. def get_wine_profile(id): wine = wines[wines['exclusiviId'] == id] wine_vector = np.array(wine[wine_attrs].values.tolist()).flatten() return wine_vector wines['vector'] = wines.exclusiviId.apply(get_wine_profile) hence the vector column look something like this vector [1, 1, 1, 2, 2, 2, 2, 1, 1, 1] [3, 1, 2, 1, 2, 2, 2, 0, 1, 3] [1, 1, 2, 1, 3, 3, 3, 0, 1, 1] . . now I want to perform cosine similarity between this column and another vector that is resulting vector from the user input This is what i have tried so far from scipy.spatial.distance import cosine cos_vec = wines.apply(lambda x: (1-cosine(wines["vector"],[1, 1, 1, 2, 2, 2, 2, 1, 1, 1]), axis=1) Print(cos_vec) this is throwing error ValueError: ('operands could not be broadcast together with shapes (63,) (10,) ', 'occurred at index 0') I also tries using sklearn but it also have the same problem with the arrar shape what i want as a final output is a column that has match score between this column and user input

http://stackoverflow.com/comment/88295216
score: 0
type: AnswerComment
has text: PERFECT!!! Thanks for your help. However, how can I compare such dict/list creature ... the key from the dict will be random. Can you help on this? How can I generically compare such dict/list combination with another dict/list combination? My questions is also related to this: https://stackoverflow.com/questions/50641447/python-comparing-2-jsons-with-variable-key-and-value-length?noredirect=1#comment88293092_50641447 when I compare two JSONs. Was advised to use it with dicts .... hence this question
type: Comment
comment on: http://stackoverflow.com/a/50642176

http://stackoverflow.com/comment/88169779
type: QuestionComment
comment on: http://stackoverflow.com/q/50579925
score: 0
has text: @JonClements: My bad. IDs need not be taken into consideration much
type: Comment

http://stackoverflow.com/comment/88193779
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50592133
has text: If the container does not terminate you could do eg. `docker cp $volumeid:/output.xml .` on the host. Generally, though, see @ivan_pozdeev's answer.
score: 0

http://stackoverflow.com/comment/88176913
has text: @Matthew You are welcome.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50580433

http://stackoverflow.com/comment/88126692
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50557914
score: 0
has text: What have you tried so far? Please post your code.

http://stackoverflow.com/q/50609551
has answer: http://stackoverflow.com/a/50609771
downvote count: 0
accepted answer: http://stackoverflow.com/a/50609771
has body: I have a pandas frame with employee PTO entries: employee_id time_off_date 1 1/1/2017 1 1/2/2017 1 1/3/2017 1 5/1/2017 2 6/1/2017 2 9/5/2017 2 9/6/2017 2 9/7/2017 2 9/8/2017 I am trying to find the longest duration of consecutive days of PTO each employee took. For example, employee #1's longest PTO duration is 3 days (1/1/2017 to 1/3/2017) and employee #2's longest PTO duration is 4 days (9/5/2017 to 9/8/2017). I'm a bit stumped on what combination of pandas groupby and shift I should use to answer this question. Bonus points: find all PTO durations for all employees over X days. Please let me know if you have any questions.
tagged with: pandas
answer count: 1
favorite count: 0
has title: Pandas - groupby "longest" duration of Paid Time Off (PTO)
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88228999
type: AnsweredQuestion
score: 1
type: Question

http://stackoverflow.com/q/50667127
has comment: http://stackoverflow.com/comment/88344242
has answer: http://stackoverflow.com/a/50667249
has comment: http://stackoverflow.com/comment/88346770
has comment: http://stackoverflow.com/comment/88347381
upvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/50667249
has body: The code below writes 20 lines of data to a csv file. It gets the data from the first page of a table from this web address: https://www.finviz.com/screener.ashx?v=161 I'm looking for a way to change the code to continue to automatically extract the remaining pages of the table like these below to add the next 40 rows. https://www.finviz.com/screener.ashx?v=161&amp;r=21 https://www.finviz.com/screener.ashx?v=161&amp;r=42 Anyone know how this would be accomplished? Thanks import requests from bs4 import BeautifulSoup base_url = 'https://www.finviz.com/screener.ashx?v=161' html = requests.get(base_url) soup = BeautifulSoup(html.content, "html.parser") main_div = soup.find('div', attrs = {'id':'screener-content'}) light_rows = main_div.find_all('tr', class_="table-light-row-cp") dark_rows = main_div.find_all('tr', class_="table-dark-row-cp") data = [] for rows_set in (light_rows, dark_rows): for row in rows_set: row_data = [] for cell in row.find_all('td'): val = cell.a.get_text() row_data.append(val) data.append(row_data) # sort rows to maintain original order data.sort(key=lambda x: int(x[0])) import pandas pandas.DataFrame(data).to_csv("AAA.csv", header=False)
downvote count: 5
has title: Extract all pages from a Table
has answer: http://stackoverflow.com/a/50668024
answer count: 3
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/88344180
has answer: http://stackoverflow.com/a/50667862
tagged with: http://stackoverflow.com/tag/csv
score: -4
tagged with: python
accepted answer: http://stackoverflow.com/a/50668024
type: AnsweredQuestion

http://stackoverflow.com/comment/88118281
comment on: http://stackoverflow.com/q/50553442
score: 0
type: Comment
type: QuestionComment
has text: "This algorithm is slow because hashing happens twice" What makes you think that this has any measurable effect?

http://stackoverflow.com/q/50573677
accepted answer: http://stackoverflow.com/a/50573942
has answer: http://stackoverflow.com/a/50573831
has title: Slicing/Indexing with multidimensional arrays using Numpy
has body: I have 3 4x4 arrays (matrices) created with: arr=np.linspace(1,48,48).reshape(3,4,4) The matrices appear as below: ` [[[ 1. 2. 3. 4.] [ 5. 6. 7. 8.] [ 9. 10. 11. 12.] [13. 14. 15. 16.]] [[17. 18. 19. 20.] [21. 22. 23. 24.] [25. 26. 27. 28.] [29. 30. 31. 32.]] [[33. 34. 35. 36.] [37. 38. 39. 40.] [41. 42. 43. 44.] [45. 46. 47. 48.]]]` I would like to perform indexing/splicing to obtain certain outputs eg: [[36. 35.] [40. 39.] [44. 43.] [48. 47.]] [[13. 9. 5. 1.] [29. 25. 21. 17.] [45. 41. 37. 33.]] [[25. 26. 27. 28.], [29. 30. 31. 32.], [33. 34. 35. 36.], [37. 38. 39. 40.]] 4*. [[1. 4.] [45. 48.]] I am struggling with exactly how to approach it. When working with a particular matrix, I have attempted to access that matrix and then splice/index from there. For example, the output [[36. 35.] [40. 39.] [44. 43.] [48. 47.]] lies in the third matrix. I access the matrix like this matrix3 = arr[array([2])] Now I am only working with rows and columns in the third matrix and am finding it difficult to slice correctly. Should matrix3[::-1,::-1] invert both columns and rows? If yes then is this the best way to approach it? Instead, should I use reshape and should you use reshape on all 3 4x4 arrays or access the matrix you want to work with and then reshape? edit: added 4.
tagged with: python
possible better answer: http://stackoverflow.com/a/50573831
tagged with: indexing
has answer: http://stackoverflow.com/a/50573942
type: AnsweredQuestion
score: 0
tagged with: slice
type: Question
tagged with: numpy
answer count: 2
tagged with: arrays

http://stackoverflow.com/comment/88113276
has text: Sorry, thought it was clear. It doesn’t recognize the directory I give. My bad
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50547353

http://stackoverflow.com/q/50636877
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50639088
score: 1
has answer: http://stackoverflow.com/a/50638769
has body: I am parsing a file where labels are defined as below, with hierarchies represented by using new lines +--------------------+--------------------+--------------------+ | L1 - A | | | | | L2 - B | | | | | L3 - C | | | | | | L1 - D | | | | | L2 - E | | | | | L3 - F | +--------------------+--------------------+--------------------+ I represent the above as: labels = [ ['A', None, None, None, 'D', None, None], [None, 'B', None, None, None, 'E', None], [None, None, 'C', None, None, None, 'F'] ] I tried def joinfoo(items): if len(items) == 1: return items[0] result = [] active = None for x, y in zip(items[0], joinfoo(items[1:])): active = x if x else active if type(y) is tuple: result.append((active, y[0], y[1])) else: result.append((active, y)) return result I wanted [ ('A', None, None), ('A', 'B', None), ('A', 'B', 'C'), (None, None, None), ('D', None, None), ('D', 'E', None), ('D', 'E', 'F') ] and got this [ ('A', None, None), ('A', 'B', None), ('A', 'B', 'C'), ('A', 'B', None), ('D', 'B', None), ('D', 'E', None), ('D', 'E', 'F') ] Suggestions on how to fix joinfoo() to achieve the desired result? Solution needs to support a variable number of columns. It should be something like for x, y in zip(joinfoo(items[:-1]), items[-1]): instead of for x, y in zip(items[0], joinfoo(items[1:])): to go in the right direction...? Edit: The original list of lists may have wrongly implied a pattern to the hierarchy. There is no defined pattern. Number of columns are also variable. A better test case maybe.. +--------------+--------------+--------------+ | L1 - A | | | = A | | L2 - B | | = A - B | | | L3 - C | = A - B - C | | | L3 - D | = A - B - D | | L2 - E | | = A - E | | | | = | L1 - F | | | = F | | L2 - G | | = F - G | | | L3 - H | = F - G - H +--------------+--------------+--------------+ labels = [ ['A', None, None, None, None, None, 'F', None, None], [None, 'B', None, None, 'E', None, None, 'G', None], [None, None, 'C', 'D', None, None, None, None, 'H'] ]
upvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/50639088
has title: Denormalizing hierarchy in list of lists
accepted answer: http://stackoverflow.com/a/50638769
tagged with: python-2.7
answer count: 3
has comment: http://stackoverflow.com/comment/88283910
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50637667
tagged with: python
has comment: http://stackoverflow.com/comment/88283960

http://stackoverflow.com/comment/131978255
type: AnswerComment
comment on: http://stackoverflow.com/a/50651915
type: Comment
has text: The question was about typing in [Table in Behave's Step Data](https://behave.readthedocs.io/en/stable/tutorial.html#step-data), but your tutorial only works for [Behave's Scenario Outline](https://behave.readthedocs.io/en/stable/tutorial.html#scenario-outlines) which is a different mechanism even if it looks like a table too.
score: 1

http://stackoverflow.com/comment/105777317
has text: @Georgy no, not really. The issue here wasn't general exception catching, but, given that module X throws and error specific to that module, how does one figure out where to import the given exception from X.
type: QuestionComment
comment on: http://stackoverflow.com/q/50651378
score: 0
type: Comment

http://stackoverflow.com/q/50647278
accepted answer: http://stackoverflow.com/a/50682395
score: 0
answer count: 1
tagged with: neo4j
has title: Update property relation with py2neo neo4j
tagged with: py2neo
tagged with: python
has comment: http://stackoverflow.com/comment/88322364
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50682395
type: Question
has comment: http://stackoverflow.com/comment/88317602
has body: I'm trying to check if a relation between two nodes exists but i get this error: raise TypeError("Nodes for relationship match end points must be bound") TypeError: Nodes for relationship match end points must be bound below my code: graph = Graph(user='neo4j') src = Node(src_type, internal_id=int(src_id)) dst = Node(dst_type, internal_id=int(dst_id)) src_voted_dst = Relationship(src, "VOTED", dst) for elem in graph.match(start_node=src, rel_type="VOTED", end_node=dst, bidirectional=True): elem.properties["vote"] = elem.properties["vote"] + 1 elem.push() break else: src_voted_dst.properties["vote"] = 1 graph.merge(src_voted_dst)

http://stackoverflow.com/comment/88265945
has text: Actually `conda activate [environment name]` is now preferred -- see https://conda.io/docs/release-notes.html#id24
comment on: http://stackoverflow.com/a/50627791
type: AnswerComment
score: 2
type: Comment

http://stackoverflow.com/a/50551868
answers question: http://stackoverflow.com/q/50551827
type: Answer
score: 2
downvote count: 0
upvote count: 2
has body: You can just do this: example_array = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]] indexes = [[1,2,3], [2,3], [0,4,2], [1,4,3], [0,4,3], [1,2,3], [1,2]] for i,index in enumerate(indexes): for idx in index: example_array[i][idx] = 1 print example_array Output: [[0, 1, 1, 1, 0], [0, 0, 1, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 1], [1, 0, 0, 1, 1], [0, 1, 1, 1, 0], [0, 1, 1, 0, 0]]
accepted answer of: http://stackoverflow.com/q/50551827
type: AcceptedAnswer

http://stackoverflow.com/q/50698491
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50724960
score: 1
tagged with: reportlab
upvote count: 1
type: Question
has title: Different page template from second page
has body: The following is my code for generation of a pdf using reportlab. I am almost finished with the format but the page template of first page is getting copied from the second page as well. From second page, I just need a two column template and I do not want the TopCenter, frame1 and frame2 format from second page. from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter,A4 from reportlab.platypus import Image from reportlab.lib.units import inch, cm import json from reportlab.platypus import BaseDocTemplate,Frame,Paragraph,PageBreak, PageTemplate,Spacer,FrameBreak,NextPageTemplate from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.styles import ParagraphStyle from reportlab.lib.enums import TA_JUSTIFY, TA_CENTER from reportlab.platypus import BaseDocTemplate, Frame, Paragraph, PageBreak, PageTemplate from reportlab.lib.styles import getSampleStyleSheet def foot1(canvas,doc): width,height = A4 canvas.saveState() canvas.setFont('Times-Roman',9) canvas.drawString(width-0.1*inch, 0.1 * inch, "%d" % doc.page) canvas.restoreState() def foot2(canvas,doc): width,height = A4 canvas.saveState() canvas.setFont('Times-Roman',9) canvas.drawString(width-0.1*inch, 0.1 * inch,"%d" % doc.page) def demo1(canvas): width,height = A4 doc = BaseDocTemplate('test.pdf',showBoundary=1) contents =[] styleSheet = getSampleStyleSheet() TopCenter = Frame(1.2*inch,height-1.2*inch,width-2.4*inch,1*inch,showBoundary = 1,id='normal') frame1 = Frame(0.2*inch,0.2*inch,(width-0.6*inch)/2, height-1.6*inch,showBoundary = 1,id='col1') frame2 = Frame(0.4*inch+(width-0.6*inch)/2,0.2*inch, (width-0.6*inch)/2, height-1.6*inch,showBoundary = 1,id='col2' ) leftlogoframe = Frame(0.2*inch,height-1.2*inch,1*inch,1*inch,showBoundary = 1) rightlogoframe = Frame((width-1.2*inch),height-1.2*inch,1*inch,1*inch,showBoundary = 1) frame1later = Frame(0.2*inch,0.2*inch,(width-0.6*inch)/2, height-0.4*inch,showBoundary = 1,id='col1later') frame2later = Frame(0.4*inch+(width-0.6*inch…
tagged with: http://stackoverflow.com/tag/pdf
downvote count: 0
answer count: 1

http://stackoverflow.com/q/50674086
tagged with: pandas
answer count: 1
has title: How to Arrange a column of a Dataframe in Python
favorite count: 0
tagged with: python-3.x
tagged with: pivot-table
has comment: http://stackoverflow.com/comment/88357837
tagged with: python
has answer: http://stackoverflow.com/a/50674100
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88357845
has body: I have a dataframe with values Product Range Sold A 1-3 5 A 4-7 23 A 8-15 2 B 4-7 4 B 8-15 1 I need the output as Sold Product Range A 1-3 5 4-7 23 8-15 2 B 4-7 4 8-15 1 Can this be done by any built-in functions or any pivot table functions?
upvote count: 2
score: 1
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50674100

http://stackoverflow.com/comment/123520817
has text: I believe the `$` is meant as the terminal entry, not part of the command...
type: Comment
score: 11
comment on: http://stackoverflow.com/a/69872518
type: AnswerComment

http://stackoverflow.com/q/50640686
type: UnansweredQuestion
tagged with: python
tagged with: selenium-webdriver
has answer: http://stackoverflow.com/a/50641968
tagged with: selenium
has title: How to login/submit request through Selenium and Python
type: Question
has answer: http://stackoverflow.com/a/50640745
has comment: http://stackoverflow.com/comment/88291517
score: 0
has body: I am not sure why selenium is not sending submit request. edx.py or Coursera from selenium import webdriver browser = webdriver.Chrome() browser.get('https://courses.edx.org/login') email = browser.find_element_by_id('login-email') email.send_keys('xxxxx@gmail.com') pwd = browser.find_element_by_id('login-password') pwd.send_keys('password') login_attempt = browser.find_element_by_xpath('//*[@id="login"]/button') login_attempt.submit()
answer count: 3
tagged with: css-selectors
tagged with: xpath
has comment: http://stackoverflow.com/comment/88291411
has answer: http://stackoverflow.com/a/50640828

http://stackoverflow.com/q/50573612
has comment: http://stackoverflow.com/comment/88157050
favorite count: 0
has answer: http://stackoverflow.com/a/50580608
tagged with: python
upvote count: 3
type: UnansweredQuestion
has body: Remove the invalid parenthesis using Python in O(n) time complexity and O(1) space. I have few approaches which will take O(n log n) and O(n^2) time and also O(n) both space and time. But, I am looking for one which minimal time. I tried searching in web but couldn't found any approach to solve. For example: input - {}{}{{}}}}}{{{{{} output - {}{}{{}}{} There are several other edge cases too.
downvote count: 1
has comment: http://stackoverflow.com/comment/88156837
score: 2
tagged with: algorithm
has comment: http://stackoverflow.com/comment/88156819
has comment: http://stackoverflow.com/comment/88169875
has title: Remove Invalid Parenthesis
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/88156901
tagged with: sorting

http://stackoverflow.com/comment/88162166
comment on: http://stackoverflow.com/a/50576206
type: Comment
has text: File "C:\New folder\try.py", line 65, in onFindClicked self.rs.setText(name) TypeError: setText(self, str): argument 1 has unexpected type 'int'
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88212408
type: Comment
has text: @river_bell: I don't know what your use case is, so I can't really tell, sorry.
comment on: http://stackoverflow.com/a/50589008
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88342963
comment on: http://stackoverflow.com/q/50666299
score: 0
has text: have you tried the workaround in this comment : https://stackoverflow.com/questions/50394873/import-pandas-datareader-gives-importerror-cannot-import-name-is-list-like#comment87850508_50415484
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50736057
answers question: http://stackoverflow.com/q/50670262
type: Answer
has body: your first print outputing a list of hrefs user = response.css("span a").extract() print(user) your code should looks like def parse(self, response): for tr in response.css("tbody"): for user in response.css("span a"): if bot_words not in user: print(user.extract()) href = user.css('::attr(href)').extract()[0] print(href) #yield response.follow("http://www.backpack.tf" + href, self.parse_accounts) print("this is a value") Also, Best practice in srapy is using of items instead of raw print function. And be aware of code duplication like response.css("span a").extract()
accepted answer of: http://stackoverflow.com/q/50670262
upvote count: 1
type: AcceptedAnswer
downvote count: 0
score: 1

http://stackoverflow.com/comment/88323334
comment on: http://stackoverflow.com/a/50654995
has text: Even faster: `pd.to_datetime(['-'.join(i) for i in df'h3', 'h2', 'h1'.values.astype(str)])`; inspired by [this answer](https://stackoverflow.com/a/49804868/9209546).
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88340739
has text: thanks for this tip. I actually examined the _base_ and the _view_ by `__array_interface__` earlier myself. I simply did not understand why Numpy would even create a view in case of my question. But what you explained here I find extremely useful. Please also have a look at my comment I left in the answer
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50662366
type: Comment

http://stackoverflow.com/a/50695931
type: Answer
has body: Try using a list comprehension to check if each character is in string.ascii_letters or not, if it is, it will be stored: import string String = ' 529Wind3@. ' print(''.join([i for i in String if i in string.ascii_letters])) Output: Wind
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50695819

http://stackoverflow.com/comment/88324258
score: 1
has text: @Abdelouahab the `with` statement is used exactly for closing without specifying. The `async with` statement does the same while not blocking. But again, I am not sure which class/method is the one in that package which does this as I havent used asyncpg. I have found that example above in the issues section of the github page so it may be what you're looking for
type: AnswerComment
comment on: http://stackoverflow.com/a/50657088
type: Comment

http://stackoverflow.com/a/50636175
type: AcceptedAnswer
has body: It's because super(sub_class, instance).method() means call the method method of the parent of sub_class on the instance instance. Since the parent of B is A, the result makes sense. What you want is super(C, self).bar().
downvote count: 0
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50636131
upvote count: 1
answers question: http://stackoverflow.com/q/50636131

http://stackoverflow.com/q/50635956
type: UnansweredQuestion
downvote count: 1
has comment: http://stackoverflow.com/comment/88281836
has answer: http://stackoverflow.com/a/50636112
has comment: http://stackoverflow.com/comment/88281799
score: -1
type: Question
upvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has body: So I want to take various coordinates with variables assigned to them and place them into a grid. For example: p = (0,0) v = (2,3) t = (5,4) Would output: |p| | | | | | | | | | | | | | | | | | | | | | |v| | | | | | | | | |t| So obviously I could use print and go line by line but is there a way to 1. Do this more efficiently and 2. Make my grid adaptable for bigger coordinates?
has comment: http://stackoverflow.com/comment/88281851
tagged with: python-3.x
has title: Outputting coordinates onto a grid python

http://stackoverflow.com/comment/88313881
comment on: http://stackoverflow.com/q/50651378
score: 0
type: Comment
type: QuestionComment
has text: I usually catch `Exception as e` while developing and then `print(type(e))` to see what I should actually be catching.

http://stackoverflow.com/q/50693031
downvote count: 0
answer count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88396883
linked to: http://stackoverflow.com/q/46242488
has comment: http://stackoverflow.com/comment/88400267
type: Question
score: 3
has comment: http://stackoverflow.com/comment/88396920
tagged with: python
has comment: http://stackoverflow.com/comment/88400375
duplicate of: http://stackoverflow.com/q/46242488
has comment: http://stackoverflow.com/comment/88395530
has comment: http://stackoverflow.com/comment/88396842
has comment: http://stackoverflow.com/comment/88396525
has comment: http://stackoverflow.com/comment/88400768
upvote count: 3
has comment: http://stackoverflow.com/comment/88396590
tagged with: pandasql
has comment: http://stackoverflow.com/comment/88400268
has comment: http://stackoverflow.com/comment/88395645
has comment: http://stackoverflow.com/comment/88396550
has comment: http://stackoverflow.com/comment/98315638
linked to: http://stackoverflow.com/q/30486417
has title: Pandas Group by a Column and take the non null values in different rows for each column
has comment: http://stackoverflow.com/comment/88400167
has body: I have an interesting question for which I am not getting any built-in solution in Pandas. I have data like: A B C D E F 1 null null Red null 12 1 89 76 Red null null 1 null null null null 12 I am trying to get an output like: 1 89 76 Red null 12 Now, these data are messages coming at different times. Many messages belong to a single transaction. So, suppose A is the identifier of the transaction. Some messages with the same identifier have a value for column B, some have value for column C. So, I want to group by the unique identifier and then get the non-null values for each column. So, this is a grouping and then aggregating task. But unlike count or things like that, I am really creating a new row. I am not finding a way to do so in pandas. Any help is greatly appreciated, Thanks! Example:> A B C D 1 null null 100 1 90 null null 2 null 1000 999 1 80 2 1000 null 799 df.groupby('A').first() B C D A 1 null null 100 2 null 1000 999 But the required output is: B C D A 1 90 80 100 2 1000 1000 999
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88395533
has comment: http://stackoverflow.com/comment/88396748
has comment: http://stackoverflow.com/comment/88396818
tagged with: pandas-groupby
has comment: http://stackoverflow.com/comment/88396706
tagged with: pandas
has comment: http://stackoverflow.com/comment/88400185
has comment: http://stackoverflow.com/comment/88396968

http://stackoverflow.com/q/50585305
type: Question
has comment: http://stackoverflow.com/comment/88212571
has comment: http://stackoverflow.com/comment/88180027
linked to: http://stackoverflow.com/q/25405110
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88207102
has comment: http://stackoverflow.com/comment/88188333
upvote count: 2
tagged with: python-sphinx
linked to: http://stackoverflow.com/q/47903710
tagged with: python
has comment: http://stackoverflow.com/comment/88180057
linked to: http://stackoverflow.com/q/22096187
has title: Include specific imported functions in sphinx documentation
has answer: http://stackoverflow.com/a/50601695
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/88210261
accepted answer: http://stackoverflow.com/a/50601695
linked to: http://stackoverflow.com/q/30856279
has body: Let's say that my_module has the following __init__.py: from my_module.misc import f2 def f1(p1,p2): """ My f1 function. :param p1: First parameter. :param p2: Second parameter. :return: Returned value. """ return p1 + p2 Where the misc.py contains the following function: def f2(p1,p2): """ My f2 function. :param p1: First parameter. :param p2: Second parameter. :return: Returned value. """ return p1 - p2 I am documenting my_module using sphinx with the following approach and f2 is not appearing in the result, is there a way to specify that it should be included? my_module --------- .. automodule:: my_module :members: :undoc-members:
has comment: http://stackoverflow.com/comment/88180849

http://stackoverflow.com/comment/88299491
score: 0
type: Comment
type: QuestionComment
has text: @StephenDeWolfe as DyZ asked, why not regex?
comment on: http://stackoverflow.com/q/50634955

python-datetime
tag name: python-datetime
tags question: http://stackoverflow.com/q/50581676
type: Tag

http://stackoverflow.com/q/50631477
score: 4
has comment: http://stackoverflow.com/comment/88273260
answer count: 2
linked to: http://stackoverflow.com/q/20306981
tagged with: jquery
favorite count: 0
tagged with: ajax
has comment: http://stackoverflow.com/comment/88273115
has answer: http://stackoverflow.com/a/50634668
has comment: http://stackoverflow.com/comment/88272961
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50631650
tagged with: django
tagged with: python
upvote count: 4
downvote count: 0
has title: How to pass data through an AJAX request in django?
type: Question
has body: I want to retrieve data from the database when the bottom of the page is hit. Now, what I have so far: urls.py urlpatterns = [ url(r'^$', feedViews.index, name='index'), url(r'^load/$', feedViews.load, name='load'), ] views.py def index(request): if request.method == 'GET': context = { 'entry_list': Entry.objects.filter()[:5], } return render(request,'index.html',context) else: return HttpResponse("Request method is not a GET") def load(request): if request.method == 'GET': context = { 'entry_list': Entry.objects.filter()[:1], } return render(request,'index.html',context) else: return HttpResponse("Request method is not a GET") index.html ... &lt;script&gt; $(window).on("scroll", function() { if ((window.innerHeight + window.scrollY) &gt;= document.body.offsetHeight) { console.log( "TEST" ); $.ajax( { type:"GET", url: "/load", data:{ }, }) } }); &lt;/script&gt; ... Basicaly it loads 5 items at the beginning and what I try to achieve is that it loads 1 more as soon as I hit the bottom of the page. So jQuery works beacuase the console.log('Test') works and in my terminal it says "GET /load/ HTTP/1.1" 200 484 which is fine as well. I think I messed up the ajax somehow. I am not sure though. As you can probably tell I am a nooby but any help is highly appreciated.

http://stackoverflow.com/comment/88306259
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50647756
score: 0
has text: Perhaps because `'baz' in 'bazbar' == True`?

http://stackoverflow.com/q/50678419
has comment: http://stackoverflow.com/comment/88369480
answer count: 1
tagged with: discord
has comment: http://stackoverflow.com/comment/88369182
favorite count: 0
tagged with: python-3.x
has title: How to make multiple files Python Bot
upvote count: 5
has body: How to load commands from multiple files Python Bot below is my main.py and other python files with commands. Is this correct method or do i need to change anything? do i need to add token, prefix, bot = commands.Bot, bot.run(token) etc in all files. main.py token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" prefix = "?" import discord from discord.ext import commands startup_extensions = ["second", "third"] bot = commands.Bot(command_prefix=prefix) bot.remove_command("help") @bot.event async def on_ready(): print('Logged in as') print(bot.user.name) print(bot.user.id) print('------') @bot.command(pass_context=True) async def hello1(ctx): msg = 'Hello {0.author.mention}'.format(ctx.message) await bot.say(msg) bot.run(token) second.py import discord from discord.ext import commands class Second(): def __init__(self, bot): self.bot = bot @commands.command(pass_context=True) async def hello2(ctx): msg = 'Hello{0.author.mention}'.format(ctx.message) await bot.say(msg) def setup(bot): bot.add_cog(Second(bot)) third.py import discord from discord.ext import commands class Third(): def __init__(self, bot): self.bot = bot @commands.command(pass_context=True) async def hello3(ctx): msg = 'Hello{0.author.mention}'.format(ctx.message) await bot.say(msg) def setup(bot): bot.add_cog(Third(bot))
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88393083
linked to: http://stackoverflow.com/q/419163
has comment: http://stackoverflow.com/comment/88368180
has comment: http://stackoverflow.com/comment/88368214
downvote count: 0
has answer: http://stackoverflow.com/a/68871226
type: Question
has comment: http://stackoverflow.com/comment/88369645
has comment: http://stackoverflow.com/comment/88394098
has comment: http://stackoverflow.com/comment/88393046
tagged with: discord.py
score: 5
has comment: http://stackoverflow.com/comment/88367861

http://stackoverflow.com/comment/88159328
comment on: http://stackoverflow.com/a/50574755
type: AnswerComment
score: 0
has text: Thanks mhawke that worked. I needed to add a few other snippets to finish the solution but your suggesting got me most of the way there.
type: Comment

http://stackoverflow.com/a/50679186
score: 3
answers question: http://stackoverflow.com/q/50679032
has comment: http://stackoverflow.com/comment/88437049
upvote count: 3
has body: You might want to look at BrowserMob Proxy. It can capture performance data for web apps (via the HAR format), as well as manipulate browser behavior and traffic, such as whitelisting and blacklisting content, simulating network traffic and latency, and rewriting HTTP requests and responses. Taken from readthedocs, the usage is simple and it integrates well with selenium webdriver api. You can read more about BMP here. from browsermobproxy import Server server = Server("path/to/browsermob-proxy") server.start() proxy = server.create_proxy() from selenium import webdriver profile = webdriver.FirefoxProfile() profile.set_proxy(proxy.selenium_proxy()) driver = webdriver.Firefox(firefox_profile=profile) proxy.new_har("google") driver.get("http://www.google.co.uk") proxy.har # returns a HAR JSON blob server.stop() driver.quit()
has comment: http://stackoverflow.com/comment/88371724
downvote count: 0
type: Answer

http://stackoverflow.com/comment/88401197
type: AnswerComment
has text: Are you sure that is correct? I would have thought that doing that would just open `"A/m1/m2/A/b1/b2/somefile.csv"`, which won't exist.
comment on: http://stackoverflow.com/a/50695459
type: Comment
score: 0

http://stackoverflow.com/comment/88235440
score: 1
comment on: http://stackoverflow.com/q/50612655
type: QuestionComment
type: Comment
has text: I can give you the short version: after `fork`, you have two processes with the same loaded program, memory heap, file descriptors, etc., but in the child `fork` has returned 0, while in the parent, it's returned the child's PID. There are a few minor differences (most obviously, who the parent of each process is, and whether each process has any children…), but for the most part they don't matter. One place they _do_ matter is shutdown, for which you have to understand how child reaping and signals and so on all work, which is not trivial, but all well documented.

http://stackoverflow.com/a/50586924
has body: Not sure if this is the best way to do it, but it works: In [56]: df_list = [] ...: for i in locals(): ...: try: ...: if type(locals()[i]) == pd.core.frame.DataFrame and not i.startswith('_'): ...: df_list.append(i) ...: except KeyError: ...: pass In [57]: df_list Out[57]: ['df', 'df2'] In [58]: for d in df_list: ...: locals()[d]['Variable'] = d In [59]: df Out[59]: Year Value Variable 0 1995-01-02 0.844 df 1 1995-01-03 0.845 df 2 1995-01-04 0.845 df 3 1995-01-05 0.843 df 4 1995-01-06 0.840 df 5 1995-01-09 0.844 df 6 1995-01-10 0.847 df 7 1995-01-11 0.851 df In [60]: df2 Out[60]: Year Value Variable 0 2008-01-02 0.844 df2 1 2008-01-03 0.845 df2 2 2008-01-04 0.845 df2 3 2008-01-05 0.843 df2 4 2008-01-06 0.840 df2 5 2008-01-09 0.844 df2 6 2008-01-10 0.847 df2 7 2008-01-11 0.851 df2
downvote count: 1
score: 0
answers question: http://stackoverflow.com/q/50586862
type: Answer
upvote count: 1

typechecking
tags question: http://stackoverflow.com/q/50675417
type: Tag
tag name: typechecking

http://stackoverflow.com/comment/88288290
type: Comment
type: QuestionComment
has text: I have put up a sample data set. Is there no easier way? There has to be.
comment on: http://stackoverflow.com/q/50638823
score: 0

http://stackoverflow.com/comment/88292194
score: 0
type: AnswerComment
type: Comment
has text: While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please [include an explanation for your code](//meta.stackexchange.com/q/114762/269535), as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. **Flaggers / reviewers:** [For code-only answers such as this one, downvote, don't delete!](//meta.stackoverflow.com/a/260413/2747593)
comment on: http://stackoverflow.com/a/50640531

http://stackoverflow.com/comment/88194165
comment on: http://stackoverflow.com/q/50591098
score: 0
has text: @alex The main options there is not `-r requirements.txt` but `--no-index --find-links`.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88246296
type: Comment
has text: abarnert, yeah this is another problem, You generally do not want to test float values with != , then how to test them ?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50610838

http://stackoverflow.com/comment/88355133
type: Comment
has text: Can you post an example of what you want to resulting XML to look like?
comment on: http://stackoverflow.com/q/50672570
type: QuestionComment
score: 0

http://stackoverflow.com/q/50666517
has comment: http://stackoverflow.com/comment/88343000
has answer: http://stackoverflow.com/a/50666615
favorite count: 0
has body: Is this a format that can be parsed by Python into a dict or some other data structure? And of course any format can be parsed, but I am wondering if this format is "known" and can be parsed by some existing library or does the parsing have to be hand written? It is the output from requesting font info as provided by fc-scan You can see here the output when I do: fc-scan : family /usr/share/fonts/truetype/yaldevicolombo/YaldeviColombo-ExtraLight.ttf (venv35) ubuntu@ip-10-0-0-196:~/font/fonts-master$ fc-scan : family /usr/share/fonts/truetype/yaldevicolombo/YaldeviColombo-ExtraLight.ttf Pattern has 23 elts (size 32) family: "Yaldevi Colombo ExtraLight"(s) "Yaldevi Colombo"(s) familylang: "en"(s) "en"(s) style: "Regular"(s) "ExtraLight"(s) stylelang: "en"(s) "en"(s) fullname: "Yaldevi Colombo ExtraLight"(s) fullnamelang: "en"(s) slant: 0(i)(s) weight: 48(i)(s) width: 100(i)(s) foundry: "unknown"(s) file: "/usr/share/fonts/truetype/yaldevicolombo/YaldeviColombo-ExtraLight.ttf"(s) index: 0(i)(s) outline: True(s) scalable: True(s) charset: 0000: 00000000 ffffffff ffffffff 7fffffff 00000000 ffffffff ffffffff ffffffff 0001: cfcff0ff 7ec3cc0c cfff31fe 7f0fcc3f 00040000 00000000 00000000 00000000 0002: 0f000000 00000000 00000000 00000000 00000000 00000000 3f0002c0 00000000 0003: 00000000 00000000 00000000 00000000 00000000 00000000 00000001 00000000 000d: 00000000 00000000 00000000 00000000 fc7fffec 2ffbffff ff5f847f 001c0000 0020: 77183000 06010047 00000010 00000000 00000000 24001000 00000000 00000000 0021: 00080000 00004044 00000000 00000000 00000000 00000000 00000000 00000000 0022: 46268044 00000800 00000100 00000031 00000000 00000000 00000000 00000000 0025: 00000000 00000000 00000000 00000000 00000000 00000000 00001400 00000000 00fb: 00000006 00000000 00000000 00000000 00000000 00000000 00000000 00000000 (s) lang: aa|ay|bi|br|bs|ch|co|cs|da|de|en|es|et|eu|fi|fj|fo|fr|fur|fy|gd|gl|gv|ho|hr|hu|ia|id|ie|io|is|it|lb|lt|lv|mg|mh|nb|nds|nl|nn|no|nr|nso|oc|om|pl|pt|rm|ro|si|sk|…
has title: Is this a known data format parseable by Python?
has comment: http://stackoverflow.com/comment/88343050
tagged with: python
has answer: http://stackoverflow.com/a/50666705
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88343199
type: UnansweredQuestion
tagged with: truetype
upvote count: 1
downvote count: 1
type: Question
score: 0
answer count: 2

http://stackoverflow.com/q/50570267
type: AnsweredQuestion
type: Question
has title: how to get list from a list which contains dict_values in python
has answer: http://stackoverflow.com/a/50570557
has body: I have a list which is having a set of key,values like {`namelist = [{'name': 'John'},{'name': 'Tin'},{'name': 'Mony'}, {'name':'Hilber'},{'name': 'Marge'}]`} Iam tring to get list which is having only names like {`names =['John','Tin','Mony','Hilber','Marge']`} I tried like {`names = [] for i in range(len(namelist)): names.append(namelist[i].values())`} it is giving output like {`[dict_values(['John']), dict_values(['Tin']), dict_values(['Mony']), dict_values(['Hilber']), dict_values(['Marge'])] `} but i want only names in the list without dict_values tagging. please help me
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50570557
tagged with: python

http://stackoverflow.com/comment/88153054
type: Comment
has text: Maybe. I Tried in python 3.5, there it worked fine. Which error do you get? Which Pythoversion? Obviously 2.x, but which one? I'll try doing it with threading then...
type: AnswerComment
comment on: http://stackoverflow.com/a/50570841
score: 0

http://stackoverflow.com/a/50563359
score: 4
upvote count: 4
downvote count: 0
type: Answer
has body: If you want to keep all occurences of the maximum, you could use cond = tf.equal(a, tf.reduce_max(a)) a_max = tf.where(cond, a, tf.zeros_like(a)) If you want to keep only one occurrence of the maximum, you could use argmax = tf.argmax(a) a_max = tf.scatter_nd(argmax, [a[argmax]], tf.to_int64(tf.shape(a))) However according to the doc of tf.argmax, Note that in case of ties the identity of the return value is not guaranteed As I understand it, the maximum that is kept may not be the first or the last -- and may not even be the same if run twice on the same array.
answers question: http://stackoverflow.com/q/50563215

http://stackoverflow.com/comment/88433527
comment on: http://stackoverflow.com/a/50698565
has text: @trinathreddy, thats correct, I made the edit in answer
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88205198
type: Comment
comment on: http://stackoverflow.com/a/50597997
type: AnswerComment
score: 0
has text: And `venv` or `pipenv` for additional garantee

http://stackoverflow.com/q/50633853
has answer: http://stackoverflow.com/a/50634909
answer count: 1
has body: I am trying to copy contents of a folder but it keeps on showing the error of Permission denied. import subprocess import shutil import os procId = subprocess.call('adb pull /sdcard/HDrec2.0/records/ tmp/', stdin = subprocess.PIPE) folderPath = (os.getcwd() + os.sep + 'tmp') shutil.copyfile(folderPath ,'D:\job\HDrec2_MotoG\Windows\records') error message is traceback (most recent call last): File "D:\job\HDrec2_MotoG\Windows\z2.py", line 20, in &lt;module&gt; shutil.copyfile(folderPath ,'D:\job\HDrec2_MotoG\Windows\records') File "C:\Python27\lib\shutil.py", line 96, in copyfile with open(src, 'rb') as fsrc: IOError: [Errno 13] Permission denied: 'D:\\job\\HDrec2_MotoG\\Windows\\tmp'
score: 0
has comment: http://stackoverflow.com/comment/88277888
has comment: http://stackoverflow.com/comment/88279892
tagged with: ioerror
tagged with: python
tagged with: shutil
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88277883
has title: shutil.copyfile keep returning error of permission denied
type: Question

http://stackoverflow.com/q/50572611
has body: I'm new Django and have been working on project. When I click on my techposts. it says No Techpost matches the given query. It was working fine and I didn't change anything. Not sure what could have happened. It has happened 2-3 times. Database flush used to fix this issue. But now nothing is working. Please suggest how do I fix this and the possible reason behind this? PS: Found similar questions but their answers didnt help. CODE: models.py class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Techpost(models.Model): STATUS_CHOICS=( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField(max_length=255, blank=False, null=False) slug = models.SlugField(max_length=255, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='tech_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices = STATUS_CHOICS, default='draft') tags = TaggableManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title objects = models.Manager() # default manager published = PublishedManager() # Custom Manager. def get_absolute_url(self): return reverse('rincon:techpost_details', args=[ self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug ]) class Comment(models.Model): techpost = models.ForeignKey(Techpost, on_delete=models.CASCADE, related_name='comments') comment = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now =True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return "Comment on {}".format(self.techpost) views.py @login_required def techpost_details(request, year, month, day, techpost): techpo…
has comment: http://stackoverflow.com/comment/88155017
has comment: http://stackoverflow.com/comment/88155399
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: django: No Techpost matches the given query
has comment: http://stackoverflow.com/comment/88155359
has comment: http://stackoverflow.com/comment/88154944
answer count: 0
has comment: http://stackoverflow.com/comment/88155918
has comment: http://stackoverflow.com/comment/88155539
type: Question
has comment: http://stackoverflow.com/comment/88155434
has comment: http://stackoverflow.com/comment/88155946
has comment: http://stackoverflow.com/comment/88155282
has comment: http://stackoverflow.com/comment/88154909
has comment: http://stackoverflow.com/comment/88155837
score: 0
has comment: http://stackoverflow.com/comment/88155725

http://stackoverflow.com/comment/88240493
score: 0
has text: You did not include the server-side code in your question.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50614257

http://stackoverflow.com/a/50664952
downvote count: 0
answers question: http://stackoverflow.com/q/50635104
type: Answer
score: 3
upvote count: 3
has body: More general solution should be change condition if in G or H columns is X, then merge together and shift by condition: d = pd.DataFrame({ 'J' : [10,'B','C','C',50, 60], 'I' : ['B',20,30,40,'C', 'D'], 'H' : ['X','A','C','B','X', 'Y'], 'G' : ['Y', 'B', 'A','B','X', 'X'], }, columns=list('GHIJ')) print (d) G H I J 0 Y X B 10 1 B A 20 B 2 A C 30 C 3 B B 40 C 4 X X C 50 5 X Y D 60 m = d'G','H'.eq('X').any(axis=1) print (m) 0 True 1 False 2 False 3 False 4 True 5 True dtype: bool d['H'] = d['G'] + d['H'] d[m] = d[m].shift(-1, axis=1) print (d) G H I J 0 YX B 10 NaN 1 B BA 20 B 2 A AC 30 C 3 B BB 40 C 4 XX C 50 NaN 5 XY D 60 NaN

http://stackoverflow.com/q/50672603
has comment: http://stackoverflow.com/comment/88357253
has comment: http://stackoverflow.com/comment/88355000
type: Question
has body: I need to read data table from .txt file with python 2.7, and parse it to variable sir... I hope someone help me.. I have data on .txt (10 item): LEW01,14/01/2016,07:50:00,15.6,-19,943,-8.7,-228,-19,943,-8.7,-0.9,48.5,4.14,12.39 LEW01,14/01/2016,08:00:00,16.2,-18,944,-8.6,-229,-19,943,-8.6,-0.9,48.5,4.14,12.39 LEW01,14/01/2016,08:10:00,16.8,-19,943,-8.7,-228,-18,944,-8.6,-0.9,48.4,4.16,12.39 LEW01,14/01/2016,08:20:00,17.6,-18,944,-8.6,-229,-18,943,-8.6,-0.9,48.5,4.16,12.44 LEW01,14/01/2016,08:30:00,18.4,-19,943,-8.6,-229,-18,943,-8.6,-0.9,48.5,0.96,12.44 LEW01,14/01/2016,08:40:00,19.4,-18,944,-8.6,-230,-18,943,-8.6,-0.9,48.4,4.18,12.49 LEW01,14/01/2016,08:50:00,20.8,-19,943,-8.7,-230,-18,943,-8.6,-0.9,48.6,4.18,12.49 LEW01,14/01/2016,09:00:00,22.2,-18,944,-8.6,-231,-18,942,-8.6,-0.9,48.6,4.18,12.49 LEW01,14/01/2016,09:10:00,23.4,-19,943,-8.7,-232,-17,942,-8.6,-0.9,48.6,4.18,12.54 LEW01,14/01/2016,09:20:00,24.6,-18,944,-8.6,-233,-17,942,-8.6,-0.9,48.7,4.18,12.59 when i compile with code python: with open('data_peng.txt') as x: for rec in x: a=rec.split(',')[0] b=rec.split(',')[1] c=rec.split(',')[2] d=rec.split(',')[3] e=rec.split(',')[4] f=rec.split(',')[5] g=rec.split(',')[6] h=rec.split(',')[7] i=rec.split(',')[8] j=rec.split(',')[9] k=rec.split(',')[10] l=rec.split(',')[11] m=rec.split(',')[12] n=rec.split(',')[13] o=rec.split(',')[14] output : >>> a 'LEW01' >>> b '14/01/2016' >>> c '09:20:00' >>> d '24.6' >>> e '-18' >>> f '944' >>> g '-8.6' >>> h '-233' >>> i '-17' >>> j '942' >>> k '-8.6' >>> l '-0.9' >>> m '48.7' >>> n '4.18' >>> o '12.59' That I want , for example variable c: >>> c [07:50:00,08:00:00,08:10:00,08:20:00,08:30:00,08:40:00,08:50:00,09:00:00,09:10:00,09:20:00] Please help me, thanks a lot
tagged with: python
accepted answer: http://stackoverflow.com/a/50672715
linked to: http://stackoverflow.com/q/50662220
score: 0
answer count: 2
has title: read data table from .txt file and parse it to variable
possible better answer: http://stackoverflow.com/a/50672629
tagged with: python-2.7
has answer: http://stackoverflow.com/a/50672629
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50672715

http://stackoverflow.com/a/52749252
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50644300
has body: I had the same error. I ended up trying a few things and getting it to work. 1) Updated pip python -m pip install --upgrade pip 2) Update setuptools python -m pip install --upgrade setuptools 3) Install Microsoft 2017 build tools (https://visualstudio.microsoft.com/downloads/), select "Build Tools for Visual Studio 2017." Download install, etc
downvote count: 0

http://stackoverflow.com/q/50659705
answer count: 0
has comment: http://stackoverflow.com/comment/88341268
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/88329728
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/2600191
duplicate of: http://stackoverflow.com/q/2600191
has title: How to print data as a table in python on a local host
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/88329530
has body: for issues in response.json()["issues"]: p = (issues["fields"]["creator"]["emailAddress"]) rep+=(p[:-8]+"\n") print(rep) This will give me email with duplicates abc@company.com abc@company.com cde@company.com cde@company.com I want to print the string with their count available in a table using python,Please help me with this abc@company.com 2 cde@company.com 2
tagged with: python

http://stackoverflow.com/a/77586556
score: 0
type: Answer
has body: Convenient solution would be using @declared_attr.directive decorator. So, in your mixin class you can write something like following: @declared_attr.directive def order(cls) -&gt; Mapped[OrderTable | None]: return relationship(primaryjoin=f'{cls.__name__}.order_no==OrderTable.id')
answers question: http://stackoverflow.com/q/50697065

http://stackoverflow.com/comment/88169456
type: Comment
comment on: http://stackoverflow.com/q/50577697
has text: remove all redundant fields and can you please post also your view? i can give you some hint how to achieve what you are trying to do
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88162667
type: Comment
comment on: http://stackoverflow.com/a/50571083
score: 0
type: AnswerComment
has text: that sounds perfectly logical, thank you very much!! I also did some extra digging [link](https://stackoverflow.com/a/13531072/9855924) . I guess that if these values (strings) were of some mutable type (eg lists) the first case would work too?

http://stackoverflow.com/q/50565735
favorite count: 0
has comment: http://stackoverflow.com/comment/88204055
has title: Big Query table create and load data via Python
has body: I'm trying to extract events from MixPanel, process it and then upload to BigQuery table(Creating a new table). I googled for all the available resources but not useful in solving the issue. Below is my code, # Required modules import import os from mixpanel_api import Mixpanel import collections import json from google.cloud import storage, bigquery # Function to flatten exported file def flatten(d, parent_key='', sep=''): items = [] for k, v in d.items(): new_key = parent_key.replace("PROPERTIES","").replace("-","_").replace("[","").replace("]","").replace("/","").replace("\\","").replace("'","") + sep + k.replace(" ","").replace("_","").replace("$","").replace("-","_").replace("[","").replace("]","").replace("/","").replace("\\","").replace("'","") if parent_key else k #new_key = parent_key.replace("PROPERTIES","").join(e for e in parent_key if e.isalnum()) + sep + k.join(e for e in k if e.isalnum()) if parent_key else k if isinstance(v, collections.MutableMapping): items.extend(flatten(v, new_key.upper(), sep=sep).items()) else: items.append((new_key.upper().replace("-","_").replace("[","").replace("]","").replace("/","").replace("\\","").replace("'",""), v)) #items.append((new_key.upper().join(e for e in new_key if e.isalnum()), v)) #items.append(("ID","1")) #items.append(("PROCESS_DATE","")) #items.append(("DATA_DATE","")) return dict(items) # Start of execution point if __name__ == '__main__': # Secret and token to access API api_sec = 'aa8af6b5ca5a5ed30e20f3af0acdfb2d' api_tok = 'ad5234953e64b908bcd35388875324db' # User input for date range and filename start_date = str(input('Enter the start date(format: YYYY-MM-DD): ')) end_date = str(input('Enter the end date(format: YYYY-MM-DD): ')) file_name = str(input('Enter filename to store output: ')) file_formatter = str(input('Enter filename to store formatted output: ')) # Instantiating Mixpanel object mpo = Mixpanel(api_sec, api_tok ) # Exporting events for the specified date range and storing in the filename p…
has answer: http://stackoverflow.com/a/59229147
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88144728
has comment: http://stackoverflow.com/comment/88369065
tagged with: python
has comment: http://stackoverflow.com/comment/88219228
upvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/88372570
has comment: http://stackoverflow.com/comment/88153188
score: 3
has comment: http://stackoverflow.com/comment/88244829
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/88260387
tagged with: google-bigquery
answer count: 1
downvote count: 0

multiprocess
tags question: http://stackoverflow.com/q/50601116
tag name: multiprocess
type: Tag
tags question: http://stackoverflow.com/q/50593550

http://stackoverflow.com/a/50615331
score: 1
has body: What you usually want in cases like this is a wrapper function. For example, you have a bunch of lines that look like this: self.w[i0-1][j0+1] += 3 The only difference from one line to the next is the two indices and the increment value. So, let's write a method that takes those three things as parameters: def _inc(self, i, j, diff): try: self.w[i][j] += diff except: pass And now, each of those lines can be changed to: self._inc(i0-1, j0+1, 3) … and it'll do what you wanted: increment everything that doesn't raise an exception, do nothing when it does. But, while we're at it, you probably don't want a bare except here. Instead, you want to guard against just the specific exception you were expecting. Which is probably an IndexError. The nice thing about a wrapper function is that we only have to change things in one place instead of 78 places: def _inc(self, i, j, diff): try: self.w[i][j] += diff except IndexError: pass And likewise, if you wanted to change things so it calls log.debug every time there's an exception, you just replace that pass. Or if you want to pre-check or post-check that 0 &lt;= i &lt; len(self.w) and 0 &lt;= j &lt; len(self.w[i]). (And you may want this—notice that if self.w is a list of lists, when i0 is 0, i0-1 is -1, which isn't going to raise an IndexError, it's going to increment the last row…)
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50615293
accepted answer of: http://stackoverflow.com/q/50615293
type: Answer
downvote count: 0

http://stackoverflow.com/a/50623754
has body: Use ast.literal_eval: In [24]: import ast In [25]: ast.literal_eval(table) Out[25]: [['January 2010', 1368, 719], ['February 2010', 1366, 729], ['April 2018', 1429, 480], ['Today', 1440, 448]]
answers question: http://stackoverflow.com/q/50623709
score: 4
type: Answer
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50623709
type: AcceptedAnswer

metis
type: Tag
tags question: http://stackoverflow.com/q/50675790
tag name: metis

http://stackoverflow.com/a/50629875
score: 2
upvote count: 2
has body: Using Series.get pd.Series(df.index,index=df.B).get(df.A) Out[135]: A x 3 y 2 z 1 k 0 x 3 dtype: int64 #df['A']=pd.Series(df.index,index=df.B).get(df.A).values
downvote count: 0
answers question: http://stackoverflow.com/q/50629848
type: Answer

http://stackoverflow.com/q/50640339
has body: I have two arrays of corresponding data (x and y) that I plot as above on a log-log plot. The data is currently too granular and I would like to bin them to get a smoother relationship. Could I get some guidance on how I can bin along the x-axis, in exponential bin sizes, so that it appears linear on the log-log scale? For example, if the first bin is of range x = 10^0 to 10^1, I want to collect all y-values with corresponding x in that range and average them into one value for that bin. I don't think np.hist or plt.hist quite does the trick, since they do binning by counting occurrences. Edit: For context, if it helps, the above plot is an assortativity plot that plots the in vs out degree of a certain network.
tagged with: histogram
has title: How to bin a 2D data along the x-axis with Python
has answer: http://stackoverflow.com/a/50641459
has answer: http://stackoverflow.com/a/50643759
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 1
tagged with: matplotlib
downvote count: 1
type: Question
tagged with: numpy
answer count: 2
tagged with: binning

http://stackoverflow.com/comment/89862862
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50573196
has text: Thank you for the implementation below. Note that your first link above is out of date and the [Google API Client Libraries](https://developers.google.com/api-client-library/) page has a reference to the [photos v1 API description under the Go language](https://github.com/google/google-api-go-client/blob/master/photoslibrary/v1/photoslibrary-api.json) but not under Python. The generic python interface should read that specification and be able to use it generically.
score: 0

http://stackoverflow.com/q/50595690
has title: Python List Comprehension - Accessing Index
type: Question
has body: How would I go about converting this into a list comprehension? queue_lengths = [0, 1, 2, 3] for i, queue in enumerate(queue_lengths): if queue &gt; 0: queue_lengths[i] = queue - 1 Below obviously won't work, because we don't have access to i. queue_lengths[i] = [(queue - 1) for i, queue in enumerate(queue_lengths) if queue &gt; 0]
score: -1
tagged with: list-comprehension
answer count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50595743
type: UnansweredQuestion
tagged with: python
upvote count: 0

http://stackoverflow.com/a/50696636
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50696073
type: Answer
answers question: http://stackoverflow.com/q/50696073
has comment: http://stackoverflow.com/comment/88403295
has comment: http://stackoverflow.com/comment/88402689
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88403188
has comment: http://stackoverflow.com/comment/88402992
has body: Try below code to get required output: lines = ['; '.join([j.text for j in i.find_elements_by_xpath('./td/div | ./td/span/span | ./td/span[not(span)]') if j.text]) for i in driver.find_elements_by_xpath('//*[@class="footballmaincontent"]//tr[position()&gt;2]') if i.text] for line in lines: print line
has comment: http://stackoverflow.com/comment/88404053

http://stackoverflow.com/q/50677770
tagged with: datetime
tagged with: python
accepted answer: http://stackoverflow.com/a/50677830
upvote count: 1
type: AnsweredQuestion
score: 1
tagged with: dataframe
tagged with: date
has title: Pandas: Drop row if it is not a date time
has body: I have a dataframe which contains a column with dates. However, it could be possible that the datestamp is incorrect as for example in the following data with the 'blabla'. import pandas as pd dates = pd.DataFrame(data={'Date':['2015-01-01' , '2015-02-01', '2015-03-01' , '2015-04-01', '2015-05-01' , '2015-06-01', 'blabla']}) dates I would like to transform the columns with the date to datetime and drop each row when the Date column is incorrect. for x in range(len(dates)): dates['Date'].iloc[x] = pd.to_datetime(dates['Date'].iloc[x], format='%Y-%m-%d') So far I can transform the column to a datetime but is there any way to drop the rows that have a incorrect datestamp? Many thanks in advance!
has answer: http://stackoverflow.com/a/50677830
type: Question
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/88355349
comment on: http://stackoverflow.com/a/50672781
type: Comment
has text: well, i would like something more like this
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88178621
type: QuestionComment
score: 0
has text: Are you asking how to make your function return `'appleorangebanana.py'` instead of `'appleorangebanana'`?
comment on: http://stackoverflow.com/q/50582767
type: Comment

http://stackoverflow.com/a/50624293
has comment: http://stackoverflow.com/comment/88258880
upvote count: 9
has body: Use rename with sum by both levels in MultiIndex in columns: label_dict = {'a1': 'A', 'a2': 'A', 'b1': 'B', 'b2': 'B'} res = df.rename(columns=label_dict, level=0).sum(level=[0,1], axis=1) #alternative with groupby #res = df.rename(columns=label_dict, level=0).groupby(level=[0,1], axis=1).sum() print(res) A B 4th 5th 4th 5th 0 2 4 10 12 1 18 20 26 28 2 34 36 42 44
score: 9
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88258832
accepted answer of: http://stackoverflow.com/q/50624223
has comment: http://stackoverflow.com/comment/88259024
answers question: http://stackoverflow.com/q/50624223

http://stackoverflow.com/comment/88282567
has text: Your SyntaxError is because of a needed closing parenthesis to `print()`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50636192

http://stackoverflow.com/comment/88144547
has text: I am getting syntax error at the def melt line, like does this even work in Python? (to define like df: Dataframe,...?).
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50566890
type: AnswerComment

http://stackoverflow.com/a/50611794
has comment: http://stackoverflow.com/comment/88233611
has comment: http://stackoverflow.com/comment/88233584
has body: Is this what you need ? distances_matrix.reset_index().melt(id_vars=['F','Ftags']) Out[434]: F Ftags P Ptags value 0 F1 tag1f1 B1 tag1b1 4.0 1 F2 tag1f2 B1 tag1b1 16.0 2 F1 tag1f1 B2 tag1b2 16.0 3 F2 tag1f2 B2 tag1b2 36.0 4 F1 tag1f1 B2 tag2b2 64.0 5 F2 tag1f2 B2 tag2b2 100.0
answers question: http://stackoverflow.com/q/50611296
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50611296
type: Answer
has comment: http://stackoverflow.com/comment/88234010
score: 2
upvote count: 2

http://stackoverflow.com/q/50656316
tagged with: python
score: 2
tagged with: mingw
answer count: 0
downvote count: 0
tagged with: cython
has title: undefined reference to `_imp__
type: Question
upvote count: 2
favorite count: 0
has body: In Windows 10, I installed Python 2.7 and also Cython 0.28. I installed MinGW and added it to path. I tried to compile a python code from Cython's tutorial. When I use python setup.py build_ext --inplace while I am in the directory that contains the helloworld.pyx and setup.py files I get these errors: running build_ext building 'helloworld' extension C:\MinGW\bin\gcc.exe -mdll -O -Wall -IC:\Python27\include -IC:\Python27\PC -c helloworld.c -o build\temp.win-amd64-2.7\Release\helloworld.o writing build\temp.win-amd64-2.7\Release\helloworld.def C:\MinGW\bin\gcc.exe -shared -s build\temp.win-amd64-2.7\Release\helloworld.o build\temp.win-amd64-2.7\Release\helloworld.def -LC:\Python27\libs -LC:\Python27\PCbuild\amd64 -LC:\Python27\PC\VS9.0\amd64 -lpython27 -lmsvcr90 -o C:\Users\MyPC\helloworld.pyd build\temp.win-amd64-2.7\Release\helloworld.o:helloworld.c:(.text+0x93): undefined reference to `_imp__PyOS_snprintf' build\temp.win-amd64-2.7\Release\helloworld.o:helloworld.c:(.text+0x9b): undefined reference to `_imp__Py_GetVersion' build\temp.win-amd64-2.7\Release\helloworld.o:helloworld.c:(.text+0x107): undefined reference to `_imp__PyOS_snprintf' build\temp.win-amd64-2.7\Release\helloworld.o:helloworld.c:(.text+0x120): undefined reference to `_imp__PyErr_WarnEx' build\temp.win-amd64-2.7\Release\helloworld.o:helloworld.c:(.text+0x160): undefined reference to `_imp__PyString_FromStringAndSize' build\temp.win-amd64-2.7\Release\helloworld.o:helloworld.c:(.text+0x166): undefined reference to `_imp__PyString_InternFromString' build\temp.win-amd64-2.7\Release\helloworld.o:helloworld.c:(.text+0x186): undefined reference to `_imp__PyUnicodeUCS2_DecodeUTF8' build\temp.win-amd64-2.7\Release\helloworld.o:helloworld.c:(.text+0x1af): undefined reference to `_imp__PyObject_Hash' build\temp.win-amd64-2.7\Release\helloworld.o:helloworld.c:(.text+0x21e): undefined reference to `_imp__PyFile_SoftSpace' build\temp.win-amd64-2.7\Release\helloworld.o:helloworld.c:(.text+0x233): undefined refe…
type: UnansweredQuestion

http://stackoverflow.com/comment/127023259
score: 1
type: Comment
comment on: http://stackoverflow.com/a/56611943
type: AnswerComment
has text: @Abu Sufian, it was always possible to list albums and photos, but San Jay's point is a different one: "if you want to move around preexisting pics, update their descriptions or add them to albums .. you cant." That is, you cannot use the API to change anything, for example the description of photos or albums, delete photos or albums, or move photos from one album to another.

http://stackoverflow.com/comment/88250055
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50616923
has text: A simpler version: `pip3 list --user --format=freeze | xargs pip3 uninstall --user -y`.
score: 2

http://stackoverflow.com/q/50667212
answer count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/275018
tagged with: list
linked to: http://stackoverflow.com/q/275018
type: Question
has comment: http://stackoverflow.com/comment/88344836
has body: !curlhttps://raw.githubusercontent.com/MicrosoftLearning/intropython/master/elements1_20.txt -o elements1_20.txt elements = open('elements1_20.txt', 'r') elements_lines = elements.readlines() count = 0 for line in elements_lines: elements_lines[count] = line[:-1].lower() count += 1 print(elements_lines) ['hydrogen', 'helium', 'lithium', 'beryllium', 'boron', 'carbon', 'nitrogen', 'oxygen', 'fluorine', 'neon', 'sodium', 'magnesium', 'aluminum', 'silicon', 'phosphorus', 'sulfur', 'chlorine', 'argon', 'potassium', 'calciu'] As you can see the last element of list is not showing in full? can somebody help me to do so.
has title: Last of element of list is being truncated in python?
score: 0
tagged with: element
tagged with: python
has comment: http://stackoverflow.com/comment/88344680

http://stackoverflow.com/comment/88315391
has text: You need a webserver that can run python.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50652254
score: 1

http://stackoverflow.com/q/50556560
has title: I can not save a plot in pdf format using Matplotlib
tagged with: python
type: AnsweredQuestion
tagged with: matplotlib
has body: I work in a project that uses MatplotLib for plotting and saving simple graphics. But since last update of Windows, if I use text in Latex format, I can not save a picture in pdf format. See below a trial of plotting in Spyder: import numpy as np from matplotlib import pyplot as plt # Data for plot step = 0.001 x = np.arange(0, 2 + step, step) y = x*x*np.cos(10*x) plt.rc('text', usetex=True) plt.rc('font', family='serif') plt.figure(figsize=(19.2, 10.8)) plt.plot(x, y, lw=2) plt.title(r'Function $f(x) = x^2 \cos(10x)$') plt.savefig('plot.pdf', bbox_inches='tight') plt.show() plt.close() This code generate the follow error: Traceback (most recent call last): File "&lt;ipython-input-25-375950fa7d9a&gt;", line 1, in &lt;module&gt; runfile('C:/Users/Fábio/Desktop/plotter.py', wdir='C:/Users/Fábio/Desktop') File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/Fábio/Desktop/plotter.py", line 15, in &lt;module&gt; plt.savefig('plot.pdf', bbox_inches='tight') File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\pyplot.py", line 701, in savefig res = fig.savefig(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\figure.py", line 1834, in savefig self.canvas.print_figure(fname, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\backend_bases.py", line 2216, in print_figure **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\backends\backend_pdf.py", line 2592, in print_pdf self.figure.draw(renderer) File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper return draw(artist, renderer, *args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\figure.py", line 1299, in draw renderer, self, artist…
has answer: http://stackoverflow.com/a/51819042
type: Question
score: 0
accepted answer: http://stackoverflow.com/a/51819042
tagged with: http://stackoverflow.com/tag/pdf
answer count: 1
tagged with: latex

http://stackoverflow.com/comment/88580313
type: Comment
comment on: http://stackoverflow.com/q/50554302
type: QuestionComment
has text: Possible duplicate of [Calling an external command in Python](https://stackoverflow.com/questions/89228/calling-an-external-command-in-python)
score: 0

http://stackoverflow.com/a/50578844
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/88167602
has comment: http://stackoverflow.com/comment/88167469
type: Answer
downvote count: 2
answers question: http://stackoverflow.com/q/50578654
has body: from scipy.ndimage.filter import gaussian_filter1d will do the job. But any basic Python textbook will tell you that.

http://stackoverflow.com/comment/88318330
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50652473
has text: @cricket_007 I’m unfamiliar with this concept.
score: 0

wagtail
tag name: wagtail
tags question: http://stackoverflow.com/q/50652848
type: Tag
tags question: http://stackoverflow.com/q/50660798

http://stackoverflow.com/comment/88231671
type: Comment
comment on: http://stackoverflow.com/a/50594901
has text: Pyramid itself stores nothing. Your app may use any persistence system, including a database or writing to disk, to store data on the server. If you want to track the number of users who are authenticated and associated data, then you'll need to use a package or write your own. Here's a list of add-ons that you can filter by Auths: https://trypyramid.com/resources-extending-pyramid.html
type: AnswerComment
score: 0

http://stackoverflow.com/q/50628787
score: 0
has body: I have just created a unit test for my code and placed it in a test directory. It tests the functionality of module a which depends on module b. My directory tree looks like: ├── src | ├── __init__.py | ├── a.py │ ├── b.py ├── test/ │ ├── __init__.py │ ├── unit.py The unit test looks like: import unittest from src import a class TestUtils(unittest.TestCase): def test_function(self): self.assertEqual(a.func(), 1) if __name__ == '__main__': unittest.main() When I run with: python test/unit.py I get the error: Traceback (most recent call last): File "test/unit.py", line 2, in &lt;module&gt; from src import a File "/home/src/a.py", line 13, in &lt;module&gt; from b import B ImportError: No module named 'b' What can I do to keep this structure and be able to run both my program and the test?
has comment: http://stackoverflow.com/comment/88269567
type: Question
tagged with: python-import
has comment: http://stackoverflow.com/comment/88267755
has title: name 'b' is not defined when imported from unit test
has comment: http://stackoverflow.com/comment/88267787
has comment: http://stackoverflow.com/comment/88268123
has comment: http://stackoverflow.com/comment/88268444
has comment: http://stackoverflow.com/comment/88267896
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88267570
answer count: 0

libsvm
tags question: http://stackoverflow.com/q/50697579
tag name: libsvm
type: Tag

http://stackoverflow.com/comment/88294360
score: 0
has text: Use a requirements file to install packages in your venv.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50642086

http://stackoverflow.com/a/50846354
has body: Yes, there is. After starting Atom, open the script you wish to run. Then open command palette and select 'Python: Select interpreter'. A list appears with the available python versions listed. Select the one you want and hit return. Now you can run the script by placing the cursor in the edit window and right-clicking the mouse. A long menu appears and you should choose the 'Run python in the terminal window'. This is towards the bottom of the long menu list. The script will run using the interpreter you selected.
type: Answer
answers question: http://stackoverflow.com/q/50667214
score: 0

http://stackoverflow.com/q/50556847
favorite count: 0
linked to: http://stackoverflow.com/q/13530998
has comment: http://stackoverflow.com/comment/88150872
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50571083
type: AnsweredQuestion
tagged with: list
has title: Python attribute that holds other existing attributes in a list
tagged with: oop
has comment: http://stackoverflow.com/comment/88150915
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88124606
accepted answer: http://stackoverflow.com/a/50571083
score: 0
has comment: http://stackoverflow.com/comment/88124717
has body: I am currently working on a python-sqlite project, and i am novice to both. I have created a class that has some attributes declared inside the __init__ method. I need another attribute that will be a list or array, that will contain some of the already declared attributes of the class. What i want is my list to contain just a reference of the original attributes. I need this structure in order to be able to call these attributes together, to iterate on them, but i want to be able to call them separately, too. At first I tried to create that list attribute inside the __init__ method, after the rest declarations. When I create an instance, however, and change the initial value of one of the attributes, the attribute in the list is not updated. Then I tried to create that same list attribute inside another method of the class, instead of inside the init, and call it from inside my code, and it did what I wanted to. Why does the different approach has different results? Here is the code at both cases: Case #1 class Tools(): def __init__(self): self.name = "defaultname" self.manufacturer = "defaultmanuf" self.tooldetails = [self.name, self.manufacturer] def get_details(self): return self.tooldetails Case #2 class Tools(): def __init__(self): self.name = "defaultname" self.manufacturer = "defaultmanuf" def _set_detail_list(self): self.tooldetails = [self.name, self.manufacturer] def get_details(self): _set_detail_list() return self.tooldetails And when I create an instance: tool1 = Tools() tool1.name = 'abc' tool1.get_details() The first case gives me ["defaultname", "defaultmanuf"] while the second gives me ["abc","defaultmanuf"]. My question is what is the reason python gives me different output for each case? It seems like I miss something important about how initialization is working.. dir() and other similar functions or magic methods could be able to give me what i want, but i think they are not flexible enough if you want many different lists with different sets o…
answer count: 1

http://stackoverflow.com/q/50593184
tagged with: python
has answer: http://stackoverflow.com/a/50593912
type: Question
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/88195811
has title: Delete in a BST
has body: I was wondering why my delete method for my BST is not working. I have implemented recursion and for someone reason, no nodes are being deleted. def delete(self,node, val): if(node == None): return None if(val &lt; node.data): node.left = self.delete(node.left,val) elif( val &gt; node.data): node.right = self.delete(node.right,val) else: if(node.right ==None and node.left ==None): return None elif(node.left==None): # delete the node holding 1 child node=node.right return node elif(node.right==None): node = node.left return node elif(node.right and node.left): delete = node.right while(delete.left): delete = delete.left node.data = delete.data node.right = delete(node.right,delete.data) return node testTree.delete(testTree.root,30) testTree.printInorder(testTree.root) Could it be I'm not deleting directly?
tagged with: binary-search-tree
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88195807

http://stackoverflow.com/q/50607804
tagged with: spell-checking
downvote count: 0
score: 1
tagged with: diacritics
has comment: http://stackoverflow.com/comment/88225904
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51122014
tagged with: python
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51122014
has body: I need to purge a DataBase that is in Spanish but the requirement is that I must keep accent marks. For instance, if the DB contains "Administración" and "Administracion" I have to identify them as equals but keep the one with the accent mark. After some research every solution, like turn Unicode to ASCII or use PyEnchant, keeps the one without the accent mark. Is there any Library (For Python 3.5) or way to determine the correct one and keep it?
type: Question
answer count: 2
has title: Keep records with Spanish accents in Database using Python
upvote count: 1
has comment: http://stackoverflow.com/comment/88225584
possible better answer: http://stackoverflow.com/a/51123558
has answer: http://stackoverflow.com/a/51123558
has comment: http://stackoverflow.com/comment/88225617

http://stackoverflow.com/comment/88100970
score: 0
type: QuestionComment
type: Comment
has text: It would be useful if you had an example to go off of
comment on: http://stackoverflow.com/q/50544917

http://stackoverflow.com/comment/88152596
comment on: http://stackoverflow.com/q/50571381
type: Comment
has text: @juanpa.arrivillaga What do you mean by one big array?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88102493
type: Comment
type: AnswerComment
has text: https://www.programiz.com/python-programming/methods/built-in/isinstance
score: 0
comment on: http://stackoverflow.com/a/50545588

http://stackoverflow.com/comment/88286304
type: AnswerComment
score: 0
type: Comment
has text: When I change `forms.Form` to `SignupForm` I get this error: `django.core.exceptions.ImproperlyConfigured: Module "draft1.forms" does not define a "AllauthSignupForm" class` - Any idea? I imported `SignupForm` aswell
comment on: http://stackoverflow.com/a/50629332

http://stackoverflow.com/a/50569304
score: -1
has body: You can use map: d = [00, 11, 22, 33, 44, 55] s = [22, 55] new_d = list(map(lambda x:int(x in s), d)) Output: [0, 0, 1, 0, 0, 1]
type: Answer
answers question: http://stackoverflow.com/q/50569284
downvote count: 1
upvote count: 0

http://stackoverflow.com/q/50656414
type: Question
has comment: http://stackoverflow.com/comment/88330686
has title: Python - taking each item in a list and adding it to an integer
has comment: http://stackoverflow.com/comment/88325457
tagged with: ascii
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/88322821
downvote count: 1
has comment: http://stackoverflow.com/comment/88323682
favorite count: 0
has body: This is my task: https://i.sstatic.net/qv6us.png I have tried to get each item out of the ASCII list by using z as the list item so the program increases z by one every time I go through the for loop. ciphertext = [] z=0 for item in messagelist: # messagelist a list of characters If there is a space then I want to ignore it. if ' ' in messagelist: break Then I want it to add the item to an integer:'offsetfactor'. else: # ascii list is a list of ascii codes/integers y = asciilist[z] + offsetFactor # offset factor is a randomly generated integer print (y) Then if the answer is more than 126, I will minus 94 and turn the answer into an ASCII character. Then I want to append all the ASCII characters to a list and convert the list into a string. if y &gt; 126: y = y - 94 asciichar = str(chr(y)) # turns y into an ascii character ciphertext.append(asciichar) # adds the ascii character to a list called ciphertext else: asciichar = str(chr(y)) ciphertext.append(asciichar) z+=1 encrypted = str(ciphertext) # turns ciphertext into a string print ('Your encrypted message is: ',encrypted) This doesn't seem to be working as 'encrypted' is printed as an empty list. I will be grateful for any help as it took me ages even to write the question!
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/50607128
has comment: http://stackoverflow.com/comment/88322910
tagged with: list
answer count: 0
tagged with: caesar-cipher

http://stackoverflow.com/comment/88532857
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50667128
has text: @TarunLalwani i am attempting to track the count of all str allocations through the builtin `str` method, I"m hoping to increment a counter whenever `str()` is called

http://stackoverflow.com/comment/88336355
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50663131
has text: It sounds like you are doing something like `x = 3; len(x)` or `x = 3; x[-1]`. `array` isn't what you think it is.

http://stackoverflow.com/comment/88289335
score: 0
type: QuestionComment
has text: Have you seen my answer?
type: Comment
comment on: http://stackoverflow.com/q/50638823

http://stackoverflow.com/q/50554589
has body: I'm trying to an item to my list:'pepperoni' by using append. pizza_vege=['tomato sauce','mushrooms','pepper','cheese','garlic powder'] print(pizza_vege) pizza_peper=pizza_vege.append('peperoni') print(pizza_peper) #The result here should show the list of pizza_vege and add 'pepperoni to it' The result shown is: ['tomato sauce', 'mushrooms', 'pepper', 'cheese', 'garlic powder'] None I don't understand why 'print' returns 'None' in output. Isn't it supposed to join the two sequences?? thank you all !
has answer: http://stackoverflow.com/a/50554610
answer count: 2
downvote count: 0
duplicate of: http://stackoverflow.com/q/11205254
tagged with: string
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88119911
tagged with: python
tagged with: list
has answer: http://stackoverflow.com/a/50554613
score: 1
has title: String appending and why the print of a different variable returns none?
upvote count: 1
type: Question
linked to: http://stackoverflow.com/q/1682567

http://stackoverflow.com/comment/88156572
score: 0
comment on: http://stackoverflow.com/a/50571913
type: Comment
has text: Try vim or nano, then. Otherwise, there might not be a built in text editor. You can clone a git repo locally. `pip install click` should work fine if you have pip installed
type: AnswerComment

http://stackoverflow.com/comment/88177510
has text: @WhatsThePoint & DevX: That is a different issue about calling the parent property in the child property. It does not address the problem I mention here.
comment on: http://stackoverflow.com/q/50584041
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/63906135
answers question: http://stackoverflow.com/q/50686096
type: Answer
downvote count: 0
has body: I've been doing some research on this too, and apparently Mac OSX doesn't support background color for buttons or the relief styles. You can find it Here. However, there is a module I've found that allows for more customization for OSX. You can find IT here.
score: 1
upvote count: 1

http://stackoverflow.com/a/50693985
score: 2
has body: The problem was regarding how I formed the chain. It wasn't correct (at least for my celery version), though suggested in number of places. The approach that works for me. feed_chain = chain() for feed in feed_list: feed_chain |= chord(args) feed_chain.delay()
answers question: http://stackoverflow.com/q/50692471
upvote count: 2
downvote count: 0
type: Answer

http://stackoverflow.com/q/50684570
type: UnansweredQuestion
tagged with: python
has body: i would like to know why by comparing two real numbers (e.g. bool(r1 == r2)) in sage cas online it returns wrong boolean values. E.g.§1: (x,y,z)=var('x,y,z'); x=2 r1= (sin(x)).n() r2= (sin(x)).n(digits=3) print r1, type(r1) print r2, type(r2) bool(r1==r2) 0.909297426825682 == 0.909 True But E.g.§2 (x,y,z)=var('x,y,z'); x=2 r1= (sin(x)).n() r2= (0.909).n(digits=3) print r1, type(r1) print r2, type(r2) bool(r1==r2) 0.909297426825682 == 0.909 False Or e.g.§3 (x,y,z)=var('x,y,z'); x=2 r1= 0.909297426825682.n(digits=3) r2= (0.909).n(digits=3) print r1, type(r1) print r2, type(r2) bool(r1==r2) 0.909 == 0.909 False In my project I would like to compare user answer which can be rounded e.g. to 3 decimal places with 53 bits CAS-solution solution which can be both symbolic and numeric values. Thanx
has title: Comparing two numbers in sage
tagged with: numbers
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88388680
tagged with: numeric
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/88382534
tagged with: sage
upvote count: 1
has answer: http://stackoverflow.com/a/51795934
favorite count: 0

http://stackoverflow.com/q/50600750
type: Question
accepted answer: http://stackoverflow.com/a/50638973
answer count: 2
tagged with: class
possible better answer: http://stackoverflow.com/a/50602377
score: 0
has answer: http://stackoverflow.com/a/50602377
linked to: http://stackoverflow.com/q/30420621
tagged with: python
tagged with: attributes
has body: Intro Comming from this question Python- creating object instances in a loop with independent handling I was asking myself how to access the attributes of all rather than just a single instance, if you have created a list of instances. Minimal Example Consider creating a list of company instances with the attributes name and value. Now I would like to know, which of these companies does have the highest value. So far I am simply storing the values of the value attribute in an array and then find the index of the maximum value. import numpy as np class Company(object): def __init__(self, name, value): self.name = name self.value = value companies = [] for name in 'ABC': companies.append(Company(name, np.random.rand())) l = len(companies) liste = np.zeros(l) for i in range(l): liste[i] = companies[i].value ind = np.unravel_index(np.argmax(liste), liste.shape) print("Highest value: ", liste[ind]) print("Company of highest value: ", companies[ind[0]].name) Questions 1) Is there a different way to create this list of all attribute values without a for-loop? 2) Is there a direct way to find the instance in a list, for which the value of a certain attribute is maximal?
has title: How to access the attributes of all instances stored in a list?
type: AnsweredQuestion
tagged with: oop
has answer: http://stackoverflow.com/a/50638973
tagged with: instances

scrapy-splash
tag name: scrapy-splash
tags question: http://stackoverflow.com/q/50626531
tags question: http://stackoverflow.com/q/50697834
type: Tag
tags question: http://stackoverflow.com/q/50660887

http://stackoverflow.com/comment/88307946
type: Comment
has text: Thanks @abarnert and Patrick Artner. This helps
score: 0
comment on: http://stackoverflow.com/q/50648096
type: QuestionComment

http://stackoverflow.com/q/50686700
downvote count: 0
has comment: http://stackoverflow.com/comment/88383641
has comment: http://stackoverflow.com/comment/88383345
has comment: http://stackoverflow.com/comment/88383321
has comment: http://stackoverflow.com/comment/88383314
has comment: http://stackoverflow.com/comment/88383579
has comment: http://stackoverflow.com/comment/88383311
favorite count: 0
has comment: http://stackoverflow.com/comment/88383473
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: dictionary
has body: I have a function main that, given a string, should select one of many other functions, call it with some specific args and kwargs, and return its result. The most straightforward implementation of this is def main(string): if string == "a1": return a(1) elif string == "a2": return a(2) elif string == "b": return b("foo", symbol=True) # ... elif string == "y": return y() assert string == "z", "Illegal string '{}'.".format(string) return z("bar", 25) but I don't like this unsightly huge conditional. More readable is perhaps def main(string): d = { "a1": a(1), "a2": a(2), "b": b("foo", symbol=True), # ... "z": z("bar", 25), } return d[string] This also eliminates possible typos where a key is elif'd twice – nice. Unfortunately, this initializes every entry in the dictionary just to throw away almost all of them right away. Defining d outside of main isn't a big improvement either in my case since main is only executed a few times. Adding some lambdas works def main(string): d = { "a1": lambda: a(1), "a2": lambda: a(2), "b": lambda: b("foo", symbol=True), # ... "z": lambda: z("bar", 25), } return d[string]() main("a") but again, this makes the code less readable. I'm wondering whether it's possible to define something like a dictionary iterator: With all key-value pairs specified, but the value only evaluated when picked. Perhaps there's a better idea. Hints?
duplicate of: http://stackoverflow.com/q/60208
has comment: http://stackoverflow.com/comment/88383395
score: 1
linked to: http://stackoverflow.com/q/60208
has title: dictionary with values only evaluated when selected
has comment: http://stackoverflow.com/comment/88386246
has comment: http://stackoverflow.com/comment/88383356
type: Question

http://stackoverflow.com/comment/111242723
type: Comment
type: QuestionComment
score: 0
has text: As a side note, when using the `-ss` before the `-i` option, ffmpeg tries to seek to that position without bothering decompressing every single frame to that point.
comment on: http://stackoverflow.com/q/50594412

http://stackoverflow.com/comment/88178184
has text: Thank you so much. It worked. So does this mean we can use append for array?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50584472

http://stackoverflow.com/comment/88354561
type: Comment
score: 0
has text: Without seeing the view, I'm guessing you're not passing the form into the context of the view.
type: QuestionComment
comment on: http://stackoverflow.com/q/50669697

http://stackoverflow.com/q/50592219
downvote count: 0
tagged with: unit-testing
type: Question
type: AnsweredQuestion
has title: Testing Click application prompting with multiple inputs
tagged with: pytest
tagged with: command-line-interface
score: 5
tagged with: python-click
answer count: 1
has body: I've written a small command line application using Click and Python, which I am now trying to write tests for (mainly for the purpose of learning how to test Click apps so I can move on to testing the one I'm actually developing). Here's a function I'm trying to test: @click.group() def main(): pass @main.command() @click.option('--folder', '-f', prompt="What do you want to name the folder? (No spaces please)") def create_folder(folder): while True: if " " in folder: click.echo("Please enter a name with no spaces.") folder = click.prompt("What do you want to name the folder?", type=str) if folder in os.listdir(): click.echo("This folder already exists.") folder = click.prompt("Please choose a different name for the folder") else: break os.mkdir(folder) click.echo("Your folder has been created!") I'm trying to test this using the built in testing from Click (http://click.pocoo.org/6/testing/ and http://click.pocoo.org/6/api/#testing for more details) as well as pytest. This works well in the case where I test an acceptable folder name (ie. one that does not have spaces and that does not already exist). See below: import clicky # the module we're testing import os from click.testing import CliRunner import click import pytest input sys runner = CliRunner() folder = "myfolder" folder_not = "my folder" question_create = "What do you want to name the folder? (No spaces please): " echoed = "\nYour folder has been created!\n" def test_create_folder(): with runner.isolated_filesystem(): result = runner.invoke(clicky.create_folder, input=folder) assert folder in os.listdir() assert result.output == question_create + folder + echoed I now want to test this function in the case where I provide a folder name that's not allowed, such as one with spaces, and then after the prompt telling me I can't have spaces, I will provide an acceptable folder name. However, I cannot figure out how to make click.runner accept more than one input value, and that's the only way I can think to m…
accepted answer: http://stackoverflow.com/a/50604744
favorite count: 0
upvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/50604744

http://stackoverflow.com/comment/88231031
comment on: http://stackoverflow.com/a/50607271
score: 0
type: AnswerComment
type: Comment
has text: @Nikhil Without making things too complicated, you can keep track of how many arguments each command takes and make sure the user inputs that many arguments. I can show you an example of that.

http://stackoverflow.com/a/53606725
has body: ok. i solved it . maybe it was problem with socket.recv(size) answer is at code here : https://github.com/HarshVaragiya/Chat-Application/tree/master/VideoChat
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50656167

http://stackoverflow.com/q/50621281
type: UnansweredQuestion
downvote count: 2
has title: how to dynamically create array variable in json
has comment: http://stackoverflow.com/comment/88252616
score: -2
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/88253181
type: Question
has answer: http://stackoverflow.com/a/50621880
upvote count: 0
answer count: 1
has body: In python, I can use the below code to dynamically create IP address array to store n number of IP addresses. for i in range(12): addr[i] = "10.1.1." + str(i) print addr[i] I want a similar code for JSON file. Is it possible to define variables with looping in JSON file?
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88252543
tagged with: python-3.x

http://stackoverflow.com/a/50635746
answers question: http://stackoverflow.com/q/50633581
has comment: http://stackoverflow.com/comment/88281628
has body: Answer found here: Loading and parsing a JSON file with multiple JSON objects in Python worked perfectly
type: Answer
score: 0

http://stackoverflow.com/a/50687650
score: 0
has body: Dialogflow includes the event (actions_intent_OPTION) as a context with the key as the selected option. In the raw request it looks something like this: "contexts": [ { "name": "actions_intent_option", "parameters": { "OPTION": "YOUR_KEY_HERE" }, "lifespan": 0 } ] With flask-assistant you can read the value from the context_manager (which contains all contexts in the active session): from flask_assistant import context_manager selected_option = context_manager.get('actions_intent_option').get('OPTION') The key can be whatever you find most useful, it will not be shown to the user. Typically you would use some kind of id that uniquely identifies your list items.
type: Answer
accepted answer of: http://stackoverflow.com/q/50674199
answers question: http://stackoverflow.com/q/50674199
has comment: http://stackoverflow.com/comment/88391713
type: AcceptedAnswer

http://stackoverflow.com/a/50693406
has body: Maybe you need to create a job that will read Excel everyday for that day's schedule times and create a job to run the target .py file for each time listed in the list OK, to be more specific to read data from files, please check following resource https://python101.pythonlibrary.org/chapter8_file_io.html Then to interact with Windows to create scheduled tasks, please refer to https://ziade.org/2007/11/01/scheduling-tasks-in-windows-with-pywin32/ I hope that is helpful
answers question: http://stackoverflow.com/q/50693350
score: -1
downvote count: 1
type: Answer
upvote count: 0
has comment: http://stackoverflow.com/comment/88517333
has comment: http://stackoverflow.com/comment/88517152

http://stackoverflow.com/comment/88223706
type: AnswerComment
comment on: http://stackoverflow.com/a/50607012
has text: glad it worked. make sure to mark this as correct so we don't get answer spam and such
score: 0
type: Comment

http://stackoverflow.com/comment/93513811
comment on: http://stackoverflow.com/q/50579308
score: 0
has text: Hello, were you able to solve your problem?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88334101
type: AnswerComment
score: 0
has text: Sorry for the typo. Updated the post with `root.ids.input_screen.key_board.entryText`
type: Comment
comment on: http://stackoverflow.com/a/50661456

http://stackoverflow.com/comment/88377842
type: QuestionComment
comment on: http://stackoverflow.com/q/50684013
has text: @Dark np.select is the way to go for this
score: 0
type: Comment

http://stackoverflow.com/a/50669512
score: 0
has comment: http://stackoverflow.com/comment/88424758
answers question: http://stackoverflow.com/q/50665466
has body: There are different things going on here. Class imbalance As already discussed in the comments, your training set consists of 2941 negative samples (faces from other persons than you) and 308 positive samples (images with your face on it). So as classifier which always votes for the negative class gets 2941 of the 3249 samples right, i.e. 90.5%. Your training accuracy score should be read with this information in mind, because your 89.4% hint that your network has learnt nothing valuable. What you could try: Oversample the minority class Undersample the majority class Use weights in your loss function There exists a vast body of literature and tutorials on this topic, so just look around a bit. Model capacity/network design You mentioned in the comments that after using balanced training data, the loss still doesn't decrease. This hints that the capacity of your model is not high enough or that your model is not well designed for that task. There exist many different network structures for image processing tasks, depending on what exactly the task is. For example, a network for doing pixel-wise classification and instance segmentation (like Mask RCNN) will look different from a network that is designed to do face recognition (like FaceNet). Even if we only focus on one task (in this/your case: face recognition) the network structures you find will look very different. So what does that mean? Building a neural network for a specific task is not trivial and it is not easy to predict which structures work well for which task. A lot of trial and error is often needed, to find a suitable structure. The model capacity describes how "powerful" your model is. There is no rigorous definition for this but you can think about it like this: Different tasks can be harder or easier to solve. A certain model can only solve problems which are "easy enough" and on more difficult problems the model will only show poor performance. The model capacity often goes hand in hand with the n…
type: Answer

http://stackoverflow.com/a/50557387
upvote count: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50557321
score: 1
has body: In your code, you define a function main() but you never call it. To fix this, either remove def main() from the cell, that is, simply execute the code that you want to run x = 0 while (x &lt; 5): print (x) x = x + 1 or call your function main(): def main(): x = 0 while (x &lt; 5): print (x) x = x + 1 main()

macos-sierra
tag name: macos-sierra
tags question: http://stackoverflow.com/q/50657368
type: Tag

http://stackoverflow.com/comment/88194303
has text: One other caveat. Sometimes Amazon will use the word "List:" instead of "Price:"
comment on: http://stackoverflow.com/a/50592399
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88344242
has text: your first request is actually this one: `https://www.finviz.com/screener.ashx?v=161&r=0`, you could easily loop from `r = 0` to 60 with a step of 20.
comment on: http://stackoverflow.com/q/50667127
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50613165
tagged with: python-2.7
tagged with: lxml
upvote count: 1
has answer: http://stackoverflow.com/a/50613218
answer count: 1
has body: I am using lxml to generate a large XML file. One of the tags used in the file is "lambda" so I cannot define it as I normally would. (and no, I cannot change the name of the tag) Code: import lxml.etree as ETree import lxml.builder as lxmlBuilder E = lxmlBuilder.ElementMaker() root = E.root lbd = E.lambda #error since lambda is reserved myTree = root( lbd('1') ) print ETree.tostring(myTree, pretty_print=True) Intended Result: 1 Since this is the case, I just wanted to enter the "lambda" tags manually. However, when I try to do this, the "less than" or "greater than" symbols around "lambda" are converted to &lt and &gt. Code: E = lxmlBuilder.ElementMaker() root = E.root lbd = " %f " % 1 #by hand myTree = root( lbd ) print ETree.tostring(myTree, pretty_print=True) Result: 1.0000 How can I prevent the < and > symbols from being converted like this?
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
has title: Python lxml prevent less than < or greater > from being converted to &lt and &gt
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/50613218

http://stackoverflow.com/comment/88107037
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50548111
type: QuestionComment
has text: You need to get rid of the circular imports and adding modules for common code is a good way to do that. So, I'd say yes, one or more of the descriptors should move. You are doing `foo.foo()` outside of a function which is generally frowned upon (mere import shouldn't run a lot of code). If that can go inside another function then that function can do the `import foo` and remove the problem.

math
tags question: http://stackoverflow.com/q/50584748
tags question: http://stackoverflow.com/q/50694644
tags question: http://stackoverflow.com/q/50693445
tags question: http://stackoverflow.com/q/50601513
tags question: http://stackoverflow.com/q/50667849
type: Tag
tags question: http://stackoverflow.com/q/50692725
tags question: http://stackoverflow.com/q/50622088
tags question: http://stackoverflow.com/q/50666057
tags question: http://stackoverflow.com/q/50576194
tags question: http://stackoverflow.com/q/50690414
tags question: http://stackoverflow.com/q/50585504
tags question: http://stackoverflow.com/q/50671180
tag name: math
tags question: http://stackoverflow.com/q/50590082
tags question: http://stackoverflow.com/q/50602387

http://stackoverflow.com/comment/88276818
type: Comment
type: QuestionComment
score: 6
has text: Forgive me if I'm wrong, but this doesn't seem related to java
comment on: http://stackoverflow.com/q/50633262

http://stackoverflow.com/comment/88272401
score: 2
comment on: http://stackoverflow.com/q/50631214
has text: can you please show your code?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88271768
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50630693
type: Comment
has text: You'd need to change your input shape to have a single sample. I can't tell much more without seeing the rest of your code.

http://stackoverflow.com/comment/88347381
has text: Please don't make more work for people by vandalizing your posts. By posting on the Stack Exchange (SE) network, you've granted a non-revocable right, under the [CC BY-SA 3.0 license](//creativecommons.org/licenses/by-sa/3.0), for SE to distribute that content (i.e. regardless of your future choices). By SE policy, the non-vandalized version of the post is the one which is distributed. Thus, any vandalism will be reverted.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50667127
score: 3

http://stackoverflow.com/comment/88351105
type: Comment
type: QuestionComment
has text: Just some clarifications: is dense here the imported Keras layer type "Dense"? Is x an input (values, another layer), that you are then reassigning to the variable x? Maybe some more description of your expected outputs or comments inline would help. I'm having a hard time understanding what you expect from the source provided here
score: 0
comment on: http://stackoverflow.com/q/50669431

http://stackoverflow.com/comment/88193446
score: 0
comment on: http://stackoverflow.com/q/50592013
type: Comment
type: QuestionComment
has text: Unfortunately they do vary in length.

http://stackoverflow.com/comment/88383927
score: 0
type: Comment
type: QuestionComment
has text: @MarkGinsburg In that case use `df.to_dict()` and post it here.
comment on: http://stackoverflow.com/q/50686970

http://stackoverflow.com/q/50650957
accepted answer: http://stackoverflow.com/a/50687572
tagged with: side-effects
has title: What can go wrong if operators have side-effects?
tagged with: python
has comment: http://stackoverflow.com/comment/88314187
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/50687572
tagged with: operator-overloading
has comment: http://stackoverflow.com/comment/88312830
has answer: http://stackoverflow.com/a/50687603
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/50687603
has body: I came across a Python library that defines a class analogous to the following, where the &gt;&gt; operator is overloaded to have a global side-effect: from collections import defaultdict class V(object): """A Vertex in a graph.""" graph = defaultdict(list) # accessed globally def __init__(self, label): self.label = label def __rshift__(self, other): V.graph[self].append(other) return other def __repr__(self): return 'V(%r)' % (self.label,) The library does this because "it gives the user some nice syntax" for symbolically building up networks, by writing down simple expressions such as: a = V('a') b = V('b') c = V('c') a &gt;&gt; b &gt;&gt; c &gt;&gt; c in order to build a network where a is connected to b, which is connected to c, which is recurrently connected to itself. There is similar machinery within the +, *, and @ operators as well. All of this behaviour is documented and to be expected by the user. However, are there any strange things that could happen, where you wouldn't think the expression should be evaluated—but actually is—or vice-versa? That is, does the execution model for Python ever assume that certain expressions are free from any side-effects? I want to know if there is any precedent, or whether any special precautions need to be taken by the user.
has comment: http://stackoverflow.com/comment/88313286

http://stackoverflow.com/a/50640550
has comment: http://stackoverflow.com/comment/88292432
has body: Here's an attempt, binning is the same as @jezrael (except the last bin which I'm not sure should be limited to 31... is there a way to have open intervals with pd.cut?) import pandas as pd df = pd.DataFrame({ "CreatedDate": ['09-08-16 0:00','22-08-16 0:00','23-08-16 0:00','28-08-16 0:00','29-08-16 0:00','30-08-16 0:00','31-08-16 0:00']}) df["CreatedDate"] = pd.to_datetime(df.CreatedDate) # sort by date df = df.sort_values("CreatedDate") # group consecutive dates oneday = pd.Timedelta("1 day") df["groups"] = (df.diff() &gt; oneday).cumsum() counts = df.groupby("groups").count()["CreatedDate"] # bin streaks = (pd.cut(counts, bins=[0,3,7,15,1000000], labels=['1-3', '4-7','8-15', '&gt;=16']) .value_counts() .rename_axis("streak") .reset_index(name="count")) print(streaks) streak count 0 1-3 2 1 4-7 1 2 &gt;=16 0 3 8-15 0
accepted answer of: http://stackoverflow.com/q/50637603
score: 0
answers question: http://stackoverflow.com/q/50637603
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88292254
has comment: http://stackoverflow.com/comment/88292642
has comment: http://stackoverflow.com/comment/88292661
type: Answer

http://stackoverflow.com/comment/88166372
comment on: http://stackoverflow.com/q/50577760
score: 0
type: Comment
type: QuestionComment
has text: Can you reduce the dataframe to a minimum of lines (5-6), so that it is possible to grasp what is right or wrong with your substitution rules?

http://stackoverflow.com/comment/88219217
score: 0
type: Comment
type: QuestionComment
has text: I really really appreciate your help. I am also very curious to find out that in fact is causing this.
comment on: http://stackoverflow.com/q/50581156

http://stackoverflow.com/a/50599773
has body: I think need GroupBy.transform for joined values to new column as strings: df['col 5'] = (df.groupby(['col 1','col 2','col 3'])['col 4'] .transform(lambda x: ','.join(x.astype(str)))) print (df) col 1 col 2 col 3 col 4 col 5 0 A B C 25 25,22,23,45 1 A B C 22 25,22,23,45 2 A B C 23 25,22,23,45 3 A B C 45 25,22,23,45 4 P Q R 9 9,109,20 5 P Q R 109 9,109,20 6 P Q R 20 9,109,20 If need lists use join: df = df.join(df.groupby(['col 1','col 2','col 3'])['col 4'] .apply(list).rename('col 5'), on=['col 1','col 2','col 3']) print (df) col 1 col 2 col 3 col 4 col 5 0 A B C 25 [25, 22, 23, 45] 1 A B C 22 [25, 22, 23, 45] 2 A B C 23 [25, 22, 23, 45] 3 A B C 45 [25, 22, 23, 45] 4 P Q R 9 [9, 109, 20] 5 P Q R 109 [9, 109, 20] 6 P Q R 20 [9, 109, 20]
has comment: http://stackoverflow.com/comment/88209446
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88209003
accepted answer of: http://stackoverflow.com/q/50599715
answers question: http://stackoverflow.com/q/50599715
upvote count: 1
score: 1

http://stackoverflow.com/comment/88237108
comment on: http://stackoverflow.com/a/50612000
type: AnswerComment
score: 0
has text: Something I forgot to mention in my post when translating it to more general terms is the that the strings which are in a,b, and c are only substrings of those found in x. So x would actually be more like x = [{'thing' : 'apple | fruit'}, {'thing': 'dog | animal'}, {'thing' : 'boat | vehicle'}]
type: Comment

http://stackoverflow.com/comment/88144749
comment on: http://stackoverflow.com/q/50567008
score: 0
type: QuestionComment
has text: just a quick question...how would you define your roc without telling the system how you did? The syntax, as you can read from the error Traceback and the docs, `roc_auc_score(y_true, y_score)` does not correspond to `roc_auc_score(X,y)`
type: Comment

http://stackoverflow.com/comment/109794304
type: Comment
has text: Can you import the file?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50645010

http://stackoverflow.com/comment/88141345
type: Comment
comment on: http://stackoverflow.com/a/50565247
has text: In my experience especially the case of changing functions arguments in the definition happens really often during the beta-phase of a code, causing lots of confusion. Even if the user is also the beta-tester and the programmer. ;) Often it is just extremely complicated to keep track of all function definitions you have with thousands/tenthousands LOC.
type: AnswerComment
score: 0

http://stackoverflow.com/a/50661068
has body: You're mistaken here. You don't want a list comprehension. You use list comprehensions when you need to build new lists. That's not what you want to do here. You want to assign a certain value to name_list depending on a condition. This can be done using Python's or operator. The or operator is short-circuited, and returns the first 'truthy' value it evaluates: name_list = [x for x in list] or "n\a" However, I would recommended being careful using the above code, as it can be confusing for people who aren't familiar with it. Depending on your case, it might be better to be more explicit and break the above code into two steps: tmp = [x for x in list] name_list = tmp if tmp else "n\a"
accepted answer of: http://stackoverflow.com/q/50660972
type: Answer
answers question: http://stackoverflow.com/q/50660972
has comment: http://stackoverflow.com/comment/88332868
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88332945
has comment: http://stackoverflow.com/comment/88359455
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/51013449
answers question: http://stackoverflow.com/q/50634131
score: 1
has body: For plotly its important to sort your data by your x axis first. In pandas you can sort like this: df_sorted = df.sort_values(by=['timestamp'])
upvote count: 1
downvote count: 0
type: Answer

http://stackoverflow.com/q/50593476
has title: The warning "Unused variable 'subdirs'" when written in a function
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50593629
type: Question
tagged with: debugging
tagged with: function
score: 0
has body: For a reason that I cannot resolve, my "subdirs" variable in my first for loop becomes an "unused variable" when it is written inside a function, which results in a incomplete search of my directory to achieve the goal of the function. But when it is not part of a function, it's recognized as a variable and my code is able to successfully search the entire directory and performed the desired tasks. I'm relatively new to python, please let me know how I can fix my function so "subdirs" will be recognized as a variable. Thanks a lot! My For Loop With "Subdirs" Within a Function import os def function(rootdir, keyPhrases): path = rootdir # Enter the root directory you want to search from key_phrases = [keyPhrases] # Enter here the key phrases in the lines you hope to find # This for loop allows all sub directories and files to be searched for (path, subdirs, files) in os.walk(path): files = [f for f in os.listdir(path) if f.endswith('.txt') or f.endswith('.log')] # Specify here the format of files you hope to search from (ex: ".txt" or ".log") files.sort() # file is sorted list files = [os.path.join(path, name) for name in files] # Joins the path and the name, so the files can be opened and scanned by the open() function # The following for loop searches all files with the selected format for filename in files: # Opens the individual files and to read their lines with open(filename) as f: f = f.readlines() # The following loop scans for the key phrases entered by the user in every line of the files searched, and stores the lines that match into the "important" array for line in f: for phrase in key_phrases: if phrase in line: print(line) break print("The end of the directory has been reached, if no lines are printed then that means the key phrase does not exist in the root directory you entered.") My For Loop With "Subdirs"By Itself import os path = r"D:\(Chosen Root Directory)" key_phrases = ["example_keyPhrase1"] # Enter here the key phrases in the lines you hope to …
answer count: 1
tagged with: python
tagged with: python-3.x

http://stackoverflow.com/q/50631050
has answer: http://stackoverflow.com/a/50631206
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
has body: My Ubuntu 16.04 LTS laptop refuses to import pandas. I have tried re installing and updating pandas countless times. I use a list to load all my libraries. To make sure there was not a conflict in libraries or compatibility issue I reloaded every element on my script on this local machine AND simultaineously on an Ubuntu 16.04.4 x64 cloud server. When I tried to import pandas on the cloud server it worked no problem. When I tried to import pandas on my local machine I continued to get this error. Then I tried installing pandas using pip instead of conda and it still refused to import however the error changed. Please let me know if you have any suggestions or need any additional information. import pandas as pd ModuleNotFoundError Traceback (most recent call last) ModuleNotFoundError: No module named 'pandas.core.dtypes.common' ===================================================================== After pip install: import pandas as pd ImportError Traceback (most recent call last) ImportError: cannot import name 're_type'
has comment: http://stackoverflow.com/comment/88273595
type: Question
accepted answer: http://stackoverflow.com/a/50631206
tagged with: anaconda
has title: Local Ubuntu Machine Refuses to import Pandas due to unfound Module 'pd.core.dtypes.common'
has comment: http://stackoverflow.com/comment/88272593
tagged with: pandas
has comment: http://stackoverflow.com/comment/88272232
has comment: http://stackoverflow.com/comment/88272117
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/50607466
score: 0
has title: Filtering Rows from Multi-Header DataFrame by values from column
type: Question
tagged with: dataframe
has body: I'm building a Python script to do the following: List CSVs in directory Read single CSV file to DataFrame -> "data" (rows 2 (Parameter Name) and 3 (Parameter Unit) are defined as header). Only keep rows if value in columns "TMOD1", "TMOD2", "TMOD3" and "TMOD4" are 0 (if one is not 0, the entire row has to go) Drop all columns (-> parameters) with the unit "bit" Drop all rows with more than e.g. 10 "NaN" values Append filtered DataFrame "data" to DataFrame "result" Iterate steps 2-7 for all CSV files Save resulting DataFrame "result" as new CSV file I'm stuck at how to implement steps 3 and 4, everything else works fine. I've tried the following for step 3: data = data[(data.TMOD1 == 0) &amp; (data.TMOD2 == 0) &amp; (data.TMOD3 == 0) &amp; (data.TMOD4 == 0)] And the following for step 4: data.drop(labels='bit', axis=1, level=1, inplace=True) Step 4 works perfectly when leaving out Step 3 and using a multi header row DataFrame. However, Step 3 only works when switching to a single header row DataFrame - in which case Step 4 obviously won't work. I guess I messed up with calling the correct header level.
tagged with: filter
tagged with: pandas
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88225894
has comment: http://stackoverflow.com/comment/88224639
has answer: http://stackoverflow.com/a/50628630
tagged with: python

http://stackoverflow.com/comment/88174308
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50582179
has text: Please refer attached images - Input file & Output file

http://stackoverflow.com/comment/88172670
has text: definitely, makes sense in what you shared, i was looking for the same info.
score: 0
comment on: http://stackoverflow.com/a/50580215
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50588257
tagged with: heatmap
tagged with: bokeh
has answer: http://stackoverflow.com/a/50933295
type: Question
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: holoviews
tagged with: python
has title: holoviews/bokeh gridline issue
has body: I am attempting to make a heat map with holoviews (currently using the bokeh backend). I have a data frame ('dep_df') with 3 columns: X, Y, type. X and Y are the dimension labels, and type is a categorical variables b/n 0 and n (where n is an integer). Here's my code: dep_hm = hv.HeatMap(dep_df"X", "Y", "type", label="DEP population") TOOLS = ['hover'] colors = palettes.d3['Category20b'][5] %%opts HeatMap [width=300, height=300, xaxis=None, yaxis=None, show_grid=True] grid_style = {'grid_line_color': 'white', 'grid_line_width': 1.5} dep_hm.options(cmap=ListedColormap(colors), gridstyle=grid_style, tools=TOOLS, invert_axes=True) The plot looks correct in Jupiter notebook except that the ygrid lines don't show (only xgrid), and its showing all tools instead of just 'hover' as I specified. Even with the grid lines that do show, there's always a missing gridline exactly in the middle (have had that issue even in straight bokeh implementations of this heatmap. Another issue is that I've tried saving the file to HTML using both Bokeh.io and renderer.save() and in both cases, all formatting options are not executed (like not showing the axes, inverting the axes, and not showing full toolbar options). it seems to just save the plot with default options. Thanks for your help.

http://stackoverflow.com/q/50597139
has answer: http://stackoverflow.com/a/63816226
tagged with: bar-chart
has answer: http://stackoverflow.com/a/50597612
favorite count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/110404231
upvote count: 4
tagged with: plotly
has title: How to plot 3D Bar chart/ Pie Chart/ Donut using Plotly
type: Question
has body: I have found code to make bar charts and pie charts in plotly also other 3D plots. A simple bar chart works like this: from plotly.offline import plot from plotly.graph_objs import * trace1 = Bar( x=['cats', 'dogs', 'monkeys'], y=[20, 14, 23] ) data = Data([trace1]) plot(data) Is there any option available in plotly to plot this bar graph in 3D layout. Also for pie chart/donut also?
answer count: 2
tagged with: pie-chart
tagged with: 3d
score: 4

http://stackoverflow.com/comment/88326689
type: AnswerComment
has text: I should also mention that ideally I want to know if it is possible to pass in my_var once for the parent class, then have all children classes use this without passing it in as an argument themselves. But my_var also is only evaluated at run time so I don't know if this is possible.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50658115

http://stackoverflow.com/q/50579596
tagged with: pandas-groupby
has comment: http://stackoverflow.com/comment/88168398
linked to: http://stackoverflow.com/q/21767900
has comment: http://stackoverflow.com/comment/88168460
duplicate of: http://stackoverflow.com/q/21767900
has comment: http://stackoverflow.com/comment/88168668
type: UnansweredQuestion
tagged with: seaborn
has comment: http://stackoverflow.com/comment/88168636
has body: My data is being grouped correctly. df_RFQ_by_Salesperson = df[ (df['state'].str.contains('Done')) ]'sales_person_name2', 'rfq_qty', 'rfq_qty_CAD_Equiv', 'state' .copy() df_RFQ_by_Salesperson = df_RFQ_by_Salesperson.groupby('sales_person_name2').agg({'state': 'size','rfq_qty': 'sum', 'rfq_qty_CAD_Equiv': 'sum'}) df_RFQ_by_Salesperson['Percentage'] = df_RFQ_by_Salesperson.rfq_qty_CAD_Equiv / df_RFQ_by_Salesperson.rfq_qty_CAD_Equiv.sum() df_RFQ_by_Salesperson = df_RFQ_by_Salesperson.rename(columns={'state':'Done Trades'}, level=0) # rename the column header in the groupby display(df_RFQ_by_Salesperson.sort_values('Percentage',ascending=False)) sales_person_name2 Done Trades rfq_qty rfq_qty_CAD_Equiv Percentage MP 11 214400000.0 3.045802e+08 0.258089 AC 22 228800000.0 2.648099e+08 0.224390 YJ 7 202500000.0 2.490527e+08 0.211038 RW 18 129000000.0 1.693008e+08 0.143459 AY 171 118366000.0 1.189635e+08 0.100805 RL 47 78617000.0 7.342725e+07 0.062219 But when I try to visualize with sns.countplot, it appears the grouped by column is not in the column list hence an error is raised. display(df_RFQ_by_Salesperson.columns) Index(['Done Trades', 'rfq_qty', 'rfq_qty_CAD_Equiv', 'Percentage'], dtype='object') # # Visualisation ax = sns.countplot( x='sales_person_name2', data=df_RFQ_by_Salesperson, # Order by the count order = df_RFQ_by_Salesperson['sales_person_name2'].value_counts().index, color=plot_colour ) for label in ax.xaxis.get_ticklabels(): label.set_rotation(90) plt.show() KeyError: 'sales_person_name2' ---&gt; 22 order = df_RFQ_by_Salesperson['sales_person_name2'].value_counts().index, Is there a way to force python to include sales_person_name2 in the datarame?
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/88168499
type: Question
has comment: http://stackoverflow.com/comment/88168535
has title: Groupby result does not return grouped column hence errors when using countplot
tagged with: dataframe
score: 0

http://stackoverflow.com/a/67214552
answers question: http://stackoverflow.com/q/50595573
type: Answer
has body: Looking at the official test code for Python on GitHub samples/python/stitching.py, you can use Stitcher_PANORAMA or Stitcher_SCANS. You can always check the test code of any module, like modules/stitching/misc/python/test in this case. stitcher = cv.Stitcher.create(cv.Stitcher_PANORAMA)
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/50557166
upvote count: 2
answers question: http://stackoverflow.com/q/50556940
downvote count: 0
has body: You can avoid explicit for loops by filtering for the necessary columns and then using pd.DataFrame.join to join an empty dataframe: new_cols = df.columns[df.columns.str.startswith('aa')] + '_new' df = df.join(pd.DataFrame(columns=new_cols)) print(df) name area aa2 ab1 aa7 ac3 time type aa2_new aa7_new 0 CAN 11 0.5 1.2 0.4 2.1 7:21 H NaN NaN 1 SPA 22 0.4 1.4 0.5 2.5 6:45 M NaN NaN 2 USP 21 0.7 1.1 0.6 2.5 3:14 G NaN NaN 3 COM 13 0.1 1.9 0.2 2.2 8:22 D NaN NaN 4 MAP 16 0.3 1.8 0.1 2.4 3:11 S NaN NaN The problem with your code is you do not assign a value to your series, and this is what tells pandas to create a new column. Your subsequent question should be asked separately, if it hasn't already been answered elsewhere.
type: Answer
score: 2

scatter-plot
type: Tag
tags question: http://stackoverflow.com/q/50619380
tag name: scatter-plot

http://stackoverflow.com/q/50576194
has answer: http://stackoverflow.com/a/50576276
tagged with: python
has answer: http://stackoverflow.com/a/50576263
has comment: http://stackoverflow.com/comment/88161521
tagged with: math
upvote count: 1
has body: I have a list of base2 values (5 digits each) : [10000, 10001, 10010, 10011, 10100, 10101, 10110, 10111, 11000, 11001, 11010, 11011, 11100, 11101, 11110, 11111] Is there a way to do math with them in base2? For Example, 10001 + 1110 = 11111 And 10000 - 1 = 1111. EDIT : I only care about addition and subtraction.
type: Question
has answer: http://stackoverflow.com/a/50577145
has title: how to use base2 in math
answer count: 6
score: -1
tagged with: python-2.7
has answer: http://stackoverflow.com/a/50576427
has answer: http://stackoverflow.com/a/50576214
has answer: http://stackoverflow.com/a/50576232
favorite count: 0
tagged with: binary
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/comment/88358233
has text: Well, getting rid of a '-' and trailing whitespace seems easier than a regex for a random sentence...
comment on: http://stackoverflow.com/q/50674031
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88106609
comment on: http://stackoverflow.com/q/50547708
type: QuestionComment
type: Comment
has text: Welcome to SO. Please take the time to read [ask] and the other links found on that page. There may be more than one way. Dataframe plots are a ['simple wrapper' for Matplotlib.pyplot.plt](http://pandas.pydata.org/pandas-docs/stable/visualization.html). You can typically find a feature you want by browsing [Matplotlib's gallery](https://matplotlib.org/gallery/index.html) It also has [excellent Tutorials](https://matplotlib.org/tutorials/index.html). which are worth investing time with.
score: 1

http://stackoverflow.com/comment/88407392
type: Comment
comment on: http://stackoverflow.com/a/50698724
has text: I used File.exists and both python.exe and .py file are not found.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88303830
score: 0
type: AnswerComment
has text: Just to add some context, `bkcharts` has alwasy been deprecated/unsupported. It was all the `bokeh.charts` code (including `Bar`) that got removed. Since then, `vbar` and `vbar_stack` and more have been added to the stable `bokeh.plotting` API, and those are now better and more featureful than the old `bokeh.charts` ever was. HoloViews is a separate project that builds on top of Bokeh. It's entirely optional, but many people like its concise, high level, data-centric API, especially for exploratory work.
type: Comment
comment on: http://stackoverflow.com/a/50642536

http://stackoverflow.com/comment/88385910
comment on: http://stackoverflow.com/a/50682930
has text: I mean not a WM_LBUTTONDOWN/WM_CLICK handler itself but the code which enables this handler. It may run after some trigger. Can it be the app issue/bug?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/50666261
type: Answer
answers question: http://stackoverflow.com/q/50664124
has body: I'm not sure if your pyjnius is compiled properly. However, the bigger problem is that your pyjnius code will only work on Android - org.renpy.android.Hardware does not exist on the desktop. This is usually the case with pyjnius, although it can work on the desktop there isn't much point in having it there if you only need it for Android. I would usually resolve this by conditionally importing and using pyjnius only if running on Android.
has comment: http://stackoverflow.com/comment/88347093
score: 0
has comment: http://stackoverflow.com/comment/88342814

http://stackoverflow.com/comment/88156087
comment on: http://stackoverflow.com/q/50573241
score: 0
has text: the library is already installed in R and i have coded in R too but now i want to call that in Python. Is there any other way ?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/121621372
type: Comment
comment on: http://stackoverflow.com/a/53685910
type: AnswerComment
score: 0
has text: This is a great option for non command line apps. I just used is as `C:\Miniconda3\pythonw.exe C:\Miniconda3\cwp.py C:\Miniconda3\envs\env0 app.exe` . Replace env0 and app.exe with your respective values and no cmd.exe will be shown

http://stackoverflow.com/a/50657542
downvote count: 0
has comment: http://stackoverflow.com/comment/88325443
score: 1
has comment: http://stackoverflow.com/comment/88325128
answers question: http://stackoverflow.com/q/50657403
type: Answer
has comment: http://stackoverflow.com/comment/88325323
accepted answer of: http://stackoverflow.com/q/50657403
upvote count: 1
has comment: http://stackoverflow.com/comment/88325186
has comment: http://stackoverflow.com/comment/88325083
has body: The answer is in you Error message. I haven't used boto in a while but without even trying to run your example you can tell the problem is here: b_asin = b.GetMatchingProductForIdResult.Products.Product.MarketplaceASIN The error says: AttributeError: 'list' object has no attribute 'Products' working backwards we can tell that python is trying to access an attribute called Products but the object is a list. So b.GetMatchingProductForIdResult is a list. Try printing it and see what you get. Iterate over it and print the elements or print the dir of the first element to see the attributes of each. print(dir(b.GetMatchingProductForIdResult[0])) The Traceback is your friend, learn it, love it, live it. Now to MWS specifically: Amazon provides an xsd file that describes the response found here. This should tell you exactly what you're dealing with. More generally it describes the elements here.
type: AcceptedAnswer

http://stackoverflow.com/comment/88137843
comment on: http://stackoverflow.com/a/50563697
type: Comment
score: 2
has text: If there is multiple values it return something else, not divide by shifted column.
type: AnswerComment

http://stackoverflow.com/a/50557097
downvote count: 0
has comment: http://stackoverflow.com/comment/88125760
has comment: http://stackoverflow.com/comment/88125264
has comment: http://stackoverflow.com/comment/88125299
has comment: http://stackoverflow.com/comment/88125799
has body: The problem only occurs when the element editor is activated, which means that in some way the view is not notified of the changes in the model. At that time, dataChanged of the model is not sent to the proxy. An alternative solution is to call the proxy dataChanged and change the state of the expansion or contraction to refresh the view, at the end restore the state of expansion and contraction. def add_row_click(self): index = self.treeView.selectionModel().selectedIndexes()[0] self.treeView.setCurrentIndex(index) self.proxy_model.insertRows(self.proxy_model.rowCount(index), 1, index) self.proxy_model.setData(self.proxy_model.index(self.proxy_model.rowCount(index) - 1, 0, index), "new_test") self.proxy_model.dataChanged.emit(index, index) v = self.treeView.isExpanded(index) self.treeView.setExpanded(index, not v) self.treeView.setExpanded(index, v) In conclusion if a child is inserted but the view is not updated correctly, this can be verified using another QTreeView and setting self.model as a model.
type: Answer
has comment: http://stackoverflow.com/comment/88125322
has comment: http://stackoverflow.com/comment/88125681
has comment: http://stackoverflow.com/comment/88125646
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50556719
accepted answer of: http://stackoverflow.com/q/50556719
has comment: http://stackoverflow.com/comment/88125326
has comment: http://stackoverflow.com/comment/88125219
type: AcceptedAnswer

http://stackoverflow.com/q/50663482
tagged with: python-3.x
type: UnansweredQuestion
tagged with: data-visualization
tagged with: python
has answer: http://stackoverflow.com/a/50663532
has answer: http://stackoverflow.com/a/50664228
has title: Python Horizontal Floating Stacked Bar
type: Question
answer count: 2
has body: I like to know how to produce a diagram like the following in Python. Which is the best library to use? Seaborn? Pandas? Can anyone point me to some sample code that can produce the diagram.
score: 0

http://stackoverflow.com/q/50682144
has title: Display Surface quit error when quitting
accepted answer: http://stackoverflow.com/a/50682493
answer count: 1
has body: I made a pygame program what is working fine, but when I try to quit it, error occurs: pygame.error: display Surface quit, and show the code part: DS.blit(bg, (back_x - bg.get_rect().width, 0)). I use quit() command in my events and also at the end of the loop. Can't figure out where is the problem. import pygame, os, random pygame.init() pygame.mixer.init() W, H = 800,600 HW, HH = W/2,H/2 WHITE = (255,255,255) PURPLE = (139,34,82) FPS = 60 DS = pygame.display.set_mode((800, 600)) pygame.display.set_caption('Purpleman') clock = pygame.time.Clock() #Allalaadimised bg = pygame.image.load(os.path.join('Pildid', 'Taust3.png')) bg = pygame.transform.scale(bg, (2000, 600)) startscreen = pygame.image.load(os.path.join('Pildid', 'Start.png')) startscreen = pygame.transform.scale(startscreen, (800, 600)) endscreen = pygame.image.load(os.path.join('Pildid', 'dead.png')) endscreen = pygame.transform.scale(endscreen, (800, 600)) PLAYER_SHEET = pygame.image.load(os.path.join('Pildid', 'karakter.png')).convert_alpha() menuu = pygame.mixer.Sound(os.path.join('Helid', 'Taust_laul.ogg')) ohno = pygame.mixer.Sound(os.path.join('Helid', 'ohno.ogg')) sad = pygame.mixer.Sound(os.path.join('Helid', 'sad.ogg')) pygame.mixer.music.load(os.path.join('Helid', 'taustalaul.ogg')) pygame.display.set_icon(bg) # Sprite sheeti loikamine ja lisamine listi PLAYER_IMAGES = [] width = PLAYER_SHEET.get_width() / 4 height = PLAYER_SHEET.get_height() for x in range(4): PLAYER_IMAGES.append(PLAYER_SHEET.subsurface(x*width, 0, width, height)) class Player(pygame.sprite.Sprite): '''Mangija''' def __init__(self, x, y, py): super(Player,self).__init__() self.x = x self.y = y self.jumping = False self.platform_y = py self.velocity_index = 0 self.velocity = list([(i/ 1.5)-25 for i in range (0,60)]) #huppe ulatus ja kiirus self.frame_index = 0 self.image = PLAYER_IMAGES[self.frame_index] #kaadri valimine self.rect = self.image.get_rect() self.mask = pygame.mask.from_surface(self.image) #hitbox def do_jump(self):…
tagged with: python
tagged with: pygame
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50682493
tagged with: pycharm
score: 0
type: Question

http://stackoverflow.com/comment/88401223
has text: I doubt that this is possible. Can't think of a query to do this in SQL, and as such it makes me believe that the same isn't possible through the Django ORM. But keep in mind that this could just be because I haven't looked deep enough.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50694818

http://stackoverflow.com/comment/88117039
type: Comment
has text: My one complaint about this question is related to this statement of yours: *"If you only inherit from one class super you do not need super"*. That is definitely true, but it's still good practice to use `super`, if only because it lets you avoid having to hard-code the parent class's name. I fear that the way you phrased that sentence might discourage people from using `super` with no good reason.
comment on: http://stackoverflow.com/a/50550877
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88194878
has text: No. It is python3. Although my system is x64 like I said, it seems pandas is using int32 by default. Using @ALollz suggestion worked.
type: QuestionComment
comment on: http://stackoverflow.com/q/50592523
type: Comment
score: 0

http://stackoverflow.com/q/50652373
has body: I have a pandas dateframe with stock market data. There is a date column ('date'). When trying to access a date using a string, I receive: KeyError: 'the label [1981-02-17 00:00:00] is not in the [index]' I explicitly set the index to be a datetime index by calling self.data['date'] = pandas.to_datetime(self.data['date'], format="%Y-%m-%d") self.data.set_index(pandas.DatetimeIndex(self.data['date'], inplace=True)) Here's my class: class ohlcData: def __init__(self, ticker=None, csv=None, intrinio=False): if ticker is not None: self.ticker = ticker.upper() else: self.ticker = None if csv is not None: name_len = csv.find(".csv") if name_len is -1: raise ValueError("CSV file should be named ticker.csv where ticker is the stock ticker.") else: self.ticker = csv[0:name_len].upper() self.data = pandas.read_csv(csv) self.data['date'] = pandas.to_datetime(self.data['date'], format="%Y-%m-%d") self.data.set_index(self.data['date'], inplace=True) if not intrinio: self.data = pandas.DataFrame() else: self.read_from_intrinio() Relevant excerpt of main: aapl = ohlcData(csv="aapl.csv") print(aapl.data.loc[datetime.date(1981, 2,17)]) Resulting in: KeyError: 'the label [1981-02-17] is not in the [index]' What am I doing wrong?
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/88315810
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88316412
has comment: http://stackoverflow.com/comment/88316223
tagged with: datetime
has comment: http://stackoverflow.com/comment/88315819
tagged with: python
has title: Issue with pandas.setindex() to datetime
tagged with: datetimeindex
has comment: http://stackoverflow.com/comment/88315868
answer count: 0
has comment: http://stackoverflow.com/comment/88316215
has comment: http://stackoverflow.com/comment/88316377
type: Question
has comment: http://stackoverflow.com/comment/88315855

http://stackoverflow.com/a/50640929
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/88315763
has body: It's example how to write Scrapy pileline in Django project. from &lt;YOU_APP_NAME&gt;.models import detikNewsItem class DetikAppPipeline(object): def process_item(self, item, spider): d, created = detikNewsItem.objects.get_or_create(breadcrumbs=item['breadcrumbs'], url=item['url']) if created: d.tanggal = item['tanggal'] d.penulis = item['penulis'] d.judul = item['judul'] d.berita = item['berita'] d.tag = item['tag'] d.save() return item By the way you need to run Scrapy in Django environment. There are several ways to do that: Using django-extensions module. Need to create new file: &lt;DJANG_PROJECT&gt;/scripts/__init__.py &lt;DJANG_PROJECT&gt;/scripts/run_scrapy.py With code inside: from scrapy.cmdline import execute execute(['run_scrapy.py', 'crawl', 'detik']) Another way is to use Django Managment. Need to create folders in project with file: &lt;folder_of_app&gt;/management/commands/__init__.py &lt;folder_of_app&gt;/management/commands/scrapy.py scrapy.py file should contain code: from scrapy.cmdline import execute from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Run scrapy.' def add_arguments(self, parser): parser.add_argument('arguments', nargs='+', type=str) def handle(self, *args, **options): args = [] args.append('scrapy.py') args.extend(options['arguments']) execute(args) It allow to run Scrapy in Django environment like this: python manage.py scrapy crawl detik python manage.py scrapy shell 'https://news.detik.com/indeks/all/?date=02/28/2018'
has comment: http://stackoverflow.com/comment/88296333
type: Answer
has comment: http://stackoverflow.com/comment/88294151
answers question: http://stackoverflow.com/q/50637920
score: 5

http://stackoverflow.com/q/50592076
answer count: 1
linked to: http://stackoverflow.com/q/34308337
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/34308337
tagged with: python
has answer: http://stackoverflow.com/a/50592104
tagged with: list
has body: What is the best way in python to convert a list of small length (3 or 4) into variables. Actually I want to do the opposite of creating a list like this in Python 3. some_python_list=[a,b,c,d] So what I want is something which does a,b,c,d=some_python_list.decompose(4) #while I know alist is of length 4 So I can save myself from a=some_python_list[0] b=some_python_list[1] c=some_python_list[2] d=some_python_list[3] or a,b,c,d=some_python_list[0],some_python_list[1],some_python_list[2],some_python_list[3]
downvote count: 3
upvote count: 1
type: Question
score: -2
has comment: http://stackoverflow.com/comment/88193471
has title: Decomposing python list i.e creating variables from python list

http://stackoverflow.com/a/50584293
has body: In python3 map is a generator. If you want to reuse the variable use selectedvalidations='1,2,3,4,5,6,7' x=list(map(int,selectedvalidations.split(','))) #Encapsulate map in list print(x)
score: 1
has comment: http://stackoverflow.com/comment/88177724
upvote count: 1
has comment: http://stackoverflow.com/comment/88179995
has comment: http://stackoverflow.com/comment/88177712
downvote count: 0
has comment: http://stackoverflow.com/comment/88180077
answers question: http://stackoverflow.com/q/50584218
type: Answer

http://stackoverflow.com/comment/88359448
type: QuestionComment
comment on: http://stackoverflow.com/q/50674757
has text: You're gonna need some kind of temporary variable; there's no way around it. List comprehensions aren't suited for this kind of thing.
score: 0
type: Comment

http://stackoverflow.com/q/50649853
upvote count: 177
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/70498636
tagged with: dataframe
has answer: http://stackoverflow.com/a/78160454
has body: These are my two dataframes saved in two variables: &gt; print(df.head()) &gt; club_name tr_jan tr_dec year 0 ADO Den Haag 1368 1422 2010 1 ADO Den Haag 1455 1477 2011 2 ADO Den Haag 1461 1443 2012 3 ADO Den Haag 1437 1383 2013 4 ADO Den Haag 1386 1422 2014 &gt; print(rankingdf.head()) &gt; club_name ranking year 0 ADO Den Haag 12 2010 1 ADO Den Haag 13 2011 2 ADO Den Haag 11 2012 3 ADO Den Haag 14 2013 4 ADO Den Haag 17 2014 I'm trying to merge these two using this code: new_df = df.merge(ranking_df, on=['club_name', 'year'], how='left') The how='left' is added because I have less datapoints in my ranking_df than in my standard df. The expected behaviour is as such: &gt; print(new_df.head()) &gt; club_name tr_jan tr_dec year ranking 0 ADO Den Haag 1368 1422 2010 12 1 ADO Den Haag 1455 1477 2011 13 2 ADO Den Haag 1461 1443 2012 11 3 ADO Den Haag 1437 1383 2013 14 4 ADO Den Haag 1386 1422 2014 17 But I get this error: ValueError: You are trying to merge on object and int64 columns. If you wish to proceed you should use pd.concat But I do not wish to use concat since I want to merge the trees not just add them on. Another behaviour that's weird in my mind is that my code works if I save the first df to .csv and then load that .csv into a dataframe. The code for that: df = pd.DataFrame(data_points, columns=['club_name', 'tr_jan', 'tr_dec', 'year']) df.to_csv('preliminary.csv') df = pd.read_csv('preliminary.csv', index_col=0) ranking_df = pd.DataFrame(rankings, columns=['club_name', 'ranking', 'year']) new_df = df.merge(ranking_df, on=['club_name', 'year'], how='left') I think that it has to do with the index_col=0 parameter. But I have no idea to fix it without having to save it, it doesn't matter much but is kind of an annoyance that I have to do that.
accepted answer: http://stackoverflow.com/a/50649933
has answer: http://stackoverflow.com/a/61487375
has comment: http://stackoverflow.com/comment/109214579
tagged with: pandas
has answer: http://stackoverflow.com/a/59668007
has answer: http://stackoverflow.com/a/60313656
favorite count: 0
has answer: http://stackoverflow.com/a/56429102
has answer: http://stackoverflow.com/a/60515993
linked to: http://stackoverflow.com/q/22676081
has title: Trying to merge 2 dataframes but get ValueError
has answer: http://stackoverflow.com/a/76399793
answer count: 10
tagged with: python
possible better answer: http://stackoverflow.com/a/60515993
score: 176
has answer: http://stackoverflow.com/a/57776579
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50649933

pytorch
tags question: http://stackoverflow.com/q/50546862
tags question: http://stackoverflow.com/q/50652579
tags question: http://stackoverflow.com/q/50652874
tags question: http://stackoverflow.com/q/50544730
tags question: http://stackoverflow.com/q/50654505
tags question: http://stackoverflow.com/q/50665141
tags question: http://stackoverflow.com/q/50621786
tags question: http://stackoverflow.com/q/50611420
tags question: http://stackoverflow.com/q/50657449
tags question: http://stackoverflow.com/q/50570697
tag name: pytorch
type: Tag
tags question: http://stackoverflow.com/q/50541851
tags question: http://stackoverflow.com/q/50562552
tags question: http://stackoverflow.com/q/50663803
tags question: http://stackoverflow.com/q/50588958
tags question: http://stackoverflow.com/q/50605205
tags question: http://stackoverflow.com/q/50666440
tags question: http://stackoverflow.com/q/50658111
tags question: http://stackoverflow.com/q/50586687
tags question: http://stackoverflow.com/q/50612899

http://stackoverflow.com/comment/88364476
comment on: http://stackoverflow.com/a/50633805
type: Comment
score: 0
type: AnswerComment
has text: Giving the same input directly to `Rule` (e.g., `Rule(env, ...)`) and then trying to print the rule gives `Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.7/site-packages/clips/agenda.py", line 223, in __repr__ string = lib.EnvGetDefrulePPForm(self._env, self._rule) TypeError: initializer for ctype 'void *' must be a cdata pointer, not Environment`

http://stackoverflow.com/q/50618639
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/1207406
tagged with: list
has comment: http://stackoverflow.com/comment/88247037
downvote count: 2
has answer: http://stackoverflow.com/a/50619387
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50618694
answer count: 3
has comment: http://stackoverflow.com/comment/88247014
has answer: http://stackoverflow.com/a/50618977
has body: a = [[' 0 ', '*X*', '*Y*', '*Z*'], [' 0 ', '*X*', '*Y*', '*Z*'], [' 0 ', '*X*', '*Y*', '*Z*']] for i in a: for j in i: if '*' in j: i.remove(j) for i in range(len(a)): for j in range(len(a[i])): if '*' in a[i][j]: del a[i][j] I try to delete the item contain star in the list, but the first loop will give me out of range error, and the second loop will still have y does not delete, how do I fix the problem? Thank you very much
favorite count: 0
has title: How do I remove an item from a list where I am getting an index out of range error?
score: -1
tagged with: python-3.x

http://stackoverflow.com/q/50549112
has body: How do I create a function that will let me input a word, and it will execute to create a dictionary that counts individual letters in the code. I would want it to display as a dictionary, for example, by inputting 'hello' it will display {'e': 1, 'h': 1, 'l': 2, 'o': 1} I AM ALSO required to have 2 arguments in the function, one for the string and one for the dictionary. THIS IS DIFFERENT to the "Counting each letter's frequency in a string" question. For example, I think I would have to start as, d = {} def count(text, d ={}): count = 0 for l in text: if l in d: count +=1 else: d.append(l) return count But this is incorrect? Also Would i need to set a default value to text, by writing text ="" in case the user does not actually enter any word? Furthermore, if there were existing values already in the dictionary, I want it to add to that existing list. How would this be achieved? Also if there were already existing words in the dictionary, then how would you add onto that list, e.g. dct = {'e': 1, 'h': 1, 'l': 2, 'o': 1} and now i run in terminal >>> count_letters('hello', dct) the result would be {'e': 2, 'h': 2, 'l': 4, 'o': 2}
linked to: http://stackoverflow.com/q/10806866
score: -1
linked to: http://stackoverflow.com/q/1132941
answer count: 3
has comment: http://stackoverflow.com/comment/88109159
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88109332
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/10806866
has comment: http://stackoverflow.com/comment/88109238
upvote count: 0
has answer: http://stackoverflow.com/a/50549302
has answer: http://stackoverflow.com/a/50549293
has comment: http://stackoverflow.com/comment/88109121
has title: Creating a function in Python that counts number of letters in a dictionary
type: Question
has answer: http://stackoverflow.com/a/50549137

http://stackoverflow.com/comment/88341429
comment on: http://stackoverflow.com/q/50665681
has text: Yes, I am trying to draw N random zero indices, but if I take the compliment of all the non zero indices (2312497) to get all the indices that contains zeros 281903 * 281903 = 79466988912 - 2312497 = 79.466.988.912. python just throws an out of memory error
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50635826
type: Question
tagged with: python-2.7
answer count: 3
has answer: http://stackoverflow.com/a/50635852
downvote count: 0
has body: Suppose I have the following dictionary. params = {'a': 'aaa', 'b': 'bbb', 'c': 'ccc', 'd': 'ddd-hoge'} When printing using the following script, &gt;&gt;&gt; print("1: {a} 2: {b} 3: {c} 4: {d}.split('-')[0]".format(**params)) the output will be "1: aaa 2: bbb 3: ccc 4: ddd-hoge.split('-')[0]" How should I modify the script to get the same output as the following? "1:aaa 2:bbb 3:ccc 4:ddd"
favorite count: 0
has title: Python: How to format a string with split function?
upvote count: 2
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88281529
score: 2
has answer: http://stackoverflow.com/a/50635886
has comment: http://stackoverflow.com/comment/88281557
has answer: http://stackoverflow.com/a/50635898

http://stackoverflow.com/a/50655804
has comment: http://stackoverflow.com/comment/88321647
score: 0
accepted answer of: http://stackoverflow.com/q/50643465
type: Answer
answers question: http://stackoverflow.com/q/50643465
type: AcceptedAnswer
has body: GLIBCXX_3.4.22' not found You can unpack libstdc++.so.6 -&gt; libstdc++.so.6.0.22 in e.g. your $HOME, and include it when you run the command : Example → export LD_LIBRARY_PATH=/home/[name]/libstdc++6_6.3.0_amd64:$LD_LIBRARY_PATH &amp;&amp; import matlab.engine what is ... [command] [command] means "any command" to be used with the libstdc++.so.6 in $HOME. About the folder libstdc++6_6.3.0_amd64/ : You can rename to e.g. lib64 to have a shorter file name : /home/[name]/lib64/ → export LD_LIBRARY_PATH=/home/[name]/lib64:$LD_LIBRARY_PATH &amp;&amp; import matlab.engine

http://stackoverflow.com/comment/88141874
score: 0
comment on: http://stackoverflow.com/q/50559570
type: Comment
type: QuestionComment
has text: There are already [124 questions for classifier string features](https://stackoverflow.com/search?q=is%3Aquestion+classifier+string+features), mostly Python. Which one should be canonical?

http://stackoverflow.com/q/50691154
has answer: http://stackoverflow.com/a/50691750
tagged with: pdftotext
has title: Why is this code not able to extract unicode text from PDFs properly?
tagged with: http://stackoverflow.com/tag/pdf
answer count: 1
downvote count: 0
tagged with: unicode
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
has body: I want to extract the text contained in a PDF. This is my code to do this: import textract doc = textract.process(r"C:\path\to\the\downloaded.pdf", encoding = 'raw_unicode_escape') f = open('pdf_to_text.txt','wb') f.write(doc) This is the output: \u53cb\u90a6\u4fdd\u96aa\u63a7\u80a1\u6709\u9650\u516c\u53f8 REAL LIFE REAL IMPACT A NNUA L REP ORT 2015 STOCK CODE : 1299 VISION &amp; PURPOSE Our Vision is to be the pre-eminent life insurance provider in the Asia-Pacific region. That is our service to our customers and our shareholders. Our Purpose is to play a leadership role in driving economic and social development across the region. That is our service to societies and their people. ABOUT AIA AIA Group Limited and its subsidiaries (collectively \u201cAIA\u201d or the \u201cGroup\u201d) comprise the largest independent publicly listed pan-Asian life insurance group. It has a presence in 18 markets in Asia-Paci\ufb01c \u2013 wholly-owned branches and subsidiaries in Hong Kong, Thailand, Singapore, Malaysia, China, Korea, the Philippines, Australia, Indonesia, Taiwan, ... ... ... ... ... ... As can be seen, it reads some of the "fancy" text (unicode? ascii?) properly, but not all. How do I fix this? I have tried 5 encoding schemes - utf-8 produces bad results, utf-16 produces the worst results converting everything to illegible text, ascii produces not-so-bad results but does leave behind a few characters, unicode_escape produces average results leaving quite a few illegible characters, and raw_unicode_escape also produces good results but leaves behind a few like ascii. This is the link to the PDF which I downloaded to the local drive for the analysis: https://www.aia.com/content/dam/group/en/docs/annual-report/aia-annual-report-2015-eng.pdf P.S. Another small unrelated issue is it keeps gaps between letters of a word at times, like A NNUA L REP ORT in the text snippet above. How can this be fixed? EDIT: I have found in Pages 10 and 11 of textract's documentation abou…
type: Question
tagged with: encoding

http://stackoverflow.com/comment/88108338
type: Comment
comment on: http://stackoverflow.com/a/50548747
has text: I will have certain cases where I will have spaces in values. Is there a way to resolve that?
type: AnswerComment
score: 0

http://stackoverflow.com/a/50655136
has body: You are looking for tf.gather_nd which will index based on an index array: # From documentation indices = [[0, 0], [1, 1]] params = [['a', 'b'], ['c', 'd']] output = ['a', 'd'] To use it in a Keras model make sure to wrap it in a Layer like Lambda.
accepted answer of: http://stackoverflow.com/q/50653044
answers question: http://stackoverflow.com/q/50653044
type: AcceptedAnswer
upvote count: 3
type: Answer
downvote count: 0
score: 3

xml.etree
type: Tag
tags question: http://stackoverflow.com/q/50627432
tag name: xml.etree

http://stackoverflow.com/comment/88279753
comment on: http://stackoverflow.com/a/50634655
type: Comment
has text: As I mentioned in AChampion's question, the savings from looping 1 time instead of 4 may not actually outweigh the cost of looping in Python and repeatedly indexing vs. looping in C (or maybe even calling something like `memchr` that may even be more optimized than that…), especially in CPython. It's definitely better in the sense of cleaner and more readable, but it may not be faster, which your answer implies that it is.
score: 1
type: AnswerComment

http://stackoverflow.com/q/50677656
type: AnsweredQuestion
has body: I have a test that I am running with: pytest --capture=no --verbose --rootdir=testing/ testing/tests/docker_test.py from /home/user/development/. The test checks if some containers are running and uses the default logging framework of Python 3.6. The logger inside the test file is configured as follows: logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logging.basicConfig(level=logging.INFO, stream=sys.stdout, format="%(asctime)s %(levelname)s %(message)s") Inside tests I am using the logger as follows: logger.info(f"TEST SUCCESSFUL: container {container_name} is running") logger.info(f"TEST SUCCESSFUL: all required containers are running") Inside testing (the root directory) I have a file pytest.ini: [pytest] log_level = INFO log_cli_level = INFO log_format = %(asctime)s %(levelname)s %(message)s log_cli_format = %(asctime)s %(levelname)s %(message)s log_date_format = %H:%M:%S log_cli_date_format = %H:%M:%S Basically I do not want any date to be in the timestamp and I want pytest to log live to the command line when I am running the tests. For one I am wondering what asctime stands for. It looks like "ascii time". I do not want a standardized timestamp, but instead the format I describe in the pytest.ini. That is why I also tried to use date, datetime and timestamp, instead of asctime, all resulting in an error. So I guess asctime is the only way to get a timestamp. However, pytest seems to ignore all the options I am setting in my pytest.ini file, although is indicates, that it found the file, when I am running the tests: cachedir: testing/.pytest_cache rootdir: /home/user/development/testing, inifile: pytest.ini How can I change the timestamp in pytest logging?
downvote count: 0
tagged with: pytest
type: Question
score: 4
tagged with: python-logging
has title: Pytest logging ignores options in pytest.ini
has answer: http://stackoverflow.com/a/50685453
accepted answer: http://stackoverflow.com/a/50685453
answer count: 1
favorite count: 0
tagged with: python
upvote count: 4
tagged with: logging

http://stackoverflow.com/a/50659368
answers question: http://stackoverflow.com/q/50659245
has body: Set the common index for both dataframes before using pd.DataFrame.sub: df_tot = df_tot.set_index('Wavelength') df_nap = df_nap.set_index('Wavelength') res = df_tot.sub(df_nap) If you require 'Wavelength' as a series rather than an index, you can call reset_index on the result: res = res.reset_index() However, there are certain benefits attached to storing a unique row-identifier as an index rather than a series. For example, more efficient lookup and merge functionality.
score: 1
upvote count: 1
downvote count: 0
type: Answer

http://stackoverflow.com/a/50688479
type: Answer
has comment: http://stackoverflow.com/comment/88387548
has body: The problem is that you cannot connect to a QTextEdit's focusOutEvent. It is not a signal but an event handler. You must override the class and emit a signal from the event handler. self.plainTextEdit = CustomTextEdit() self.plainTextEdit.focus_out.connect(lambda:self.check_input(Dialog14)) class CustomTextEdit(QtWidgets.QTextEdit): focus_out = QtCore.pyqtSignal() def __init__(self): super().__init__() def focusOutEvent(self, event): super().focusOutEvent(event) self.focus_out.emit()
accepted answer of: http://stackoverflow.com/q/50688163
upvote count: 1
has comment: http://stackoverflow.com/comment/88387003
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50688163

http://stackoverflow.com/q/50634857
type: Question
has answer: http://stackoverflow.com/a/50651123
has title: Different forms of genetic algorithim
has comment: http://stackoverflow.com/comment/88279955
downvote count: 0
answer count: 1
score: 1
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: I wrote a code that implements a simple genetic algorithm to maximize: f(x) = 15x - x^2 The function has its maximum at 7.5, so the code output should be 7 or 8 since the population are integers. When I run the code 10 times I get 7 or 8 around three times out of 10. What modification should I make to further improve the algorithm and what are different types of genetic algorithms? Here is the code: from random import * import numpy as np #fitness function def fit(x): return 15*x -x**2 #covert binary list to decimal number def to_dec(x): return int("".join(str(e) for e in x), 2) #picks pairs from the original population def gen_pairs(populationl, prob): pairsl = [] test = [0, 1, 2, 3, 4, 5] for i in range(3): pair = [] for j in range(2): temp = np.random.choice(test, p=prob) pair.append(populationl[temp].copy()) pairsl.append(pair) return pairsl #mating function def cross_over(prs, mp): new = [] for pr in prs: if mp[prs.index(pr)] == 1: index = np.random.choice([1,2,3], p=[1/3, 1/3, 1/3]) pr[0][:index], pr[1][:index] = pr[1][:index], pr[0][:index] for pr in prs: new.append(pr[0]) new.append(pr[1]) return new #mutation def mutation(x): for chromosome in x: for gene in chromosome: mutation_prob = np.random.choice([0, 1], p=[0.999, .001]) if mutation_prob == 1: #m_index = np.random.choice([0,1,2,3]) if gene == 0: gene = 1 else: gene = 0 #generate initial population randlist = lambda n:[randint(0,1) for b in range(1, n+1)] for j in range(10): population = [randlist(4) for i in range(6)] for _ in range(20): fittness = [fit(to_dec(y)) for y in population] s = sum(fittness) prob = [e/s for e in fittness] pairsg = gen_pairs(population.copy(), prob) mating_prob = [] for i in pairsg: mating_prob.append(np.random.choice([0,1], p=[0.4,0.6])) new_population = cross_over(pairsg, mating_prob) mutated = mutation(new_population) decimal_p = [to_dec(i)for i in population] decimal_new = [to_dec(i)for i in new_population] # print(decimal_p) # print(decimal_new) population = new_populat…
tagged with: genetic-algorithm

http://stackoverflow.com/comment/88379512
score: 0
type: Comment
has text: Did you write this yourself? Please be aware that there are numerous available resources for Python if you google "python pdf to text". Have you tried any of those?
comment on: http://stackoverflow.com/a/50684837
type: AnswerComment

http://stackoverflow.com/comment/88384249
type: QuestionComment
comment on: http://stackoverflow.com/q/50686866
has text: Well, like I say, you seem to be misunderstanding the relationship between JS and Django. There is no way that a template tag, which is executed on the backend, could be called by a JS script, which is executed on the front end long after the template has been rendered. But why do you need to "store" the file data in an HTML element? Why don't you upload it directly to Django, either via a form or via Ajax?
score: 0
type: Comment

http://stackoverflow.com/a/50599255
has comment: http://stackoverflow.com/comment/103186301
upvote count: 18
type: Answer
answers question: http://stackoverflow.com/q/50599045
downvote count: 0
has comment: http://stackoverflow.com/comment/88209004
has body: You can monkey patch this method as follows: class TestMOD(object): def testFunc(self, variable): var = variable self.something = var + 12 print(f'original {self.something}') def alternativeFunc(self, variable): var = variable self.something = var + 1.2 print(f'alternative {self.something}') if __name__ == '__main__': test_original = TestMOD() test_original.testFunc(12) TestMOD.testFunc = alternativeFunc test_alternate = TestMOD() test_alternate.testFunc(12) Output: original 24 alternative 13.2
score: 18
has comment: http://stackoverflow.com/comment/124136286

http://stackoverflow.com/a/50561251
downvote count: 0
answers question: http://stackoverflow.com/q/50561222
type: Answer
score: 4
has body: You need to use the input method: response = input("Enter your name:") (or raw_input for python 2)
upvote count: 4

http://stackoverflow.com/comment/88271936
type: Comment
has text: @Tom No problem
comment on: http://stackoverflow.com/a/50594789
type: AnswerComment
score: 0